<template>
  <div>
    <a-card>
      <a-form layout="vertical">
        <a-row :gutter="24">
          <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
            <a-form-item :label="$t('functional-analysis.top-btn.translation-flag')">
              <a-radio-group @change="translationFlagChange" :default-value="0">
                <a-radio :value="0">
                  {{ $t('functional-analysis.top-btn.untranslated') }}
                </a-radio>
                <a-radio :value="1">
                  {{ $t('functional-analysis.top-btn.translated') }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="12" :md="24" :sm="24" :xs="24">
            <a-form-item :label="$t('functional-analysis.top-btn.from')">
              <a-select
                  @change="fromNlsChange"
                  :value="queryParameter.sourceLkey"
              >
                <a-select-option
                    v-for="(item, index) in fromNls"
                    :key="index"
                    :value="item.lkey">
                  {{ $t('global-dict.select-nls.' + item.lkey) }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="12" :md="24" :sm="24" :xs="24">
            <a-form-item :label="$t('functional-analysis.top-btn.to')">
              <a-select
                  @change="toNlsChange"
                  :value="queryParameter.targetLkey"
              >
                <a-select-option
                    v-for="(item, index) in toNls"
                    :key="index"
                    :value="item.lkey">
                  {{ $t('global-dict.select-nls.' + item.lkey) }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="24" :md="24" :sm="24" :xs="24">
            <a-form-item class="tr" :label="'\xa0'">
              <a-button class="ml10" @click="search" type="primary">
                {{ $t('global-btn.search') }}
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 表格 Start -->
    <a-table
        class="mt10"
        :loading="loading"
        bordered
        :columns="tableColumns"
        :rowKey="(record, index) => {return index;}"
        size="small"
        :dataSource="tableData"
        :scroll="{ y: 'calc(88vh - 600px)' }"
        @change="handleTableChange"
        :pagination="pagination"
    >
      <template slot="target" slot-scope="text, record">
        <EditTableCell :obj="{id: record.struId, value: record.target}"
                       @change="handleCellChange(record.struId, 'target', $event)"/>
      </template>
    </a-table>
    <!-- 表格 End -->

    <div slot="footer" class="mt10 text-right" v-if="this.$api.isLook !== '1'">
      <a-button :disabled="btnAutoTranslate" :loading="btnAutoTranslateLoading" class="ml10" @click="autoTranslation" type="primary">
        {{ $t('global-btn.automatic-translation') }}
      </a-button>
      <a-button :disabled="btnTranslate" :loading="btnTranslateLoading" class="ml10" @click="translate" type="primary">
        {{ $t('global-btn.translate') }}
      </a-button>
      <a-button :disabled="btnTranslateNext" :loading="btnTranslateNextLoading" class="ml10" @click="translatePage" type="primary">
        {{ $t('global-btn.translate-next') }}
      </a-button>
    </div>
  </div>
</template>
<script>

import EditTableCell from './EditTableCell';

export default {
  name: 'NameEditTable',
  components: {
    EditTableCell
  },
  props: {
    tabName: {
      default: '',
      type: String
    },
  },
  data() {
    return {
      formItemLayout: {
        labelCol: {
          span: 1
        },
        wrapperCol: {
          span: 11
        }
      },
      /** 表格表头 */
      tableColumns: [
        {
          title: () => this.$t('functional-analysis.top-modal.name'),
          dataIndex: 'source',
          align: 'center',
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-modal.name'),
          dataIndex: 'target',
          align: 'center',
          scopedSlots: {customRender: 'target'},
          ellipsis: true
        }
      ],
      /** 表格数据 */
      tableData: [],
      /** 表格分页 */
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页条数
        showTotal: total => this.$t('global-constant.table.show-total', [total]), // 用于显示数据总量和当前数据顺序
        showSizeChanger: false, // 是否可以改变 pageSize
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 指定每页可以显示多少条
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // pageSize 变化的回调
        total: 0 // 总条数
      },
      /** 参考语言 */
      fromNls: [],
      /** 目标语言 */
      toNls: [],
      /** 表格加载中... */
      loading: false,
      /** 自动翻译加载中... */
      btnAutoTranslateLoading: false,
      /** 翻译加载中... */
      btnTranslateLoading: false,
      /** 翻译并翻页加载中... */
      btnTranslateNextLoading: false,
      /** 检索条件 */
      queryParameter: {
        fmeaId: this.$store.getters.rfmeaId,
        translateFlag: 0, /** 翻译标识：0未翻译，1已翻译 */
        sourceLkey: undefined, /** 参考语言 */
        targetLkey: undefined, /** 目标语言 */
        pagination: {
          pageCurrent: 1
        }
      },
      /** 按钮：自动翻译 */
      btnAutoTranslate: false,
      /** 按钮：翻译 */
      btnTranslate: false,
      /** 按钮：翻译并翻页 */
      btnTranslateNext: false,
      /** 翻页标识 */
      nextFlag: 0
    };
  },
  mounted() {
    this.list();
  },
  methods: {
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.loading = true;
      _that.$api.getTranslationDescription(_that.queryParameter).then(res => {
        if (res.flag) {
          let currentNls = res.data.rdfmcurrentNls;
          let translateModels = JSON.parse(res.data.translateModels);
          _that.fromNls = JSON.parse(JSON.stringify(currentNls));
          _that.toNls = JSON.parse(JSON.stringify(currentNls));
          // 参考语言
          _that.queryParameter.sourceLkey = res.inputData.sourceLkey;
          // 目标语言
          _that.queryParameter.targetLkey = res.inputData.targetLkey;
          // 表格表头
          _that.tableColumns[0].title = _that.$t('global-dict.select-nls.' + _that.queryParameter.sourceLkey);
          _that.tableColumns[1].title = _that.$t('global-dict.select-nls.' + _that.queryParameter.targetLkey);
          _that.nextFlag = res.inputData.translateFlag;
          if (translateModels && translateModels.length > 0) {
            _that.tableData = translateModels;
            if (_that.queryParameter.translateFlag === 0) {
              _that.btnTranslate = true;
              _that.btnAutoTranslate = false;
            } else {
              _that.btnTranslate = false;
              _that.btnAutoTranslate = true;
            }
            _that.btnTranslateNext = false;
          } else {
            _that.tableData = [];
            _that.btnAutoTranslate = true;
            _that.btnTranslate = true;
            _that.btnTranslateNext = true;
          }
          // 表格分页
          _that.pagination.current = res.data.pagination.pageCurrent;
          _that.pagination.pageSize = res.data.pagination.pageSize;
          _that.pagination.total = res.data.pagination.rowTotal;
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.loading = false;
      });
    },
    /**
     * 处理表格页码选择事件
     */
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.queryParameter.pagination.pageCurrent = pagination.current;
      this.list();
    },
    /**
     * 处理单元格编辑事件
     */
    handleCellChange(key, dataIndex, value) {
      const dataSource = [...this.tableData];
      const target = dataSource.find(item => item.struId === key);
      if (target) {
        target[dataIndex] = value;
        this.tableData = dataSource;
      }
    },
    /**
     * 翻译表示选择事件
     */
    translationFlagChange(e) {
      this.queryParameter.translateFlag = e.target.value;
    },
    /**
     * 参考语言选择事件
     */
    fromNlsChange(val) {
      this.queryParameter.sourceLkey = val;
    },
    /**
     * 目标语言选择事件
     */
    toNlsChange(val) {
      this.queryParameter.targetLkey = val;
    },
    /**
     * 查询
     */
    search() {
      this.list();
    },
    /**
     * 自动翻译
     */
    autoTranslation() {
      let _that = this;
      _that.btnAutoTranslateLoading = true;
      _that.$api.autoTranslationDescription({
        fmeaId: _that.$store.getters.rfmeaId,
        sourceLkey: _that.queryParameter.sourceLkey,
        targetLkey: _that.queryParameter.targetLkey,
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.list();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.btnAutoTranslateLoading = false;
      });
    },
    /**
     * 翻译
     */
    translate() {
      let _that = this;
      _that.btnTranslateLoading = true;
      _that.$api.saveTranslationDescription({
        fmeaId: _that.$store.getters.rfmeaId,
        targetLkey: _that.queryParameter.targetLkey,
        rdfmTranslateModels: _that.tableData,
        translateFlag: _that.queryParameter.translateFlag
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.list();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.btnTranslateLoading = false;
      });
    },
    /**
     * 翻译并翻页
     */
    translatePage() {
      let _that = this;
      _that.btnTranslateNextLoading = true;
      _that.$api.saveTranslationDescription({
        fmeaId: _that.$store.getters.rfmeaId,
        targetLkey: _that.queryParameter.targetLkey,
        rdfmTranslateModels: _that.tableData
      }).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          if (_that.nextFlag === 1) {
            _that.pagination.current = _that.pagination.current + 1;
            _that.queryParameter.pagination.pageCurrent = _that.queryParameter.pagination.pageCurrent + 1;
          }
          _that.list();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.btnTranslateNextLoading = false;
      });
    },
    /**
     * 关闭对话框
     */
    closeModal() {
      this.$emit("closeModal");
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .ant-table-tbody {
  .ant-table-row-cell-ellipsis:nth-of-type(1) {
    text-align: left !important;
  }

  .ant-table-row-cell-ellipsis:nth-of-type(2) {
    text-align: left !important;
  }
}

/*/deep/ .ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body {
  overflow-y: auto !important;
}*/
</style>
