<template>
  <div>
    <a-form layout="vertical">
      <a-row :gutter="24">
        <a-col :xl="9" :lg="9" :md="9" :sm="24" :xs="24">
          <a-form-item :label="$t('functional-analysis.add-modal.name')">
            <a-input v-model="name" allowClear :placeholder="$t('functional-analysis.add-modal.please-enter-name')"/>
          </a-form-item>
        </a-col>
        <a-col :xl="9" :lg="9" :md="9" :sm="24" :xs="24">
          <a-form-item :label="$t('functional-analysis.top-modal.status')">
            <a-select
                allowClear
                v-model='status'
                :placeholder="$t('functional-analysis.top-modal.please-select') + $t('functional-analysis.top-modal.status')">
              <a-select-option :value="0">
                {{ $t('fmeamanager.snakerflow.process.enable') }}
              </a-select-option>
              <a-select-option :value="1">
                {{ $t('fmeamanager.snakerflow.process.disable') }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24">
          <a-form-item class='tr' :label="'\xa0'">
            <a-button class="ml10" @click="reset">
              {{ $t('global-btn.reset') }}
            </a-button>
            <a-button type="primary" class="ml10" @click="search">
              {{ $t('global-btn.search') }}
            </a-button>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <div class="mb20" v-if="$api.isLook !== '1'">
          <a-col>
            <a-button type="primary" class="mt10" @click="create">
              {{ $t('global-btn.create') }}
            </a-button>
          </a-col>
        </div>
      </a-row>
    </a-form>
    <!-- 表格 Start -->
    <a-table
        ref="tableRef"

        :loading="loading"
        bordered
        :columns="tableColumns"
        :rowKey="(record, annotationGroup) => {return annotationGroup;}"
        size="small"
        :dataSource="tableData"
        :scroll="{}"
        :pagination="pagination"
        @change="tableChange">
      <!-- 序号 -->
      <template slot="index" slot-scope="text, record, index">
        <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
      </template>
      <template v-slot:default="text, record">
        <div v-if="record.isDefaultFlag === '1'">
          <div class="circle"></div>
        </div>
      </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.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 && record.isDefaultFlag !== '1'">
            <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.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 -->
    <!-- 新建备注 -->
    <CreateNoteModal ref="createNote" :showCreateNoteModal="showCreateNoteModal" @list="list"
                     @closeCreateNoteModal="closeCreateNoteModal"/>
    <!-- 编辑备注 -->
    <EditNoteModal ref="editNote" :showEditNoteModal="showEditNoteModal" @list="list"
                   @closeEditNoteModal="closeEditNoteModal"/>
  </div>
</template>
<script>
import CreateNoteModal from "./NotesCreate";
import EditNoteModal from "./NotesEdit";
export default {
  components: {
    CreateNoteModal,
    EditNoteModal
  },
  data() {
    return {
      /** 输入框名称 */
      inputName: '',
      // 表头
      tableColumns: [
        // 序号
        {
          title: this.$t('functional-analysis.top-modal.serialNumber'),
          width: 50,
          align: 'center',
          dataIndex: "index",
          scopedSlots: { customRender: "index" },
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-modal.name'),
          align: 'center',
          dataIndex: "groupName",
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-modal.current-default'),
          width: 100,
          align: 'center',
          scopedSlots: {
            customRender: "default"
          },
          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,
      name: undefined,
      status: undefined,
      /** 创建备注弹窗 */
      showCreateNoteModal: false,
      /** 更新备注弹窗 */
      showEditNoteModal: false,
      /** 表格分页 */
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页条数
        showTotal: total =>
            this.$t("global-constant.table.show-total", [total]), // 用于显示数据总量和当前数据顺序
        showSizeChanger: true, // 是否可以改变 pageSize
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 指定每页可以显示多少条
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // pageSize 变化的回调
        total: 0 // 总条数
      },
    };
  },
  methods: {
    search() {
      this.pagination.current = 1;
      this.list();
    },
    /**
     * 单选框改变回调
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.save(selectedRowKeys, selectedRows[0]);
    },
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.loading = true;
      _that.$api.getNodesConfig({
        fmeaId: _that.$store.getters.rfmeaId,
        pageCurrent: _that.pagination.current,
        pageSize: _that.pagination.pageSize,
        name: _that.name,
        status: _that.status
      }).then(res => {
        if (res.flag) {
          _that.tableData = res.data.mfmeaAnnotationGroupList || [];
          _that.pagination.total = res.data.totalCount;
          _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.tableData[i].isDefaultFlag = '1';
              break;
            }
          }
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.loading = false;
      });
    },
    /**
     * 重置
     */
    reset() {
      this.name = undefined;
      this.status = undefined;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.list();
    },
    /**
     * 新建
     */
    create() {
      let _that = this;
      _that.showCreateNoteModal = true;
      _that.$refs.createNote.fmeaId = _that.$store.getters.rfmeaId;
    },
    /**
     * 关闭：新建备注模态框
     */
    closeCreateNoteModal() {
      this.showCreateNoteModal = false;
    },
    /**
     * 编辑
     * @param row
     */
    edit(row) {
      let _that = this;
      _that.showEditNoteModal = true;
      _that.$refs.editNote.fmeaId = _that.$store.getters.rfmeaId;
      _that.$refs.editNote.noteId = row.annotationGroup;
      _that.$refs.editNote.inputName = row.groupName;
      _that.$refs.editNote.dfeault = row.isDefaultFlag === '1' ? true : false;
    },
    /**
     * 关闭：编辑备注模态框
     */
    closeEditNoteModal() {
      this.showEditNoteModal = false;
    },
    /**
     * 处理更改
     */
    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
     */
    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() {
        }
      });
    },
    /**
     * 表格点击分页中数字触发的方法
     * @param pagination 分页
     * @param filters 过滤
     * @param sorter 排序
     * @param currentDataSource 当前数据源
     */
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      let _that = this;
      // 处理分页
      _that.handlePagination(pagination);
    },
    /**
     * 处理分页
     */
    handlePagination(pagination) {
      let _that = this;
      _that.pagination.current = pagination.current;
      _that.pagination.pageSize = pagination.pageSize;
      _that.list();
    },
  },
  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;
  }
}

// 配置管理 DFMEA默认/PFEMA默认列表显示小圆点
.circle {
  width: 20px;
  height: 20px;
  background-color: #000000;
  border-radius: 10px;
  /* 图形的半径 */
  display: inline-block;
  margin-bottom: -5px;
}

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

