<template>
  <div>
    <!-- 表单 -->
    <a-form layout='vertical'>
      <a-row :gutter='24'>
        <!-- 节点类型 -->
        <a-col :md="12" :sm="24">
          <a-form-item :label="$t('functional-analysis.merge-modal.nodeType')">
            <a-select
              v-model="nodeType"
              :placeholder="$t('functional-analysis.merge-modal.please-select-nodeType')"
              allowClear>
              <a-select-option
                v-for="item in nodeTypeList"
                :key="item.value"
                :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <!-- 节点名称 -->
        <a-col :md="12" :sm="24">
          <a-form-item :label="$t('functional-analysis.merge-modal.nodeName')">
            <a-input v-model.trim="nodeName" :placeholder="$t('functional-analysis.merge-modal.please-enter-nodeName')" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter='24'>
        <!-- 所选节点 -->
        <a-col :md="12" :sm="24">
          <a-form-item :label="$t('functional-analysis.merge-modal.selected-node')">
            <a-input v-model="selectName" disabled/>
          </a-form-item>
        </a-col>
        <!-- 合并后节点名称 -->
        <a-col :md="12" :sm="24">
          <a-form-item required :label="$t('functional-analysis.merge-modal.merged-node-name')">
            <a-input v-model.trim="mergeName" :maxLength="500"/>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 按钮组 -->
      <a-form-item class="tr" :label="'\xa0'">
        <!-- 重置 -->
        <a-button class="ml10" @click="reset">
          {{ $t("global-btn.reset") }}
        </a-button>
        <!-- 查询 -->
        <a-button class="ml10" type="primary" @click="search">
          {{ $t("global-btn.search") }}
        </a-button>
      </a-form-item>
      <!-- 描述 -->
      <span class="description">
        {{ $t('functional-analysis.merge-modal.note.has-been-merged') }}
      </span>
      <!-- 待合并节点 -->
      <a-row>
        <a-form-item>
          <h2>{{ $t('functional-analysis.merge-modal.node-to-be-merged') }}</h2>
        </a-form-item>
      </a-row>
    </a-form>
    <!-- 表格 -->
    <div>
      <a-table
          :data-source="tableData"
          :columns="tableColumns"
          :rowClassName="rowClassName"
          :customRow="customRow"
          :rowKey="(row, index) => {return index;}"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange
          }"
          bordered
          size="small"
          :scroll="{ y: 'calc(88vh - 400px)' }"
          :pagination="false"/>
    </div>
    <!-- 底部按钮 -->
    <div slot="footer" class="mt10 text-right">
      <!-- 取消 -->
      <a-button @click="closeModal">
        {{ $t('global-btn.cancel') }}
      </a-button>
      <!-- 确认 -->
      <a-button
          type="primary"
          class="ml10"
          @click="save()"
          :loading="saveLoading"
          v-preventReClick>
        {{ $t('global-btn.confirm') }}
      </a-button>
    </div>
  </div>
</template>
<script>
import {checkHotTableLength} from "@/utils/validate";

