<template>
  <div>
    <div class="mb10" v-if="$api.isLook !== '1'">
      <a-input-search
          v-model="inputName"
          :placeholder="$t('functional-analysis.top-modal.please-enter-name')"
          :loading="saveLoading"
          :maxLength="100"
          @search="create"
      >
        <a-button
            type="primary"
            style="width: 50px"
            icon="plus"
            slot="enterButton"
            :maxLength="100"
        />
      </a-input-search>
    </div>
    <!-- 表格 Start -->
    <a-table
        ref="tableRef"
        :rowSelection="{
          columnTitle: this.$t('functional-analysis.top-modal.current-default'),
          columnWidth: 100,
          type: 'radio',
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          getCheckboxProps: record => ({
              props: {
                disabled: $api.isLook === '1' || record.state === 1
              }
          })
        }"
        :loading="loading"
        bordered
        :columns="tableColumns"
        :rowKey="(record, index) => {return index;}"
        size="small"
        :dataSource="tableData"
        :scroll="{ y: 'calc(88vh - 400px)' }"
        :pagination="false">
      <template v-slot:groupName="text, record">
        <a-input
            v-if="record.editFlag"
            style="margin: -5px 0"
            :value="record.groupName"
            @change="e => handleChange(e.target.value, record.annotationGroup, 'groupName')"
            :maxLength="500"
        />
        <template v-else>
          {{ record.groupName }}
        </template>
      </template>
      <template v-slot:state="text, record">
        <span>
          {{
            record.state === 1
                ? $t('functional-analysis.top-modal.disabled')
                : $t('functional-analysis.top-modal.enable')
          }}
        </span>
      </template>
      <template slot="action" slot-scope="text, record" v-if="$api.isLook !== '1'">
        <span v-if="record.editFlag && record.annotationGroup !==0">
          <!-- 保存 -->
          <a class="operate-btn" @click="update(record)">
            <a-tooltip :title="$t('global-btn.save')">
              <a-icon type="check"/>
            </a-tooltip>
          </a>
          <!-- 取消 -->
          <a class="ml10 operate-btn" @click="cancel(record)">
            <a-tooltip :title="$t('global-btn.cancel')">
              <a-icon type="undo"/>
            </a-tooltip>
          </a>
        </span>
        <span v-else-if="!record.editFlag && record.annotationGroup !== 0 && record.state === 0">
          <!-- 编辑 -->
          <a class="operate-btn" :disabled="!!editIngKey" @click="edit(record)">
            <a-tooltip :title="$t('global-btn.edit')">
              <i class="iconfont iconicon-bainji"></i>
            </a-tooltip>
          </a>
          <!-- 禁用 -->
          <span v-if="record.annotationGroup !== selectedRow.annotationGroup">
            <a class="ml10 operate-btn" :disabled="!($api.isLook !== '1') || !!editIngKey" @click="changeStatus(record.annotationGroup, 1)">
              <a-tooltip :title="$t('global-btn.disabled')">
                <a-icon type="close-circle"/>
              </a-tooltip>
            </a>
          </span>
        </span>
        <span v-else-if="!record.editFlag && record.annotationGroup !== 0 && record.state === 1">
          <!-- 启用 -->
          <span v-if="record.annotationGroup !== selectedRow.annotationGroup">
            <a class="operate-btn" :disabled="!!editIngKey" @click="changeStatus(record.annotationGroup, 0)">
              <a-tooltip :title="$t('global-btn.enable')">
                <a-icon type="check-circle" theme="filled" />
              </a-tooltip>
            </a>
          </span>
        </span>
      </template>
    </a-table>
    <!-- 表格 End -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      /** 输入框名称 */
      inputName: '',
      // 表头
      tableColumns: [
        {
          title: () => this.$t('functional-analysis.top-modal.name'),
          align: 'center',
          scopedSlots: {
            customRender: "groupName"
          },
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-modal.status'),
          width: 100,
          align: 'center',
          scopedSlots: {
            customRender: 'state' /** 0：启用 1: 禁用 */
          },
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-modal.operate'),
          width: 100,
          align: "center",
          scopedSlots: {
            customRender: "action"
          },
          ellipsis: true
        }
      ],
      tableData: [],
      tableCacheData: [],
      /** 编辑中的Key */
      editIngKey: '',
      selectedRowKeys: [],
      selectedRow: {},
      loading: false,
      saveLoading: false,

    };
  },
  methods: {
    /**
     * 单选框改变回调
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.save(selectedRowKeys, selectedRows[0]);
    },
    /**
     * 保存
     * @param selectedRowKeys
     * @param row
     */
    save(selectedRowKeys, row) {
      let _that = this;
      _that.$confirm({
        title: this.$t('global-message.warn'),
        content: this.$t('global-message.nodes.group.change'),
        icon: "aaoopqa", //图标，不想用就随便写一个
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onOk() {
          _that.$api.saveNodesConfig({
            fmeaId: _that.$store.getters.rfmeaId,
            currentAnnotationGroup: row.annotationGroup,
          }).then(res => {
            if (res.flag) {
              _that.$message.success(res.message, 1);
            } else {
              _that.$message.error(res.message, 1);
            }
          }).finally(() => {
            _that.selectedRowKeys = selectedRowKeys;
            _that.selectedRow = row;
          });
        },
        onCancel() {
        }
      });
    },
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.loading = true;
      _that.$api.getNodesConfig({
        fmeaId: _that.$store.getters.rfmeaId
      }).then(res => {
        if (res.flag) {
          _that.tableData = res.data.mfmeaAnnotationGroupList || [];
          _that.tableCacheData = res.data.mfmeaAnnotationGroupList.map(item => ({...item}));
          for (let i = 0; i < _that.tableData.length; i++) {
            if (_that.tableData[i].annotationGroup === res.data.currentAnnotationGroup) {
              _that.selectedRowKeys[0] = i;
              _that.selectedRow = _that.tableData[i];
              break;
            }
          }
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.loading = false;
      });
    },
    /**
     * 新建
     */
    create() {
      let _that = this;
      // 验证非空
      if (!_that.inputName.trim())
        return _that.$message.warn(_that.$t('global-message.warn.please-enter-name'), 1);
      // 等待中
      _that.saveLoading = true;
      _that.$api.addNodesConfig({
        fmeaId: _that.$store.getters.rfmeaId,
        addGroupName: _that.inputName,
        defaultFlag: false
      }).then(res => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.list();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.saveLoading = false;
        _that.inputName = '';
      });
    },
    /**
     * 编辑
     * @param row
     */
    edit(row) {
      const newTableData = [...this.tableData];
      const target = newTableData.find(item => row.annotationGroup === item.annotationGroup);
      this.editIngKey = row.annotationGroup;
      if (target) {
        target.editFlag = true;
        this.tableData = newTableData;
      }
    },
    /**
     * 处理更改
     */
    handleChange(value, key, column) {
      const newTableData = [...this.tableData];
      const target = newTableData.find(item => key === item.annotationGroup);
      if (target) {
        target[column] = value;
        this.tableData = newTableData;
      }
    },
    /**
     * 修改
     * @param row
     */
    update(row) {
      let _that = this;
      // 验证非空
      if (!row.groupName || !row.groupName.trim())
        return _that.$message.warn(_that.$t('global-message.warn.please-enter-name'), 1);
      _that.loading = true;
      _that.$api.updateNodesConfig({
        fmeaId: _that.$store.getters.rfmeaId,
        annotationGroup: row.annotationGroup,
        groupName: row.groupName,
      }).then(res => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          const newTableData = [..._that.tableData];
          const newTableCacheData = [..._that.tableCacheData];
          const target = newTableData.find(item => row.annotationGroup === item.annotationGroup);
          const targetCache = newTableCacheData.find(item => row.annotationGroup === item.annotationGroup);
          if (target && targetCache) {
            delete target.editFlag;
            _that.tableData = newTableData;
            Object.assign(targetCache, target);
            _that.tableCacheData = newTableCacheData;
          }
          _that.editIngKey = '';
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.loading = false;
      });
    },
    /**
     * 取消
     * @param row
     */
    cancel(row) {
      const newTableData = [...this.tableData];
      const target = newTableData.find(item => row.annotationGroup === item.annotationGroup);
      this.editIngKey = '';
      if (target) {
        Object.assign(target, this.tableCacheData.find(item => row.annotationGroup === item.annotationGroup));
        delete target.editFlag;
        this.tableData = newTableData;
      }
    },
    /**
     * 禁用
     * @param key
     * @param status 0：启用，1：禁用
     */
    changeStatus(key, status) {
      let _that = this;
      _that.$confirm({
        title: _that.$t('global-message.warn'),
        content: status === 0 ? this.$t('global-message.nodes.group.enable')
            : this.$t('global-message.nodes.group.disabled'),
        icon: "aaoopqa", //图标，不想用就随便写一个
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onOk() {
          _that.loading = true;
          _that.$api.updateStatusNodesConfig({
            fmeaId: _that.$store.getters.rfmeaId,
            editAnnotationGroup: key,
            state: status,
          }).then(res => {
            if (res.flag) {
              _that.$message.success(res.message, 1);
              const newTableData = [..._that.tableData];
              const target = newTableData.find(item => key === item.annotationGroup);
              if (target) {
                target.state = status;
                _that.tableData = newTableData;
              }
            } else {
              _that.$message.error(res.message, 1);
            }
          }).finally(() => {
            _that.loading = false;
          });
        },
        onCancel() {
        }
      });
    },
  },
  mounted() {
    /**
     * 列表
     */
    this.list();
  }
};
</script>
<style lang="less" scoped>
/** 表格头部自动换行 */
/deep/ .ant-table-thead {
  .ant-table-row-cell-ellipsis .ant-table-column-title {
    white-space: normal;
  }
}

/deep/ .ant-table-tbody {
  .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>

