<template>
  <div>
    <a-card>
      <a-form layout="vertical">
        <a-row :gutter="24">
          <!-- 问题编号 -->
          <a-col :lg="8" :md="12" :sm="24" :xl='6' :xs="24">
            <a-form-item :label="$t('research.problem-number')">
              <a-input
                v-model.trim="searchData.issueCode"
                :placeholder="$t('research.please-enter-problem-number')"
                allowClear/>
            </a-form-item>
          </a-col>
          <!-- 负责人 -->
          <a-col :lg="8" :md="12" :sm="24" :xl='6' :xs="24">
            <a-form-item :label="$t('research.responsible')">
              <a-input
                v-model.trim="searchData.responsible"
                :placeholder="$t('research.please-enter-responsible')"
                allowClear/>
            </a-form-item>
          </a-col>
          <!-- 结构代码 -->
          <a-col :lg="8" :md="12" :sm="24" :xl='6' :xs="24">
            <a-form-item :label="$t('research.structure-code')">
              <a-input
                v-model.trim="searchData.svpps"
                :placeholder="$t('research.please-enter-structure-code')"
                allowClear/>
            </a-form-item>
          </a-col>
         <!-- 项目 -->
          <a-col :lg="8" :md="12" :sm="24" :xl='6' :xs="24">
            <a-form-item :label="$t('research.project')">
              <a-input
                v-model.trim="searchData.project"
                :placeholder="$t('research.please-enter-project')"
                allowClear/>
            </a-form-item>
          </a-col>
          <span v-show="advanceExpand">
            <!-- 关闭时间 -->
            <a-col :lg="8" :md="12" :sm="24" :xl='6' :xs="24">
              <a-form-item :label="$t('research.close-time')">
                <a-range-picker
                  v-model="closeTime"
                  style="width: 100%"
                  @change="divisionNameChange"/>
              </a-form-item>
            </a-col>
            <!-- 来源 -->
            <a-col :lg="8" :md="12" :sm="24" :xl='6' :xs="24">
              <a-form-item :label="$t('research.source')">
                <a-select
                  v-model="searchData.source"
                  :placeholder="$t('research.please-select-source')"
                  allowClear>
                  <a-select-option
                    v-for="item in sourceDict"
                    :key="item.value"
                    :value="item.value">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- 种类 -->
            <a-col :lg="8" :md="12" :sm="24" :xl='6' :xs="24">
              <a-form-item :label="$t('research.type')">
                <!-- <a-select
                  v-model="searchData.type"
                  :placeholder="$t('research.please-select-type')"
                  allowClear>
                  <a-select-option
                    v-for="item in typeDict"
                    :key="item.value"
                    :value="item.value">
                    {{ item.name }}
                  </a-select-option>
                </a-select> -->
                <a-input
                  allowClear
                  v-model="searchData.type"
                  :placeholder="$t('research.please-enter-type')"
                />
              </a-form-item>
            </a-col>
            <!-- 分析情况 -->
            <a-col :lg="8" :md="12" :sm="24" :xl='6' :xs="24">
              <a-form-item :label="$t('research.analyze-situation')">
                <a-select
                  v-model="searchData.analysisState"
                  :placeholder="$t('research.please-select-analyze-situation')"
                  allowClear>
                  <a-select-option value="03">
                    {{ $t('research.not-analyzed') }}
                  </a-select-option>
                  <a-select-option value="04">
                    {{ $t('research.analyzed') }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </span>
          <!-- 按钮组 -->
          <a-col :xl='24' :lg='advanceExpand ? 8 : 16' :md='24' :sm='24' :xs='24'>
            <a-form-item :label="'\xa0'" class="tr">
              <!-- 展开折叠 -->
              <a @click='toggleAdvance'>
                {{ advanceExpand ? $t('global.collapse') : $t('global.expand') }}
                <a-icon :type="advanceExpand ? 'up' : 'down'"/>
              </a>
              <!-- 重置 -->
              <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>
          </a-col>
        </a-row>
      </a-form>
      <!-- 添加 -->
      <div class="mt10">
        <a-button
            :disabled="btnDisabled"
            type="primary"
            @click="handleSubmit">
          {{ $t('global-btn.add') }}
        </a-button>
      </div>
    </a-card>
    <!-- 表格 -->
    <a-card>
      <a-table
        ref="tableRef"
        :components='components'
        :columns="tableColumns"
        :dataSource="sourceData"
        :pagination="pagination"
        :rowKey="(record) => record.id"
        :rowSelection="{
           selectedRowKeys: selectedRowKeys,
           onChange: onSelectChange,
         }"
        :scroll="{ x: tableWidth, y: 1000 }"
        bordered
        size="small"
        @change="handleOuterTableChange">
        <!-- 问题编号 -->
        <template slot="issueCode" slot-scope="text, row">
          <span
            :title="row.issueCode"
            class="system-font-color"
            @click="viewCase(row)">
            {{ row.issueCode }}
          </span>
        </template>
        <!-- 来源 -->
        <template slot="source" slot-scope="text, row">
          <span> {{ row.source }} </span>
        </template>
        <!-- 关闭时间 -->
        <template slot="pqcpCloseDate" slot-scope="text, row">
          <span>{{ $com.timeToDate(row.pqcpCloseDate) }}</span>
        </template>
      </a-table>
    </a-card>
    <view-drawer
      ref="look"
      :case="currentCase"
      :failExpId="failExpId"
      :showViewDrawer="showViewDrawer"
      @closeDrawer="closeDrawer"/>
  </div>
