<template>
  <div>
    <a-form layout="vertical">
      <a-row :gutter="24">
        <a-col :xl="8" :lg="12" :md="24" :sm="24" :xs="24">
          <a-form-item :label="$t('functional-analysis.top-modal.node-type')">
            <a-select
                allow-clear
                :placeholder="$t('functional-analysis.top-modal.please-select-node-type')"
                @change="struTypeCodeChange">
              <a-select-option
                  v-for="(item, index) in struTypeCodes"
                  :key="index"
                  :value="item.code">
                {{ item.value }}
              </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 required :label="$t('functional-analysis.top-modal.language')">
            <a-select @change="currentNlsChange" :defaultValue="defaultNls" disabled>
              <a-select-option
                  v-for="(item, index) in currentNls"
                  :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-modal.replaceAll')">
            <a-select
                v-model="choose"
                @change="replaceCodeChange">
              <a-select-option
                  v-for="(item, index) in chooseList"
                  :key="index"
                  :value="item.code">
                {{ item.value }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
          <a-form-item required :label="$t('functional-analysis.top-modal.find-content')">
            <a-input
                allowClear
                v-model="findContent"
                :placeholder="$t('functional-analysis.top-modal.please-enter-find-content')"
                :maxLength="500"
                @change="findContentChange"/>
          </a-form-item>
        </a-col>
        <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
          <a-form-item required :label="$t('functional-analysis.top-modal.replace-with')">
            <a-input
                allowClear
                v-model="afterReplaceContent"
                :maxLength="500"
                :placeholder="$t('functional-analysis.top-modal.please-enter-replace-with')"
                @change="afterReplaceContentChange"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="mt10 mb10">
      <span>
        <a-button @click="replace" type="primary" class="mr5">
          {{ $t('global-btn.replace') }}
        </a-button>
        <a-button @click="replaceAll" type="primary">
          {{ $t('global-btn.replace-all') }}
        </a-button>
      </span>
      <span class="fr">
      <span class="mr5" style="font-size: 16px" v-show="hasDataFlag">{{currentNum + 1}}/{{totalNum}}</span>
      <a-button @click="last" :loading="saveLoading" class="mr5" v-show="hasDataFlag">
        <
      </a-button>
      <a-button @click="next" :loading="saveLoading" class="mr5" v-show="hasDataFlag">
        >
      </a-button>
        <a-button @click="search" type="primary">
          {{ $t('global-btn.search') }}
        </a-button>
      </span>
    </div>

    <!-- 表格 Start -->
    <a-table
        :data-source="tableData"
        :columns="tableColumns"
        :customRow="customRow"
        :rowKey="(row, index) => {return index;}"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: checkboxChange
        }"
        v-show="false"
        :loading="tableLoading"
        bordered
        size="small"
        :scroll="{ y: 'calc(88vh - 400px)' }"
        :pagination="false">
      <template v-slot:nodeType="text, record">
        <span v-for="(item, index) in struTypeCodes">
              {{ item.code === record.nodeType ? item.value : '' }}
        </span>
      </template>
    </a-table>
    <!-- 表格 End -->

<!--    <div class="dialog-footer text-right mt10">-->
<!--      <a-button v-if="this.$api.isLook !== '1'" @click="save" type="primary" :loading="saveLoading">-->
<!--        {{ $t('global-btn.save') }}-->
<!--      </a-button>-->
<!--    </div>-->
  </div>
</template>
<script>

