<template>
  <div class="dfmea-page-card">
    <div :style="{ height: contentHeight }">
      <div ref="survey">
        <div class="survey-form">
          <a-form layout="vertical">
            <a-row :gutter="24">
              <!-- 问题编号 -->
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('research.problem-number')">
                  <a-input allowClear :placeholder="$t('research.please-enter-problem-number')"
                    v-model.trim="searchData.issueCode" />
                </a-form-item>
              </a-col>
              <!-- 责任人 -->
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('research.responsible')">
                  <a-input allowClear :placeholder="$t('research.please-enter-responsible')"
                    v-model.trim="searchData.responsible" />
                </a-form-item>
              </a-col>
              <!-- 结构代码 -->
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('research.structure-code')">
                  <a-input allowClear :placeholder="$t('research.please-enter-structure-code')"
                    v-model.trim="searchData.svpps" />
                </a-form-item>
              </a-col>
              <!-- 项目 -->
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('research.project')">
                  <a-input allowClear :placeholder="$t('research.please-enter-project')"
                    v-model.trim="searchData.project" />
                </a-form-item>
              </a-col>
              <span v-show="advanceExpand">
                <!-- 关闭时间 -->
                <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                  <a-form-item :label="$t('research.close-time')">
                    <a-range-picker style="width: 100%" v-model="timeValue" @change="divisionNameChange" />
                  </a-form-item>
                </a-col>
                <!-- 来源 -->
                <a-col :xl="6" :lg="8" :md="12" :sm="24" :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 :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                  <a-form-item :label="$t('research.type')">
                    <!-- <a-select
                    allowClear
                    v-model="searchData.type"
                    :placeholder="$t('research.please-select-type')">
                    <a-select-option
                      :value="item.value"
                      v-for="item in typeDict"
                      :key="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 :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                  <a-form-item :label="$t('research.analyze-status')">
                    <a-select allowClear v-model="searchData.analyzeStatus"
                      :placeholder="$t('research.please-select-analyze-status')">
                      <!-- 适用-未关联 -->
                      <a-select-option value="1">{{ $t('research.apply-to-be-associated') }}</a-select-option>
                      <!-- 适用-已关联 -->
                      <a-select-option value="2">{{ $t('research.apply-associated') }}</a-select-option>
                      <!-- 不适用 -->
                      <a-select-option value="3">{{ $t('research.not-apply') }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </span>
              <!-- 按钮组 -->
              <a-col :xl="advanceExpand ? 24 : 24" :lg="16" :md="advanceExpand ? 12 : 24" :sm="24" :xs="24">
                <a-form-item class="tr" :label="'\xa0'">
                  <!-- 折叠展开 -->
                  <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" @click="search" type="primary">
                    {{ $t("global-btn.search") }}
                  </a-button>
                </a-form-item>
              </a-col>
            </a-row>
            <!-- 添加历史失效 -->
            <a-row>
              <a-button class="mt10 mb10" @click="addPQCP" type="primary" :disabled="!$api.btnPms">
                {{ $t("global-btn.add-from-historical-failure-case-library") }}
              </a-button>
            </a-row>
          </a-form>
        </div>
        <!-- 表格 -->
        <a-table ref="tableRef" bordered size="small" :pagination="pagination" :rowKey="record => record.id"
          :columns="tableColumns" :dataSource="sourceData" @change="handleOuterTableChange" :components='components'
          :scroll="{ x: tableWidth, y: tableHeight }">
          <!-- 问题编号 -->
          <template slot="issueCode" slot-scope="text, row">
            <span :title="row.issueCode" @click="toDetail(row, 0)" class="system-font-color">
              {{ row.issueCode }}
            </span>
          </template>
          <!-- 来源 -->
          <template slot="source" slot-scope="text, row">
            <span>{{ row.source }}</span>
          </template>
          <!-- 关闭时间 -->
          <template slot="pqcpCloseDate" slot-scope="text">
            <span>{{ $com.timeToDate(text) }}</span>
          </template>
          <!-- 是否适用 -->
          <template slot="isApply" slot-scope="text, row">
            <a-select v-model="row.isApply" style="width: 80px" :disabled="!$api.btnPms" @change="applyChange(row)"
              @focus="applyFocus(row)">
              <a-select-option :value="1">
                {{ $t("global-dict.apply") }}
              </a-select-option>
              <a-select-option :value="0">
                {{ $t("global-dict.not-apply") }}
              </a-select-option>
            </a-select>
          </template>
          <!-- 不适用原因 -->
          <template slot="notApplyReason" slot-scope="text, row">
            <!-- 适用 -->
            <span :title="row.notApplyReason ? row.notApplyReason : ''" @click="applyClick(row)"
              v-if="row.isApply === 1 && !row.isEdit" class="ant-table-row-cell-ellipsis">
              {{
              row.notApplyReason
              ? row.notApplyReason
              : $t("research.no-explanation-needed")
              }}
            </span>
            <!-- 点击时 -->
            <a-textarea v-model="row.notApplyReason" :id="'applyInput' + row.id"
              v-show="row.isApply === 1 && row.isEdit" :rows="3" @blur="applyInputBlur(row)" :maxLength="500">
            </a-textarea>
            <!-- 不适用 -->
            <span :title="row.notApplyReason ? row.notApplyReason : ''" @click="noApplyClick(row)"
              v-if="row.isApply === 0 && !row.isEdit" class="ant-table-row-cell-ellipsis">
              {{
              row.notApplyReason
              ? row.notApplyReason
              : $t("research.please-describe-not-apply-reason")
              }}
            </span>
            <!-- 不适用原因 -->
            <a-textarea v-model="row.notApplyReason" :id="'noApplyInput' + row.id"
              v-show="row.isApply === 0 && row.isEdit" :placeholder="$t('research.please-describe-not-apply-reason')"
              :rows="3" @blur="notApplyInputBlur(row)" :maxLength="500">
            </a-textarea>
          </template>
          <!-- 关联失效 -->
          <template slot="relationFault" slot-scope="text, row">
            {{
            row.isApply === 0
            ? $t("research.not-apply")
            : row.relationFault
            ? row.relationFault
            : row.isApply === 1
            ? $t("research.to-be-associated")
            : ""
            }}
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, row">
            <!-- 关联失效 -->
            <a class="operate-btn" v-if="row.isApply === 1" @click="toDetail(row, 0)">
              <a-tooltip :title="$t('global-btn.association-failure')">
                <i class="iconfont iconguanlian2"></i>
              </a-tooltip>
            </a>
            <!-- 删除 -->
            <a class="ml10 operate-btn" :disabled="!$api.btnPms" @click="delFail(row)">
              <a-tooltip :title="$t('global-btn.delete')">
                <i class="iconfont iconshanchu"></i>
              </a-tooltip>
            </a>
          </template>
        </a-table>
      </div>
      <!-- 点击，从历史失效案例库添加 -->
      <a-modal v-model="visiblePQCPModel" :width="widthValue" @afterClose="closeModal" :destroyOnClose="true"
        :maskClosable="false" :footer="null" :dialog-style="topValue" :body-style="bodyStyle">
        <template slot="title">
          <span>{{ this.modalTitle }}</span>
          <!-- 全屏 -->
          <a-icon v-if="!fullScreenFlag" type="fullscreen" class="fullScreen" @click="changeFullScreen" />
          <!-- 取消全屏 -->
          <a-icon v-if="fullScreenFlag" type="fullscreen-exit" class="fullScreen" @click="changeFullScreen" />
        </template>
        <PQCP-selector @closeModal="closeModal" ref="childPQCPModal" />
      </a-modal>
      <view-drawer @closeDrawer="closeDrawer" :showViewDrawer="showViewDrawer" ref="look" :failExpId="failExpId"
        :case="currentCase" />
    </div>
  </div>
</template>

<script>

import PQCPSelector from "./components/PQCPSelector";
import { checkHotTableLength } from "@/utils/validate";
import ViewDrawer from "./components/components/index";
import VueDraggableResizable from "vue-draggable-resizable";
import moment from 'moment';


export default {
  name: "survey",
  components: {
    PQCPSelector,
    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,
      /**全屏标识 */
      fullScreenFlag: false,
      /**弹窗宽度 */
      widthValue: 1000,
      /**弹窗高度位置 */
      topValue: {},
      /**弹窗样式 */
      bodyStyle: {},
      /** 表格高度 */
      tableHeight: window.innerHeight-417,
      showViewDrawer: false, //点击编号查看详情
      failExpId: 0,
      currentCase: null,
      timeValue: undefined,
      visiblePQCPModel: false,
      total: 0,
      fmeaId: this.$store.getters.fmeaId,
      typeDict: [], //种类字典
      sourceDict: [], //来源字典
      // 表格列
      tableColumns: [
        // 序号
        {
          title: () => this.$t("research.serial-number"),
          width: 50,
          align: "center",
          customRender: (value, row, index) => {
            return (
              (this.pagination.current - 1) * this.pagination.pageSize +
              1 +
              index
            );
          },
          ellipsis: true
        },
        // 问题编号
        {
          title: () => this.$t("research.problem-number"),
          width: 150,
          align: "center",
          dataIndex: "issueCode",
          scopedSlots: {
            customRender: "issueCode"
          },
          ellipsis: true
        },
        // 来源
        {
          title: () => this.$t("research.source"),
          width: 150,
          align: "center",
          dataIndex: "source",
          scopedSlots: {
            customRender: "source"
          },
          ellipsis: true
        },
        // 种类
        {
          title: () => this.$t("research.type"),
          width: 150,
          align: "center",
          dataIndex: "type",
          ellipsis: true
        },
        // 项目
        {
          title: () => this.$t("research.project"),
          align: "center",
          width: 150,
          dataIndex: "project",
          key: "project",
          ellipsis: true
        },
        // 负责人
        {
          title: () => this.$t("research.responsible"),
          width: 150,
          align: "center",
          dataIndex: "responsible",
          ellipsis: true
        },
        // 关闭时间
        {
          title: () => this.$t("research.close-time"),
          width: 150,
          align: "center",
          dataIndex: "closeDate",
          scopedSlots: {
            customRender: "pqcpCloseDate"
          },
          ellipsis: true
        },
        // 结构代码
        {
          title: () => this.$t("research.structure-code"),
          width: 150,
          align: "center",
          dataIndex: "svpps",
          ellipsis: true
        },
        // 是否适用
        {
          title: () => this.$t("research.is-it-applicable"),
          width: 150,
          align: "center",
          dataIndex: "isApply",
          scopedSlots: {
            customRender: "isApply"
          },
          ellipsis: true
        },
        // 不适用原因
        {
          title: () => this.$t("research.reason-not-applicable"),
          width: 200,
          align: "center",
          dataIndex: "notApplyReason",
          scopedSlots: {
            customRender: "notApplyReason"
          },
          ellipsis: true
        },
        // 关联失效
        {
          title: () => this.$t("research.association-failure"),
          width: 150,
          align: "center",
          dataIndex: "relationFault",
          scopedSlots: {
            customRender: "relationFault"
          },
          ellipsis: true
        },
        // 操作
        {
          title: () => this.$t("research.operate"),
          width: 100,
          align: "center",
          fixed: "right",
          scopedSlots: {
            customRender: "action"
          },
          ellipsis: true
        }
      ],
      sourceData: [],
      applyInputValue: "", //用来储存适用不适用原因的
      applySelectValue: undefined, //用来储存适用不适用下拉值的
      queryData: {}, //用来储存点击查询按钮时查询条件，只有点击查询按钮时，查询条件才会更改
      searchData: {
        issueCode: undefined, //问题编号
        title: undefined, //标题
        svpps: undefined, //SVPPS
        project: undefined, //项目
        pqcpCloseStartDate: undefined,
        pqcpCloseEndDate: undefined,
        source: undefined, //来源
        type: undefined, //种类
        analyzeStatus: undefined, // 分析状态
        responsible: undefined // 责任人
      },
      outTablePageNo: 1,
      outTablePageSize: 10,
      total3: 0,
      searchData3: {
        applyFlag: undefined, //是否适用本DFMEA
        relationFlag: undefined, //是否关联
        dfmeaCode: undefined, //FMEA编号
        classify: undefined
      },
      modelPageNo: 1,
      modelPageSize: 10,
      modalTitle: "添加问题",
      historyData: [],
      historyData1: [],
      surveyQueryData: [],
      showNumber: 18,
      // 暂时的
      showFlag: true,
      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,
      contentHeight: window.innerHeight - 104 + 'px'
    };
  },
  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
    }
  },
  mounted() {
    window.onresize = () => {
      this.contentHeight = window.innerHeight - 104 + 'px';
      this.tableHeight =  window.innerHeight-417;
    };
    this.showFlag = true;
    if (this.showFlag) {
      this.showNumber = 18;
    } else {
      this.showNumber = 24;
    }
    window.addEventListener("resize", this.watchSurveyResize);
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.watchSurveyResize);
    });
    // this.getTableHeight();
    if (this.$route.query.backFlag) {
      // this.advanceExpand = true;
      // 如果是通过返回按钮返回，则不重置筛选条件，直接应用来源页面的路由参数
      this.searchData = {
        issueCode: this.$route.query.issueCode,
        title: this.$route.query.title,
        svpps: this.$route.query.svpps,
        project: this.$route.query.project,
        pqcpCloseStartDate: this.$route.query.pqcpCloseStartDate,
        pqcpCloseEndDate: this.$route.query.pqcpCloseEndDate,
        source: this.$route.query.source,
        type: this.$route.query.type,
        analyzeStatus: this.$route.query.analyzeStatus,
        responsible: this.$route.query.responsible
      };
      // 展开折叠
      this.advanceExpand = this.$route.query.advanceExpand;
      // 关闭时间
      if (this.$route.query.pqcpCloseStartDate || this.$route.query.pqcpCloseEndDate) {
        this.timeValue = [moment(this.$route.query.pqcpCloseStartDate, 'YYYY-MM-DD'), moment(this.$route.query.pqcpCloseEndDate, 'YYYY-MM-DD')];
      }
      this.queryData = this.searchData;
      this.outTablePageNo = this.$route.query.pageNum;
      // 根据获取的筛选条件重新请求数据
      this.getResearchPageList();
    } else {
      this.getResearchPageList();
      // this.advanceExpand = false;
    }
    this.initDict();
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
    // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
    this.getTableDivCss();
  },
  // 剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },

  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;
    },
    /**
     * 取得表格高度
     */
    getTableHeight() {
      this.$nextTick(() => {
        let dom = this.$refs.survey;
        // 页面顶部高度
        let antLayoutHeaderH = document.querySelector(".ant-layout-header").offsetHeight;
        // 页面容器margin：选项卡顶部高度 - 页面顶部高度
        let antTabsDom = document.querySelector(".ant-card");
        let antLayoutContentMargin = antTabsDom.offsetTop - antLayoutHeaderH;
        // 选项卡border
        let antCardBorderedStyle = window.getComputedStyle(
          document.querySelector(".ant-card-bordered"),
          null
        );
        let antCardBorderedBorder = parseFloat(
          antCardBorderedStyle.getPropertyValue("border-top")
        );
        // 选项卡padding
        let antCardBodyStyle = window.getComputedStyle(
          document.querySelector(".ant-card-body"),
          null
        );
        let antCardBodyPadding = parseFloat(
          antCardBodyStyle.getPropertyValue("padding")
        );
        // 表格表头高度
        let antTableTheadH = dom.querySelector(".ant-table-thead").offsetHeight;
        // 表格border
        let antTableSmallStyle = window.getComputedStyle(
          dom.querySelector(".ant-table-small"),
          null
        );
        let antTableSmallBorder = parseFloat(
          antTableSmallStyle.getPropertyValue("border-top")
        );
        // 表格分页56，固定值
        let antTablePaginationH = 56;
        let fromH = dom.querySelector(".survey-form").offsetHeight;
        let otherDomH =
          antLayoutHeaderH +
          antCardBodyPadding * 2 +
          antLayoutContentMargin * 2 +
          antCardBorderedBorder * 2 +
          fromH +
          antTableTheadH +
          antTableSmallBorder * 2 +
          antTablePaginationH;
        this.tableHeight = "calc(100vh - " + otherDomH + "px)";
      });
    },
    /**
     * 监听窗口大小调整
     */
    watchSurveyResize() {
      // this.getTableHeight();
    },
    closeDrawer() {
      this.showViewDrawer = false;
    },
    //查看
    viewCase(data) {
      this.currentCase = data;
      this.failExpId = parseInt(data.historyFailId);
      this.showViewDrawer = true;
      this.$refs.look.historyfailDetail(data.historyFailId);
    },
    // 表格 - 点击分页中数字触发的方法
    handleOuterTableChange(pagination) {
      this.outTablePageNo = pagination.current;
      this.outTablePageSize = pagination.pageSize;
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getResearchPageList();
    },
    // 重置
    reset() {
      this.timeValue = undefined;
      this.queryData = {};
      this.searchData = {
        issueCode: undefined, //问题编号
        title: undefined, //标题
        svpps: undefined, //SVPPS
        project: undefined, //项目
        pqcpCloseDate: undefined, //关闭时间
        pqcpCloseStartDate: undefined,
        pqcpCloseEndDate: undefined,
        source: undefined, //来源
        type: undefined, //种类
        analyzeStatus: undefined, // 分析状态
        responsible: undefined // 责任人
      };
      this.outTablePageNo = 1;
      this.outTablePageSize = 10;
      this.pagination.pageSize = 10;
      this.pagination.current = 1;
      this.getResearchPageList();
    },
    filterOption(input, option) {
      return option.componentOptions.propsData.value.indexOf(input) > -1;
    },
    divisionNameChange(data, dataString) {
      if (!dataString) {
        this.searchData.pqcpCloseDate = "";
        this.searchData.pqcpCloseStartDate = "";
        this.searchData.pqcpCloseEndDate = "";
        return;
      }
      this.searchData.pqcpCloseDate = dataString;
      this.searchData.pqcpCloseStartDate = dataString[0];
      this.searchData.pqcpCloseEndDate = dataString[1];
    },
    //重置
    resetRST() {
      this.searchData3 = {
        applyFlag: undefined, //是否适用本DFMEA
        relationFlag: undefined, //是否关联
        dfmeaCode: undefined, //FMEA编号
        classify: undefined
      };
      this.searchData.pqcpCloseStartDate = "";
      this.searchData.pqcpCloseEndDate = "";
    },
    search3() {
      this.modelPageNo = 1;
    },
    search() {
      this.queryData = this.searchData;
      this.outTablePageNo = 1;
      this.getResearchPageList();
    },
    getResearchPageList() {
      let data = {
        pageNo: this.outTablePageNo,
        pageSize: this.outTablePageSize,
        fmeaId: this.$com.fmeaId,
        ...this.queryData
      };
      this.$api.getResearch(data).then(res => {
        if (res.flag) {
          this.addParameters(res.data.data);
          this.sourceData = res.data.data;
          this.pagination.total = res.data.total;
          this.total = res.data.total;
          this.pagination.current = res.data.pageNo;
        } else {
          this.$message.error(res.messsage, 1);
        }
      });
    },
    //给每条数据添加一条参数
    addParameters(data) {
      for (var i in data) {
        this.$set(data[i], "isEdit", false);
      }
      return data;
    },
    add() {
      this.visibleModel = true;
      this.modalTitle = "添加问题";
    },
    addPQCP() {
      this.visiblePQCPModel = true;
      this.modalTitle = this.$t(
        "research.add-from-historical-failure-case-library"
      );
    },
    closeModal() {
      this.visiblePQCPModel = false;
      this.getResearchPageList();
    },
    toDetail(row, type) {
      this.$router.push({
        path: "/analyse",
        query: {
          id: row.id,
          type: type,
          fmeaId: this.$store.getters.fmeaId,
          rfmeaId: this.$store.getters.rfmeaId,
          // from: this.$route.query.from,
          back: this.$route.query.back,
          from: this.$route.fullPath, // 将当前页面路径作为来源页面
          ...this.searchData, // 传递筛选条件
          pageNum: this.outTablePageNo, // 传递当前页数
          advanceExpand: this.advanceExpand, // 展开折叠
          ntimet: new Date().getTime()
        }
      });
    },
    //调研分页列表删除
    delFail(record) {
      var _that = this;
      _that.$api
        .delResearch({ id: record.id, fmeaId: _that.$store.getters.fmeaId })
        .then(response => {
          if (response.flag) {
            _that.$message.success(response.message);
            this.queryData = this.searchData;
            if (this.outTablePageNo != 1 && this.sourceData.length == 1) {
              this.outTablePageNo -= 1;
            }
            this.getResearchPageList();
          } else {
            _that.$message.error(response.message);
          }
        });
    },
    //无需说明点击时事件
    applyClick(row) {
      if (!this.$api.btnPms) {
        return;
      }
      this.applyInputValue = "";
      this.applyInputValue = row.notApplyReason;
      row.isEdit = true;
      //获取焦点，延迟100ms是为了能获取到焦点
      setTimeout(() => {
        document.getElementById("applyInput" + row.id).focus();
      }, 100);
    },
    //不适用点击说明时
    noApplyClick(row) {
      if (!this.$api.btnPms) {
        return;
      }
      this.applyInputValue = "";
      this.applyInputValue = row.notApplyReason;
      row.isEdit = true;
      //获取焦点，延迟100ms是为了能获取到焦点
      setTimeout(() => {
        document.getElementById("noApplyInput" + row.id).focus();
      }, 100);
    },
    //下拉框获取到焦点时
    applyFocus(row) {
      this.applySelectValue = undefined;
      this.applySelectValue = row.isApply;
    },
    applyChange(row) {
      var _that = this;
      //下拉框改变时
      if (row.isApply === 0 && row.relationFault === "已关联")
        this.$confirm({
          title: this.$t("global-message.warn"),
          content: this.$t("global-message.warn.change-clean-data"),
          icon: "question-circle", //图标，不想用就随便写一个
          okText: this.$t("global-btn.ok"),
          cancelText: this.$t("global-btn.cancel"),
          onOk() {
            _that.updateResearch(row);
          },
          onCancel() {
            row.isApply = 1;
          }
        });
      else this.updateResearch(row);
    },
    //适用，原因blur事件
    applyInputBlur(row) {
      this.updateResearch(row);
    },
    //不适用，原因blur事件
    notApplyInputBlur(row) {
      this.updateResearch(row);
    },
    updateResearch(row) {
      if (checkHotTableLength(row.notApplyReason, 500)) {
        this.$message.warning("原因不能超过500个字符");
        return;
      }
      this.$api.updateResearch({
          id: row.id,
          isApply: row.isApply,
          historyFailId: row.historyFailId,
          notApplyReason: row.isApply === 0 ? row.notApplyReason : '',
          fmeaId: this.$store.getters.fmeaId
        }).then(res => {
          if (res.flag) {
            row.isEdit = false;
            this.$message.success(res.message);
            this.getResearchPageList();
          } else {
            this.$message.error(res.message);
            row.isApply = this.applySelectValue;
            row.notApplyReason = this.applyInputValue;
          }
        }).catch(err => {
          this.$message.error("未知错误，请联系管理员!");
          row.isApply = this.applySelectValue;
          row.notApplyReason = this.applyInputValue;
        });
    },
    //种类 来源，字典
    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;
        }
      });
    },
    // 切换全屏
    changeFullScreen() {
      this.fullScreenFlag = !this.fullScreenFlag;
      if (this.fullScreenFlag) {
        this.topValue = { top: 0 };
        this.bodyStyle = { height: '100vh' };
        this.widthValue = '100vw';
      } else {
        this.topValue = {};
        this.bodyStyle = {};
        this.widthValue = 1000;
      }
    }
  },
  //历史版本查询
  computed: {},
  filters: {}
};
</script>
<style lang="less" scoped>
.ant-pro-basicLayout-content {
  margin: 10px;
}

.fullScreen {
  cursor: pointer;
  position: absolute;
  right: 60px;
  color: gray;
  margin-top: 3px;
}

</style>