</template>
<script>

import ViewDrawer from './components/index';
import VueDraggableResizable from "vue-draggable-resizable";

export default {
  components: {
    ViewDrawer,
    VueDraggableResizable
  },
  data() {
    // 表格拖拽
    this.components = {
      header: {
        cell: (h, props, children) => {
          const {key, ...restProps} = props;
          // 此处的this.columns 是定义的table的表头属性变量
          const col = this.tableColumns.find((col) => {
            const k = col.dataIndex || col.key;
            return k === key;
          });
          if (!col || !col.width) {
            return h('th', {...restProps}, [...children]);
          }
          const dragProps = {
            key: col.dataIndex || col.key,
            class: 'table-draggable-handle',
            attrs: {
              w: 10,
              x: col.width,
              z: 1,
              axis: 'x',
              draggable: true,
              resizable: false
            },
            on: {
              dragging: (x, y) => {
                col.width = Math.max(x, 35);
              }
            }
          };
          const drag = h('vue-draggable-resizable', {...dragProps});
          return h('th', {...restProps, class: 'resize-table-th'}, [...children, drag]);
        }
      }
    };
    return {
      // 表格总宽度
      tableWidth: 0,
      // 表格各列宽度总和
      columnsWidth: 0,
      showViewDrawer: false,//点击编号查看详情
      failExpId: 0,
      currentCase: null,
      selectedRowKeys: [], //table勾选的项
      defaultSelected: [], //初始勾选项
      btnDisabled: undefined, //按钮disabled
      sourceData: [],
      addData: [], //需要添加的项
      delData: [], //需要删除的项
      total: 0,
      queryData: {}, //用来储存点击查询按钮时查询条件，只有点击查询按钮时，查询条件才会更改
      sourceDict: [], //来源字典
      // typeDict: [], //种类字典
      closeTime: undefined,
      searchData: {
        issueCode: undefined, //问题编号
        title: undefined, //标题
        responsible: undefined, //责任人
        svpps: undefined, //SVPPS
        project: undefined, //项目
        pqcpCloseStartDate: undefined,
        pqcpCloseEndDate: undefined,
        source: undefined, //来源
        type: undefined, //种类
        analysisState: undefined, //分析情况
      },
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        fmeaId: this.$store.getters.fmeaId,
      },
      tableColumns: [],
      pagination: {
        current: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: (total) => this.$t('global-constant.table.show-total', [total]), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 每页数量选项
        total: 0, //总条数
      },
      advanceExpand: false,
    };
  },
  created() {
    this.reset();
    this.initDict();
    this.initExisResearch();
  },
  mounted() {
    this.tableColumns = [
      // 问题编号
      {
        title: () => this.$t('research.problem-number'),
        width: 150,
        dataIndex: "issueCode",
        align: "center",
        scopedSlots: {
          customRender: "issueCode"
        },
        ellipsis: true,
      },
      // 来源
      {
        title: () => this.$t('research.source'),
        width: 200,
        align: "center",
        dataIndex: "source",
        scopedSlots: {
          customRender: "source",
        },
        ellipsis: true,
      },
      // 种类
      {
        title: () => this.$t('research.type'),
        width: 200,
        dataIndex: "type",
        align: "center",
        ellipsis: true,
      },
      // 项目
      {
        title: () => this.$t('research.project'),
        width: 200,
        dataIndex: "project",
        align: "center",
        ellipsis: true,
      },
      // 责任部门
      {
        title: () => this.$t('research.responsible-department'),
        width: 200,
        dataIndex: "department",
        align: "center",
        ellipsis: true,
      },
      // 责任人
      {
        title: () => this.$t('research.responsible'),
        width: 120,
        dataIndex: "responsible",
        align: "center",
        ellipsis: true,
      },
      // 关闭时间
      {
        title: () => this.$t('research.close-time'),
        width: 120,
        dataIndex: "pqcpCloseDate",
        align: "center",
        scopedSlots: {
          customRender: "pqcpCloseDate",
        },
        ellipsis: true,
      },
      // 结构代码
      {
        title: () => this.$t('research.structure-code'),
        width: 200,
        dataIndex: "svpps",
        align: "center",
        ellipsis: true,
      },
      // 分析情况
      {
        title: () => this.$t('research.analyze-situation'),
        align: "center",
        dataIndex: "analysisState",
        ellipsis: true,
      },
    ];
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
    // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
    this.getTableDivCss();
  },

  // 剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },

  watch: {
    tableColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
          // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
          this.getTableDivCss();
        });
      },
      deep: true,
      immediate: true
    },
    tableWidth:{
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
          // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
          this.getTableDivCss();
        });
      },
      deep: true,
      immediate: true
    }
  },

  methods: {

    // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
    getTableDivCss() {
      // 选中包裹表格的 div 元素
      let tableHeaderDiv = document.querySelector('.ant-table-header.ant-table-hide-scrollbar');
      let tableHeaderReal = document.querySelector('.resize-table-th');
      // 检查是否成功选中
      if (tableHeaderDiv) {
        // 设置背景颜色为灰色
        tableHeaderDiv.style.backgroundColor = 'rgb(245, 246, 247)';
        // 表头外层盒子的的实际样式
        let computedDivStyle = window.getComputedStyle(tableHeaderDiv);
        // 表头外层盒子的的实际高度
        let tableDivHeight = parseFloat(computedDivStyle.getPropertyValue('height'));
        // 表头的实际样式
        let computedTableStyle = window.getComputedStyle(tableHeaderReal);
        // 表头的实际高度
        let tableHeight = parseFloat(computedTableStyle.getPropertyValue('height'));
        // 设置底部外边距，一下会是负值，用于将表头下的数据单元格纵向对齐
        tableHeaderDiv.style.marginBottom = (tableHeight-tableDivHeight)+'px';
      }
    },
    // 获取表格的总宽度
    handleResize() {
      this.tableWidth = this.$refs.tableRef !== undefined ? this.$refs.tableRef.$el.offsetWidth : 1;
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal(){
      this.columnsWidth = this.tableColumns.reduce((sum, column) => sum + column.width, 0);
    },
    // 动态修改fixe的属性以便表格样式不出现空白列,并平和各列与表格的总宽度
    changeFixed() {
      if (this.columnsWidth <= this.tableWidth) {
        // 遍历 Columns 数组，将有 fixed 属性的元素的 fixed 值设置为 false（当有固定列时，列宽总和小于表格总宽度时会串行）
        this.tableColumns.forEach((column) => {
          if (column.fixed) {
            column.fixed = false;
          }
        });
        // 获取除最后一列以外其他列的宽度总和
        let otherColumnsWidth = this.tableColumns.slice(0, -1).reduce((total, column) => {
          return total + column.width;
        }, 0);
        // 将最后一列的宽度设置为剩余宽度，避免页面表头与内容显示串行
        this.tableColumns[this.tableColumns.length - 1].width = this.tableWidth - otherColumnsWidth;
      } else {
        // 恢复固定列原始定位属性
        // this.tableColumns[0].fixed='left';
        // this.tableColumns[1].fixed='left';
        // this.tableColumns[this.tableColumns.length - 1].fixed='right';
        // 恢复最后一列原始宽度
        // this.tableColumns[this.tableColumns.length - 1].width = 100;
      }
    },

    // 收起/展开
    toggleAdvance() {
      this.advanceExpand = !this.advanceExpand;
    },

    // 表格 - 点击分页中数字触发的方法
    handleOuterTableChange(pagination) {
      this.listQuery.pageSize = pagination.pageSize;
      this.listQuery.pageNo = pagination.current;
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getResearchPageList();
    },

    // 勾选框change
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      var def = new Set(this.defaultSelected);
      var sele = new Set(selectedRowKeys);
      //两个数组的交集
      var coll = new Set([...def].filter((x) => sele.has(x)));

      //原文章链接https://www.jianshu.com/p/c81a21ff9ff4
      //需要删除的数组
      this.delData = Array.from(new Set([...def].filter((x) => !coll.has(x))));
      //需要添加的数组
      this.addData = Array.from(new Set([...sele].filter((x) => !coll.has(x))));
    },

    divisionNameChange(data, dataString) {
      if (!dataString) {
        this.searchData.pqcpCloseStartDate = "";
        this.searchData.pqcpCloseEndDate = "";
        return;
      }
      this.searchData.pqcpCloseStartDate = dataString[0];
      this.searchData.pqcpCloseEndDate = dataString[1];
    },

    // 添加--按钮
    handleSubmit() {
      // 校验
      if (this.addData.length === 0 && this.delData.length === 0) {
        this.$message.warning(this.$t('global-message.warn.unchanged'), 1);
        return;
      }
      this.btnDisabled = true;
      var data = {
        fmeaId: this.$store.getters.fmeaId,
        addHistoryFails: this.addData,
        delHistoryFails: this.delData,
      };
      this.$api.addResearch(data).then((response) => {
        if (response.flag) {
          this.$message.success(response.message);
        } else {
          this.$message.error(response.message);
        }
        this.btnDisabled = false;
        this.$emit("closeModal");
      });
    },

    // 重置
    reset() {
      this.queryData = {};
      this.closeTime = undefined;
      this.searchData = {
        issueCode: undefined, //问题编号
        title: undefined, //标题
        responsible: undefined, //责任人
        svpps: undefined, //SVPPS
        project: undefined, //项目
        pqcpCloseStartDate: undefined,
        pqcpCloseEndDate: undefined,
        source: undefined, //来源
        type: undefined, //种类
      };
      this.listQuery.pageNo = 1;
      this.pagination.current = 1;
      this.addData = [];
      this.delData = [];
      this.selectedRowKeys = this.defaultSelected;
      this.getResearchPageList();
    },

    // 搜索按钮
    search() {
      this.listQuery.pageNo = 1;
      this.pagination.current = 1;
      this.getResearchPageList();
    },

    // 获取历史失效案例库【未分析、已分析】
    getResearchPageList() {
      this.queryData = this.searchData;
      this.sourceData = [];
      this.$api.getHistoryFail({
        ...this.queryData,
        ...this.listQuery,
      }).then((res) => {
        this.sourceData = res.data.data;
        this.total = res.data.total;
        this.pagination.total = res.data.total;
      });
    },

    // 查看
    viewCase(data) {
      this.currentCase = data;
      this.failExpId = parseInt(data.id);
      this.showViewDrawer = true;
      this.$refs.look.historyfailDetail(data.id);
    },

    closeDrawer() {
      this.showViewDrawer = false
    },

    // 获取已勾选的历史失效案例
    initExisResearch() {
      this.$api.get("/DFMEA/research/existResearch.do?fmeaId=" + this.$store.getters.fmeaId).then((res) => {
        if (res.flag) {
          this.defaultSelected = res.data;
          this.selectedRowKeys = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },

    initDict() {
      this.$api.getSourceDict().then((res) => {
        if (res.flag) {
          this.sourceDict = res.data;
        }
      });
      // this.$api.getTypeDict().then((res) => {
      //   if (res.flag) {
      //     this.typeDict = res.data;
      //   }
      // });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .ant-table-fixed-header .ant-table-scroll .ant-table-header {
  overflow: hidden!important;
  margin-bottom: 0!important;
  padding-right: 8px;
  background: rgb(250, 250, 250);
}
</style>