export default {
  name: "BatchReplace",
  data() {
    return {
      hasDataFlag: false, // 控制上一个下一个按钮显示与否
      totalNum: 0,
      currentNum: 0,
      /** 节点类型下拉数组 */
      struTypeCodes: [
        {code: "01", value: this.$t('global-dict.structure')},
        {code: "02", value: this.$t('global-dict.function')},
        {code: "04", value: this.$t('global-dict.product-features')},
        {code: "05", value: this.$t('global-dict.require')},
        {code: "06", value: this.$t('global-dict.failure')},
        {code: "09", value: this.$t('global-dict.prevent')},
        {code: "10", value: this.$t('global-dict.detect')},
      ],
      /** 是否全名替换 */
      chooseList :[
        {code: "01", value: this.$t('plan.basic-information.yes')},
        {code: "02", value: this.$t('plan.basic-information.no')},
      ],
      /** 是否全名称替换*/
      choose:'02',
      /** 语言下拉数组 */
      currentNls: [],
      /** 默认语言 */
      defaultNls: [],
      /** 表头 */
      tableColumns: [
        {
          title: () => this.$t('functional-analysis.top-modal.node-type'),
          dataIndex: 'nodeType',
          width: 200,
          align: 'center',
          scopedSlots: {
            customRender: 'nodeType'
          },
        },
        {
          title: () => this.$t('functional-analysis.top-modal.node-name'),
          dataIndex: 'nodeName',
          align: 'center',
          ellipsis: true
        },
      ],
      /** 表格数据 */
      tableData: [],
      /** 初始表格数据 */
      initTableData: [],
      /** 表格：选中索引 */
      selectedRowKeys: [],
      /** 表格：选中数据 */
      selectedRows: [],
      /** 选中节点类型 */
      checkedNodeType: "",
      /** 选中语言 */
      checkedLkey: 0,
      /** 查找内容 */
      findContent: "",
      /** 缓存查询条件：选中节点类型 */
      hideCheckedNodeType: "",
      /** 缓存查询条件：选中语言 */
      hideCheckedLkey: 0,
      /** 缓存查询条件：查找内容 */
      hideFindContent: "",
      /** 替换后内容 */
      afterReplaceContent: "",
      /** 表格Loading */
      tableLoading: false,
      /** 保存Loading */
      saveLoading: false,
      /** 是否全部替换   false 否 true 是 */
      flag:false
    };
  },
  mounted() {
    this.list();
  },
  watch: {
    // 监听选中的节点
    selectedRows () {
      this.$nextTick(() => {
        let _that = this;
        if (_that.tableData && _that.tableData.length != 0) {
          this.$emit('handleLeftTreeCss', _that.selectedRows, _that.findContent);
          this.$emit('handleRightTreeCss', _that.selectedRows, _that.findContent);
        }
      })
    }
  },
  methods: {
    // 上一个
    last() {
      let _that = this;
      _that.selectedRowKeys = [];
      _that.selectedRows = [];
      if (_that.currentNum > 0) {
        _that.currentNum = _that.currentNum - 1;
      }else {
        _that.currentNum = _that.totalNum - 1;
      }
      _that.selectedRowKeys.push(_that.currentNum);
      _that.selectedRows.push(_that.tableData[_that.currentNum]);
    },
    // 下一个
    next() {
      let _that = this;
      _that.selectedRowKeys = [];
      _that.selectedRows = [];
      if (_that.currentNum < _that.totalNum - 1) {
        _that.currentNum = _that.currentNum + 1;
      }else {
        _that.currentNum = 0;
      }
      _that.selectedRowKeys.push(_that.currentNum);
      _that.selectedRows.push(_that.tableData[_that.currentNum]);
    },
    /**
     * 刷新左侧树
     */
    initLeftTree() {
      this.$emit("initLeftTree");
    },
    /**
     * 刷新右侧树
     */
    initRightTree() {
      this.$emit("initRightTree");
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 校验选中节点类型
     */
    // validCheckedNodeType() {
    //   let _that = this;
    //   if (!_that.checkedNodeType) {
    //     _that.$message.warn(this.$t('global-message.warn.please-select-node-type'), 1);
    //     return false;
    //   }
    //   return true;
    // },
    /**
     * 校验选中语言
     */
    validCheckedLkey() {
      let _that = this;
      if (!_that.checkedLkey) {
        _that.$message.warn(this.$t('global-message.warn.please-select-language'), 1);
        return false;
      }
      return true;
    },
    /**
     * 校验查找内容
     */
    validFindContent() {
      let _that = this;
      if (!_that.findContent) {
        _that.$message.warn(this.$t('global-message.warn.please-enter-find-content'), 1);
        return false;
      }
      return true;
    },
    /**
     * 校验替换后内容
     */
    validAfterReplaceContent() {
      let _that = this;
      if (!_that.afterReplaceContent) {
        _that.$message.warn(this.$t('global-message.warn.please-enter-replaced-node-name'), 1);
        return false;
      }
      return true;
    },
    /**
     * 校验表格数据
     */
    validTableData() {
      let _that = this;
      if (_that.tableData.length === 0) {
        _that.$message.warn(this.$t('global-message.warn.current-no-replace'), 1);
        return false;
      }
      return true;
    },
    /**
     * 校验勾选表格数据
     */
    validCheckedTableData() {
      let _that = this;
      if (_that.selectedRows.length === 0) {
        _that.$message.warn(this.$t('global-message.warn.please-select-a-piece-of-data'), 1);
        return false;
      }
      return true;
    },
    /**
     * 校验检索条件
     */
    validSearchInfo() {
      let _that = this;
      if (_that.checkedNodeType !== _that.hideCheckedNodeType
          || _that.findContent !== _that.hideFindContent
          || _that.checkedLkey !== _that.hideCheckedLkey) {
        _that.$message.warn(this.$t('global-message.warn.replace-node-name-not-change'), 1);
        return false;
      } else {
        return true;
      }
    },
    /**
     * 搜索
     */
    search() {
      let _that = this;
      _that.currentNum = 0;
      // 校验
      // if (!_that.validCheckedNodeType()) return;
      if (!_that.validFindContent()) return;
      if (!_that.validCheckedLkey()) return;
      this.list();
    },
    /**
     * 替换
     */
    replace() {
      let _that = this;
      // 校验
      if (!_that.validTableData()) return;
      if (!_that.validAfterReplaceContent()) return;
      if (!_that.validSearchInfo()) return;
      if (!_that.validCheckedTableData()) return;

      // 单个替换
      let tableData = JSON.parse(JSON.stringify(_that.initTableData));
      if (_that.choose=='02'){
        for (let i = 0, len = tableData.length; i < len; i++) {
          if (_that.selectedRows.filter(item => item.struId === tableData[i].struId)[0]) {
            // 替换之前特殊符号先进行转义
            tableData[i].nodeName = tableData[i].nodeName.replace(
                new RegExp(RegExp.escape(_that.findContent), 'g'), _that.afterReplaceContent);
          }
        }
      }else {
        for (let i = 0, len = tableData.length; i < len; i++) {
          if (_that.selectedRows.filter(item => item.struId === tableData[i].struId)[0]) {
            tableData[i].nodeName =  _that.afterReplaceContent;
          }
        }
      }
      _that.tableData = tableData;
      _that.$confirm({
        title: this.$t('global-message.warn'),
        content: this.$t('global-message.warn.whether-replace'),
        icon: 'aaoopqa', //图标，不想用就随便写一个
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onCancel() {
        },
        onOk() {
          // 保存
          _that.selectedRows = [];
          _that.selectedRows.push(_that.tableData[_that.currentNum]); // 单个替换选中的行
          _that.flag = false; // 单个替换
          _that.save();
        },
      });
    },
    /**
     * 全部替换
     */
    replaceAll() {
      let _that = this;
      // 校验
      if (!_that.validTableData()) return;
      if (!_that.validAfterReplaceContent()) return;
      if (!_that.validSearchInfo()) return;

      _that.$confirm({
        title: this.$t('global-message.warn'),
        content: this.$t('global-message.warn.whether-replace-all', [_that.initTableData.length]),
        icon: 'aaoopqa', //图标，不想用就随便写一个
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onCancel() {
        },
        onOk() {
          // 全部替换
          let tableData = JSON.parse(JSON.stringify(_that.initTableData));
          // console.log("tableData",tableData);
          if (_that.choose=='02'){
            for (let i = 0, len = tableData.length; i < len; i++) {
              tableData[i].nodeName = tableData[i].nodeName.replace(
                  new RegExp(RegExp.escape(_that.findContent), 'g'), _that.afterReplaceContent);
            }
          }else {
            for (let i = 0, len = tableData.length; i < len; i++) {
              tableData[i].nodeName =_that.afterReplaceContent;
            }
          }
          _that.tableData = tableData;
          _that.flag=true;
          _that.currentNum = 0; // 当前
          // 保存
          _that.save();
        },
      });
    },
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.tableLoading = true;
      _that.$api.getBatchReplace({
        fmeaId: _that.$store.getters.rfmeaId,
        selectNodeType: _that.checkedNodeType, /** 节点类型 */
        nls: _that.checkedLkey, /** 语言Key */
        keyWord: _that.findContent, /** 查找内容 */
      }).then((res) => {
        if (res.flag) {
          // 语言
          _that.currentNls = res.data.rdfmcurrentNls;
          _that.defaultNls[0] = res.inputData.nls;
          _that.checkedLkey = res.inputData.nls;
          // 表格数据
          _that.tableData = res.data.rdfmTableBatchEditDtos || [];
          _that.initTableData = res.data.rdfmTableBatchEditDtos || [];
          // 总数
          _that.totalNum = _that.tableData.length;
          // 清空
          _that.selectedRowKeys = [];
          _that.selectedRows = [];
          // 默认全部打勾
          // _that.tableData.forEach((item, index) => {
          //   _that.selectedRowKeys.push(index);
          //   _that.selectedRows.push(item);
          // });
          if (_that.tableData) {
            if (_that.tableData[_that.currentNum]) {
              _that.selectedRowKeys.push(_that.currentNum);
              _that.selectedRows.push(_that.tableData[_that.currentNum]);
            }
          }
          // 缓存本次检索条件
          _that.hideCheckedNodeType = _that.checkedNodeType;
          _that.hideFindContent = _that.findContent;
          _that.hideCheckedLkey = _that.checkedLkey;
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.tableLoading = false;
        // 控制上一个下一个按钮显示与否
        if (_that.totalNum > 0) {
          _that.hasDataFlag = true;
          if (_that.totalNum === _that.currentNum) {
            _that.currentNum = _that.totalNum - 1;
            _that.selectedRowKeys.push(_that.currentNum);
            _that.selectedRows.push(_that.tableData[_that.currentNum]);
          }
        }else {
          _that.hasDataFlag = false;
        }
      });
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      // 校验
      if (!_that.validTableData()) return;
      if (!_that.validAfterReplaceContent()) return;
      if (!_that.validSearchInfo()) return;
      let  struNlsData=[];
      // 数据处理
      if (_that.flag==false){
         struNlsData = _that.selectedRows.map(item => {
          return {struId: item.struId, name: item.nodeName};
        });
      }else {
         struNlsData = _that.tableData.map(item => {
          return {struId: item.struId, name: item.nodeName};
        });
        // console.log("struNlsData2",struNlsData);
      }
      _that.$confirm({
        title: this.$t('global-message.warn'),
        content: this.$t('global-message.warn.replace-after-not-recoverable'),
        icon: 'aaoopqa', //图标，不想用就随便写一个
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onCancel() {
        },
        onOk() {
          _that.tableLoading = true;
          _that.$api.saveBatchReplace({
            fmeaId: _that.$store.getters.rfmeaId,
            selectNodeType: _that.checkedNodeType, /** 节点类型 */
            nls: _that.checkedLkey, /** 语言Key */
            keyWord: _that.findContent, /** 查找内容 */
            modifiedName: _that.afterReplaceContent, /** 替换后内容 */
            rdfmStruNlsData: JSON.stringify(struNlsData), /** 表格数据 */
            replaceAll:_that.choose  /**是否全名称替换 */
          }).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.tableLoading = false;
            _that.$emit('initLeftTree')
            _that.$emit('initRightTree')
          });
        },
      });
    },
    /**
     * 查找内容改变时
     */
    findContentChange(e) {
      this.findContent = e.target.value;
    },
    /**
     * 替换后改变时
     */
    afterReplaceContentChange(e) {
      this.afterReplaceContent = e.target.value;
    },
    /**
     * 节点类型下拉选择时
     */
    struTypeCodeChange(val) {
      this.checkedNodeType = val;
    },
    /**
     * 全名称替换下拉选择
     */
    replaceCodeChange(val){
      this.choose = val;
    },
    /**
     * 语言下拉选择时
     */
    currentNlsChange(val) {
      this.checkedLkey = val;
    },
    /**
     * 复选框改变事件
     */
    checkboxChange(rowKeys, row) {
      this.selectedRows = row;
      this.selectedRowKeys = rowKeys;
    },
    /**
     * 行点击事件
     */
    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);
            }
          }
        }
      };
    },
  },
  destroyed() {
    this.initLeftTree();
    this.initRightTree();
  }
};
</script>
<style lang="less" scoped>


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

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