export default {
  name: "MergeProbeMeasure",
  props: {
    checkedNode: {
      type: Object
    }
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      // 表格列
      tableColumns: [
        // 措施
        {
          title: () => this.$t('functional-analysis.merge-modal.measure'),
          align: "center",
          dataIndex: "actionName",
          key: "actionName",
          ellipsis: true
        },
        // 失效
        {
          title: () => this.$t('functional-analysis.merge-modal.failure'),
          align: "center",
          dataIndex: "failureName",
          key: "failureName",
          ellipsis: true
        },
        // 功能
        {
          title: () => this.$t('functional-analysis.merge-modal.function'),
          align: "center",
          dataIndex: "functionName",
          key: "functionName",
          ellipsis: true
        },
        // 结构
        {
          title: () => this.$t('functional-analysis.merge-modal.structure'),
          align: "center",
          dataIndex: "struName",
          key: "struName",
          ellipsis: true
        },
      ],
      // 选中节点的名称
      selectName: '',
      // 合并后节点名称
      mergeName: '',
      // 表格选中项 key
      selectedRowKeys: [],
      // 表格选中项 行内容数据
      selectedRows: [],
      // 保存Loading
      saveLoading: false,
      // 搜索框 节点名称
      nodeName: undefined,
      // 搜索框 节点类型
      nodeType: undefined,
      // 搜索框 节点类型 下拉选项内容
      nodeTypeList: [
        {name: this.$t('global-constant.contextmenu.equipment'), value: "01"},
        {name: this.$t('global-constant.contextmenu.function'), value: "02"},
        {name: this.$t('global-constant.contextmenu.failure'), value: "03"},
        {name: this.$t('measure-track.measure-track.measure'), value: "04"},
      ],
    };
  },
  mounted() {
    this.list();
  },
  methods: {
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新右侧结构树
     */
    initRightTree() {
      this.$emit("initRightTree");
    },
    /**
     * 改变行样式
     */
    rowClassName(record, index) {
      return record.mergeId ? 'merge-color' : '';
    },
    /**
     * 复选框改变事件
     */
    onSelectChange(selectedRowKeys, row) {
      this.selectedRows = row;
      this.selectedRowKeys = selectedRowKeys;
    },
    /**
     * 行点击事件
     */
    customRow(record, index) {
      let _that = this;
      return {
        on: {
          // 鼠标单击行
          click: () => {
            if (_that.selectedRowKeys.indexOf(index) !== -1) {
              _that.selectedRows.splice(_that.selectedRowKeys.indexOf(index), 1);
              _that.selectedRowKeys.splice(_that.selectedRowKeys.indexOf(index), 1);
            } else {
              _that.selectedRowKeys.push(index)
              _that.selectedRows.push(record);
            }
          }
        }
      };
    },
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.$api.getProbeMeasureMerge({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        nodeType: _that.nodeType ? _that.nodeType : '',
        nodeName: _that.nodeName ? _that.nodeName : '',
      }).then((res) => {
        if (res.flag) {
          _that.tableData = res.data.fmeaStruModelList;
          _that.selectName = res.data.targetName;
          _that.mergeName = res.data.targetName;
          if (_that.tableData && _that.tableData.length > 0) {
            for (let i = 0, len = _that.tableData.length; i < len; i++) {
              // 已合并或者名称相等，自动勾选。
              if ((_that.tableData[i].mergeId && _that.tableData[i].actionName === _that.selectName) || _that.tableData[i].actionName === _that.selectName) {
                _that.selectedRows.push(_that.tableData[i]);
                _that.selectedRowKeys.push(i);
              }
            }
          }
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      })
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      _that.saveMerge();
    },
    /**
     * 校验：合并数据
     */
    validateMergeData() {
      if (!this.mergeName) {
        this.$message.warning(this.$t('global-message.warn.merge-after-be-empty'));
        return false;
      } else if (this.mergeName && checkHotTableLength(this.mergeName, 500)) {
        this.$message.warning(this.$t('global-message.warn.merge-after-length'));
        return false;
      }
      if (this.selectedRows.length === 0) {
        this.$message.warning(this.$t('global-message.warn.please-merge-data'));
        return false;
      }
      return true;
    },
    /**
     * 保存：合并数据
     */
    saveMerge() {
      let _that = this;
      // 校验
      if (!_that.validateMergeData()) return;
      let selectIds = _that.selectedRows.map((item) => {
        return item.struId;
      });
      this.$confirm({
        title: this.$t('global-message.warn'),
        content: this.$t('global-message.warn.merge-after-irrecoverable'),
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onCancel() {
        },
        onOk() {
          _that.saveLoading = true; // 开启：加载中...
          _that.$api.saveProbeMeasureMerge({
            fmeaId: _that.$store.getters.rfmeaId,
            struId: _that.checkedNode.id,
            struName: _that.mergeName,
            enableFailureIds: selectIds.toString(), /** 需要合并的标识集合 */
          }).then((res) => {
            if (res.flag) {
              // 添加成功，关闭弹窗，刷新结构树
              _that.$message.success(res.message, 1);
              _that.closeModal();
              _that.initRightTree();
            } else {
              _that.$message.warning(res.message, 1);
            }
          }).catch((error) => {
            _that.$message.error(error.response.data.message, 1);
          }).finally(() => {
            _that.saveLoading = false; // 关闭：加载中...
          })
        }
      });
    },
    //查询
    search() {
      this.list();
    },
    //重置
    reset() {
      this.selectName = '';
      this.mergeName = '';
      this.nodeName = undefined;
      this.nodeType = undefined;
      this.list();
    },
  }
};
</script>
<style lang="less" scoped>

/deep/ .merge-color {
  color: #999;
}

.description {
  color: #999;
  font-weight: normal;
  font-size: 12px;
}


/deep/ .ant-col-3 {
  width: 13% !important;
}

/deep/ .ant-table-tbody {

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

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

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

  .ant-table-row-cell-ellipsis:nth-of-type(5) {
    text-align: left !important;
  }
}
</style>
