<template>
  <div>
    <a-row class="content-box">
      <a-card class="layout-card card" :title="$t('plan.dvp.create-dvp-plan')">
        <a-form layout="inline">
          <a-row class="title-padding" :gutter="24">
            <!--零部件名称-->
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item style="white-space: nowrap" :label="$t('workbench.compoment-name') + '::'">
                {{ this.$route.query.partName ? this.$route.query.partName : "--" }}
              </a-form-item>
            </a-col>
            <!--零部件编号-->
            <a-col :xl='6' :lg='8' :md='24' :sm='24' :xs='24'>
              <a-form-item style="white-space: nowrap" :label="$t('workbench.compoment-number') + '::'">
                <span  class="ml8">{{ this.$route.query.partNo ? this.$route.query.partNo : "--" }}</span>
              </a-form-item>
            </a-col>
            <!-- cpac编号 -->
            <a-col :xl='6' :lg='8' :md='24' :sm='24' :xs='24'>
              <a-form-item style="white-space: nowrap" :label="$t('verity.dvp.cpac.number') + '::'">
                <span  class="ml8">{{ this.$route.query.cpacCode ? this.$route.query.cpacCode : "--" }}</span>
              </a-form-item>
            </a-col>
            <!--FND代码-->
            <a-col :xl='6' :lg='8' :md='24' :sm='24' :xs='24'>
              <a-form-item style="white-space: nowrap" :label="$t('verity.dvp.fnd.code') + '::'">
                <span  class="ml8">{{ this.$route.query.fndCode ? this.$route.query.fndCode : "--" }}</span>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card class="layout-card cardOverFlow" :style="{ height: tableHeight }">
        <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('plan.dvp.test-type')">
                <a-select v-model="formData.testType" :options="testTypeList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('plan.dvp.please_select-test-type')"></a-select>
              </a-form-item>
            </a-col>
            <!--试验来源-->
            <a-col :xl='6' :lg='8' :md='24' :sm='24' :xs='24'>
              <a-form-item :label="$t('plan.dvp.test-source')">
                <a-select v-model="formData.testSource" :options="testSourceList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('global-btn.please-select') + $t('plan.dvp.test-source')"></a-select>
              </a-form-item>
            </a-col>
            <!--试验项目-->
            <a-col :xl='6' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('plan.dvp.test-project')">
                <a-input allowClear :maxLength='500' v-model.trim="formData.testProject" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-project')"/>
              </a-form-item>
            </a-col>
            <!--开发目标要求-->
            <a-col :xl='6' :lg='8' :md='24' :sm='24' :xs='24'>
              <a-form-item :label="$t('base.info.development-objective-requirements')">
                <a-input allowClear :maxLength='50' v-model.trim="formData.targetRequire" :placeholder="$t('global-btn.please-enter') + $t('base.info.development-objective-requirements')"/>
              </a-form-item>
            </a-col>
            <span v-show="advanceExpand">
              <!--试验标准-->
              <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
                <a-form-item :label="$t('base.info.Test-standards')">
                 <a-input v-model.trim="formData.testStandard" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('base.info.Test-standards')"/>
                </a-form-item>
              </a-col>
              <!--测试负责人-->
              <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
                <a-form-item :label="$t('plan.dvp.test-user')">
                  <a-select v-model="formData.testOwner" :options="testOwnerList"  allowClear :placeholder="$t('global-btn.please-select') + $t('plan.dvp.test-user')"></a-select>
                </a-form-item>
              </a-col>
              <!--测试地点-->
              <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
                <a-form-item :label="$t('plan.dvp.test-site')">
                 <a-input v-model.trim="formData.testSite" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-site')"/>
                </a-form-item>
              </a-col>
              <!--数据来源-->
              <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
                <a-form-item :label="$t('plan.dvp.data-sources')">
                  <a-select v-model="formData.dataSource" :options="dataSourceList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('global-btn.please-select') + $t('plan.dvp.data-sources')"></a-select>
                </a-form-item>
              </a-col>
              <!--计划结束时间-->
              <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
                <a-form-item :label="$t('plan.dvp.scheduled-end-time')">
                  <a-range-picker v-model="endTime" @change="handleQueryEndTime" allowClear valueFormat="YYYY-MM-DD" style="width: 100%" />
                </a-form-item>
              </a-col>
            </span>
          </a-row>
          <a-row :gutter="24">
            <a-form-item class='tr' :label="'\xa0'">
              <a-col :xl='24' :lg='24' :md='24' :sm='24' :xs='24'>
                <!-- 展开/收起 -->
                <a @click="toggleAdvance" class="mr10">
                  {{ advanceExpand ? $t('plan.dvp.collapse') : $t('plan.dvp.expand') }}
                  <a-icon :type="advanceExpand ? 'up' : 'down'"/>
                </a>
                <!-- 重置 -->
                <a-button @click='reset' class="mr10">
                  {{ $t('global-btn.reset') }}
                </a-button>
                <!-- 查询 -->
                <a-button @click='search' type="primary" class="mr12">
                  {{ $t('global-btn.search') }}
                </a-button>
              </a-col>
            </a-form-item>
          </a-row>
        </a-form>
        <a-form-item class='tr' >
          <!-- 新建零部件DVP -->
          <a-button :disabled="isLook || applyButtonFlag" @click='addComponentDvp' type="primary" class="ml10">
            {{ $t('global-btn.new') }}
          </a-button>
          <!-- 模板添加 -->
          <a-button :disabled="isLook || applyButtonFlag" @click='addTemplateDvP' type="primary" class="ml10">
            {{ $t('plan.dvp.template-add') }}
          </a-button>
          <!-- 历史项目添加 -->
          <a-button :disabled="isLook || applyButtonFlag" @click='addHistoryDvp' type="primary" class="ml10">
            {{ $t('plan.dvp.history-dvp-add') }}
          </a-button>
        </a-form-item>
        <a-table
          ref="tableRef"
          size="small"
          class="table-mr"
          :columns='tableColumns'
          :dataSource='tableData'
          :rowKey='(record, index) => { return index; }'
          :scroll='{ x: tableWidth, y: tableHeightValue }'
          :pagination='pagination'
          :loading='tableLoading'
          @change='handlePageChange'
          bordered
          :components='components'
        >
          <!-- 序号列 -->
          <template slot='index' slot-scope='text, record, index'>
            <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
          </template>
          <!-- 是否等效 -->
          <template slot='isEquivalent' slot-scope='text, record'>
            <span>{{ isOrNotMap[record.isEquivalent] || '-' }}</span>
          </template>
          <!-- 是否开展试验 -->
          <template slot="isCarryOut" slot-scope="text, record">
            <span :title="text"> {{ isCarryOutMap[record.isCarryOut] || '-' }} </span>
          </template>
          <!-- 等效实验报告编号 -->
          <template slot='equivalentTestCode' slot-scope='text, record'>
            <span class="clickContent" @click="viewReport(record)" :title="text">{{ record.equivalentTestCode }}</span>
          </template>
          <!-- 数据来源 -->
          <template slot='dataSource' slot-scope='text, record'>
            <span>{{ dataSourceMap[record.dataSource] || '-' }}</span>
          </template>
          <!-- 试验类型 -->
          <template slot="testType" slot-scope="text, record">
            <span :title="text"> {{ testTypeMap[record.testType] || '-' }} </span>
          </template>
          <!-- 试验来源 -->
          <template slot="testSource" slot-scope="text, record">
            <span :title="text"> {{ testSourceMap[record.testSource] || '-' }} </span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <span>
              <!-- 编辑 -->
             <a class='operation-btn ml16' @click='editInit(record)' :disabled="isLook || applyButtonFlag">
               <a-tooltip :title="$t('global-btn.edit')">
                 <i class="iconfont iconicon-bainji"></i>
               </a-tooltip>
             </a>
              <!-- 申请变更 -->
               <a class='operation-btn' @click="applyChange(record)" v-if="applyButtonFlag" :disabled="isLook">
                <a-tooltip :title="$t('global-btn.apply-for-changes')">
                  <i class="iconfont  iconprocess_branch"></i>
                </a-tooltip>
              </a>
              <!-- 删除 -->
             <a class='operation-btn' @click="deleteDvpData(record)" :disabled="isLook || applyButtonFlag || record.dataSource === '2'">
                <a-tooltip :title="$t('global-btn.delete')">
                  <i class="iconfont iconshanchu"></i>
                </a-tooltip>
              </a>
            </span>
          </template>
        </a-table>
      </a-card>
    </a-row>

    <!--新建零部件DVP弹框-->
    <a-modal
      :title="$t('plan.dvp.create-dvp')"
      :visible="isEditDVP"
      :maskClosable="false"
      @ok="saveEditDvp"
      @cancel="cancelEditDvp"
      :width="1000"
    >
      <edit-dvp ref="editDvp" @cancelEditDvp="cancelEditDvp" @initData="initData"/>
    </a-modal>
    <!-- 模板添加弹框 -->
    <a-modal
      :title="$t('plan.dvp.template-add')"
      :visible="isEditTemplate"
      :maskClosable="false"
      @ok="saveEditDvp"
      @cancel="cancelEditDvp"
      :width="1000"
    >
      <template-edit ref="templateEdit" @cancelEditDvp="cancelEditDvp" @initData="initData"/>
    </a-modal>
    <!-- 历史项目添加弹框 -->
    <a-modal
      :title="$t('plan.dvp.history-dvp-add')"
      :visible="isEditHistory"
      :maskClosable="false"
      @ok="saveEditDvp"
      @cancel="cancelEditDvp"
      :width="1000"
    >
      <history-dvp-edit ref="historyDvpEdit" @cancelEditDvp="cancelEditDvp" @initData="initData"/>
    </a-modal>

    <!-- 编辑表格行数据弹框 -->
    <edit-table-row ref="editTableRow" @closeEditRowModal="closeEditRowModal" @initData="initData" :isEditRow="isEditRow"></edit-table-row>

    <!--申请变更-->
    <apply-change ref="applyChange" :applyFlag="applyFlag" :applyTableData="applyTableData" :dvpType="dvpType" @closeModal="closeModal" @initData="initData"></apply-change>
    <!-- 文件预览 -->
    <view-office ref="viewModal"/>

  </div>
</template>

<script>

import EditDvp from "./editModal/editDvp";
import HistoryDvpEdit from "./editModal/historyDvpEdit";
import ProjectFmeaEdit from "./editModal/projectFmeaEdit";
import TemplateEdit from "./editModal/templateEdit";
import EditTableRow from "./editModal/editTableRow";
import ApplyChange from "./editModal/applyForChange";
import VueDraggableResizable from 'vue-draggable-resizable';
import ViewOffice from "@/components/viewOffice/viewOffice";

export default {
  components: {
    EditDvp,
    HistoryDvpEdit,
    ProjectFmeaEdit,
    TemplateEdit,
    EditTableRow,
    ApplyChange,
    VueDraggableResizable,
    ViewOffice
  },
  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, 90);
              }
            }
          };
          const drag = h('vue-draggable-resizable', { ...dragProps });
          return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
        }
      }
    };
    return{
      /** 查询数据 */
      formData:{},
      /** 基本信息数据源 */
      baseInfo: {},
      /** 清除时间选框用的 */
      endTime: undefined,
      startTime: undefined,
      /** 折叠 展开 */
      advanceExpand: false,
      /** 分页 */
      pagination: {
        size: 'small',
        current: 1,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: total => this.$t('global-constant.table.show-total', {total: `${total}`}), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100', '200'], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        total: 0, //总条数
        showQuickJumper: true,
      },
      // 表格总宽度
      tableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
      /** 表格高度 */
      tableHeight: window.innerHeight - 310 + 'px',
      tableHeightValue: window.innerHeight - 352,
      /** 表格加载状态 */
      tableLoading: false,
      /** 表格数据 */
      tableData: [],
      /** 表格列 */
      tableColumns: [
        //序号
        {
          title: this.$t('plan.dvp.serial-number'),
          key: 'index',
          width: 100,
          fixed: 'left',
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true
        },
        // 试验类型
        {
          title: this.$t('plan.dvp.test-type'),
          width: 150,
          dataIndex: 'testType',
          align: 'center',
          scopedSlots: {
            customRender: "testType"
          },
        },
        // 试验来源
        {
          title: this.$t('plan.dvp.test-source'),
          width: 150,
          dataIndex: 'testSource',
          align: 'center',
          scopedSlots: {
            customRender: "testSource"
          },
        },
        // 数据来源
        {
          title: this.$t('plan.dvp.data-sources'),
          width: 100,
          dataIndex: 'dataSource',
          align: 'center',
          ellipsis: true,
          scopedSlots: {customRender: 'dataSource'},
        },
        // 试验项目
        {
          title: this.$t('plan.dvp.test-project'),
          width: 180,
          dataIndex: 'testProject',
          align: 'center',
          ellipsis: true
        },
        // 开发目标要求
        {
          title: this.$t('base.info.development-objective-requirements'),
          width: 180,
          dataIndex: 'targetRequire',
          align: 'center',
          ellipsis: true
        },
        // 试验标准和试验方法
        {
          title: this.$t('plan.dvp.test-standards-and-test-method'),
          width: 150,
          dataIndex: 'testStandard',
          align: 'center',
          ellipsis: true
        },
        // 是否开展试验
        {
          title: this.$t('base.info.whether-to-develop-experimental-projects'),
          width: 150,
          dataIndex: 'isCarryOut',
          align: 'center',
          scopedSlots: {
            customRender: "isCarryOut"
          }
        },
        // 不开展试验原因
        {
          title: this.$t('base.info.reason-for-not-conducting-the-experiment'),
          width: 150,
          dataIndex: 'notCarryOutCause',
          align: 'center',
          ellipsis: true
        },
        // 是否等效试验
        {
          title: this.$t('plan.dvp.is-it-an-equivalent-test'),
          width: 150,
          dataIndex: 'isEquivalent',
          align: 'center',
          ellipsis: true,
          scopedSlots: {
            customRender: 'isEquivalent'
          }
        },
        // 等效试验报告编号
        {
          title: this.$t('plan.dvp.equivalent-report-code'),
          width: 150,
          dataIndex: 'equivalentTestCode',
          align: 'center',
          scopedSlots: {
            customRender: "equivalentTestCode"
          }
        },
        // 测试地点
        {
          title: this.$t('plan.dvp.test-site'),
          width: 150,
          dataIndex: 'testSite',
          align: 'center',
          ellipsis: true
        },
        // 测试负责人
        {
          title: this.$t('plan.dvp.test-user'),
          width: 100,
          dataIndex: 'testOwner',
          align: 'center',
          ellipsis: true
        },
        // 测试阶段
        {
          title: this.$t('plan.dvp.test-step'),
          width: 150,
          dataIndex: 'testStep',
          align: 'center',
          ellipsis: true
        },
        // 测试次数
        {
          title: this.$t('plan.dvp.test-count'),
          width: 100,
          dataIndex: 'testFrequency',
          align: 'center',
          ellipsis: true
        },
        // 样本数量
        {
          title: this.$t('plan.dvp.number-of-samples'),
          width: 100,
          dataIndex: 'sampleNumber',
          align: 'center',
          ellipsis: true
        },
        // 样件类型
        {
          title: this.$t('plan.dvp.sample-type'),
          width: 100,
          dataIndex: 'sampleType',
          align: 'center',
          ellipsis: true
        },
        // 评审意见
        {
          title: this.$t('plan.dvp.review.comments'),
          width: 100,
          dataIndex: 'planReviewComment',
          align: 'center',
          ellipsis: true
        },
        // 计划结束时间
        {
          title: this.$t('plan.dvp.scheduled-end-time'),
          width: 130,
          dataIndex: 'planEndTime',
          align: 'center',
          ellipsis: true
        },
        //操作
        {
          title: this.$t('global-constant.operation'),
          key: 'action',
          align: 'center',
          width: 100,
          fixed: 'right',
          scopedSlots: {customRender: 'action'},
          ellipsis: true
        }
      ],
      /** 是/否Map 用于表格插槽显示 */
      isOrNotMap: {
        0: this.$t("global-btn.no"),
        1: this.$t("global-btn.yes")
      },
      /** 试验类型字典  未确定具体字段-暂时写死*/
      testTypeList: [
        {
          value: '1',
          label: this.$t('dvp.appearance')
        },
        {
          value: '2',
          label: this.$t('dvp.size')
        },
        {
          value: '3',
          label: this.$t('dvp.material-regulations')
        },
        {
          value: '4',
          label: this.$t('dvp.performance-and-functionality')
        }
      ],
      testTypeMap: {
        '1': this.$t('dvp.appearance'),
        '2': this.$t('dvp.size'),
        '3': this.$t('dvp.material-regulations'),
        '4': this.$t('dvp.performance-and-functionality')
      },
      /** 试验来源下拉选项  未确定具体字段-暂时写死*/
      testSourceList: [
        {
          value: '1',
          label: this.$t('dvp.drawing')
        },
        {
          value:  '2',
          label: this.$t('dvp.KPC')
        },
        {
          value: '3',
          label: this.$t('dvp.web-require')
        },
        {
          value: '4',
          label: this.$t('dvp.standard')
        },
        {
          value: '5',
          label: this.$t('dvp.laws-and-regulations')
        }
      ],
      testSourceMap: {
        '1': this.$t('dvp.drawing'),
        '2': this.$t('dvp.KPC'),
        '3': this.$t('dvp.web-require'),
        '4': this.$t('dvp.standard'),
        '5': this.$t('dvp.laws-and-regulations')
      },
      /** 权限 */
      isLook: false,
      /** 新建零部件DVP弹框 是否显示、关闭 */
      isEditDVP: false,
      /** 模板添加弹框 是否显示、关闭 */
      isEditTemplate: false,
      /** 历史项目添加弹框 是否显示、关闭 */
      isEditHistory: false,
      /** 测试负责人下拉选项 */
      testOwnerList: [],
      /** CPAC List */
      CPACList: [],
      /** FND Code List */
      fndCodeList: [],
      /** 部门下拉选项 List */
      departmentList: [],
      /** 数据来源下拉选项 List  数据来源 0手动修改 1模板 2DFMEA 3历史DVP */
      dataSourceList: [
        {
          label: this.$t("global-btn.new"),
          value: '0'
        },
        {
          label: this.$t("plan.dvp.test-source-dvp-template"),
          value: '1'
        },
        {
          label: this.$t("plan.dvp.test-source-DFMEA"),
          value: '2'
        },
        {
          label: this.$t("plan.dvp.history-dvp"),
          value: '3'
        }
      ],
      /** 数据来源Map 用于表格插槽显示 数据来源 0手动修改 1模板 2DFMEA 3历史DVP */
      dataSourceMap: {
        '0': this.$t("global-btn.new"),
        '1': this.$t("plan.dvp.test-source-dvp-template"),
        '2': this.$t("plan.dvp.test-source-DFMEA"),
        '3': this.$t("plan.dvp.history-dvp")
      },
      /** 编辑表格行数据弹框 是否显示、关闭 */
      isEditRow: false,
      /** 申请变更弹窗 是否显示、关闭 */
      applyFlag: false,
      /** 申请变更弹窗表格数据 */
      applyTableData: [],
      /** 申请变更按钮 是否显示 */
      applyButtonFlag: false,
      /** dvpType system:系统DVP，components:零部件DVP */
      dvpType: "components",
      cpacId: this.$store.getters.cpacId,
      /** 是否开展试验 */
      isCarryOutMap: {
        '0' : this.$t('global-btn.no'),
        '1' : this.$t('global-btn.yes')
      }
    }
  },
  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() {
    this.isLook = this.$api.isLook === '1'
    this.initData();
    this.getDepartmentList();
    this.getDvpTestOwnerList();
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 352 + 'px';
      this.tableHeightValue = window.innerHeight - 352;
    };
    // 监听页面窗体大小变化
    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(250, 250, 250)';
        // 表头外层盒子的的实际样式
        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.$el.offsetWidth;
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal(){
      this.columnsWidth = this.tableColumns.reduce((sum, column) => sum + column.width, 0);
    },
    // 动态修改fixe的属性以便表格样式不出现空白列,并平和各列与表格的总宽度
    changeFixed(){
      if (this.columnsWidth <= this.tableWidth) {
        // 遍历 tableColumns 数组，将有 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[this.tableColumns.length - 1].fixed='right';
        // 恢复最后一列原始宽度
        this.tableColumns[this.tableColumns.length - 1].width = 100;
      }
    },
    /**
     * 初始化表格数据
     */
    initData() {
      let _that = this;
      _that.tableLoading = true;
      _that.formData.dvpId = _that.$store.getters.dvpId;
      _that.formData.partId = _that.$route.query.partId;
      _that.formData.pagination = {
        pageSize: _that.pagination.pageSize,
        pageCurrent: _that.pagination.current
      }
      _that.formData.systemTestSource = _that.formData.dataSource;
      _that.$api.initDvpTestList(_that.formData).then(res => {
        if (res.flag) {
          _that.tableData = res.data.data || [];
          _that.tableData.forEach( item => {
            if (item.equivalentTestCode) {
              item.isEquivalent = 1;
            } else {
              item.isEquivalent = 0;
            }
          });
          _that.pagination.total = res.data.total;
          if (res.data.data && res.data.data.length > 0) {
            _that.cpacId = res.data.data[0].cpacId;
            _that.getFndCodeList();
          }
        } else {
          _that.$message.error(res.message,1);
          _that.tableData = [];
          _that.pagination.total = 0;
        }
      }).finally(() => {
        _that.tableLoading = false;
      });

      // 变更申请按钮显示隐藏，如果DVP编制进行到DVP验证阶段，则显示
      let data = {
        dvpId: _that.$store.getters.dvpId,
        dvpType: _that.$store.getters.dvpType
      }
      _that.$api.getDvpCurrentStep(data).then(res => {
        if (res.flag) {
          _that.applyButtonFlag = res.data === 2 ;
        }
      });
    },

    /**
     *  获取团队成员 用于测试负责人下拉选
     */
    getDvpTestOwnerList() {
      let data = {
        dvpId: this.$store.getters.dvpId,
        dvpType: this.$store.getters.dvpType
      };
      this.$api.getDvpTeamMember(data).then(res => {
        if (res.flag) {
          let userList = res.data.teamMemberModels;
          let engineerList = res.data.engineerModels;
          userList.forEach(item => {
            if (item.permission === 1) {
              let options = {
                label: item.name,
                value: item.userId
              };
              this.testOwnerList.push(options);
            }
          });
          // 工程师数据处理
          engineerList.forEach(data => {
            let index = this.testOwnerList.findIndex(item => item.value === data.userId);
            if (index === -1) {
              let tempData = {
                label: data.name,
                value: data.userId
              };
              this.testOwnerList.push(tempData);
            }
          });
          // 是否包含Owner
          let ownerFlag = this.testOwnerList.find(item => item.value === this.$store.getters.dvpOwnerId);
          if (!ownerFlag) {
            // 测试负责人要包括DVP的Owner
            let owner = {
              label: this.$store.getters.dvpOwnerName,
              value: this.$store.getters.dvpOwnerId
            }
            this.testOwnerList.push(owner);
          }
        }
      });
    },


    /**
     * 获取FND代码下拉选数据
     */
    getFndCodeList(fndCode,cpacId) {
      let _that = this;
      _that.$api.getFndInfoList({
        fndCode: fndCode ? fndCode.toString() : '',
        fndCn: fndCode ? fndCode.toString() : '',
        cpacId: _that.cpacId
      }).then(res => {
        if (res.flag) {
          _that.fndCodeList = res.data || [];
          _that.fndCodeList.forEach(item => {
            item.fndValue = item.id + '-' + item.fndCode + item.fndCn;
          });
        } else {
          _that.$notification.error({message: res.message});
        }
      });
    },

    /**
     * 初始化CPAC下拉列表
     */
    getCpacInitData(cpacCoding) {
      let _that = this;
      _that.$api.getCpacInfoList({
        cpacCoding: cpacCoding,
        cpacCn: cpacCoding
      }).then(res => {
        if (res.flag) {
          let cpacData = res.data || [];
          _that.cpacList = [];
          if (cpacData.length > 0) {
            cpacData.forEach(item => {
              let temp = {
                key: item.cpacId,
                value: item.cpacCoding + '-' + item.cpacCn,
                label: item.cpacCoding + ' ' + item.cpacCn
              }
              _that.cpacList.push(temp);
            })
          }
        } else {
          _that.$notification.error({message: res.message});
        }
      });
    },

    /**
     * cpac下拉切换
     * @param value
     * @param options
     * @constructor
     */
    CPACChange(value,options) {
      this.queryParam.cpacId = options ? options.data.key : undefined;
      this.$forceUpdate();
      this.getFndCodeList(null,this.queryParam.cpacId);
    },

    /**
     * FND选择事件
     * @param value
     * @param options
     * @constructor
     */
    fndChange(value,options) {
      this.formData.fndId = options ? options.data.key : null;
      this.$forceUpdate();
    },

    /**
     * 部门 下拉选项
     * @param orgName
     */
    getDepartmentList(orgName) {
      this.$api.post('/DFMEA/fmea/org/getFuzzyOrg.do', {orgName: orgName}).then(res => {
        if (res.flag) {
          this.departmentList = res.data;
        } else {
          this.departmentList = [];
        }
      });
    },

    /**
     * 部门选择事件
     * @param value
     * @param options
     */
    orgInput(value, options) {
      this.formData.ownerDepartmentId = options ? options.data.key : undefined;
    },

    /**
     * 搜索模块按钮-查询
     */
    search() {
      this.initData();
    },

    /**
     * 搜索模块按钮-重置
     */
    reset() {
      this.endTime = undefined;
      this.startTime = undefined;
      this.formData = {};
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.advanceExpand = false;
      this.initData();
    },

    /**
     * 搜索模块按钮-收起/展开
     */
    toggleAdvance() {
      this.advanceExpand = !this.advanceExpand;
    },

    /**
     * 表格上方按钮-新建零部件DVP
     */
    addComponentDvp() {
      this.isEditDVP = true;
    },
    /**
     * 表格上方按钮-模板添加
     */
    addTemplateDvP() {
      this.isEditTemplate = true;
    },
    /**
     * 表格上方按钮-历史项目添加
     */
    addHistoryDvp() {
      this.isEditHistory = true;
    },

    /**
     * 编辑零部件DVP-确认按钮
     */
    saveEditDvp() {
      if (this.isEditDVP) {
        // 新建零部件DVP
        this.$refs.editDvp.saveDvpEdit();
      } else if (this.isEditTemplate) {
        // 模板添加
        this.$refs.templateEdit.saveTemplateEdit();
      } else if (this.isEditHistory) {
        // 历史项目添加
        this.$refs.historyDvpEdit.saveHistoryDvpEdit();
      }
    },

    /**
     * 表格上方按钮弹框-取消按钮
     */
    cancelEditDvp() {
      let _that = this;
      if (_that.isEditDVP) {
        // 新建零部件DVP 弹窗取消
        _that.$refs.editDvp.editParam.isEquivalent = 0;
        _that.$refs.editDvp.editParam = { isEquivalent: 0 };
        _that.$refs.editDvp.checked = false;
        _that.isEditDVP = false;
      } else if (_that.isEditTemplate) {
        // 模板添加 弹窗取消
        _that.$refs.templateEdit.formData = {};
        _that.$refs.templateEdit.selectedRowKeys = [];
        _that.isEditTemplate = false;
      } else if (_that.isEditHistory) {
        // 历史项目添加 弹窗取消
        _that.$refs.historyDvpEdit.formData = {};
        _that.$refs.historyDvpEdit.selectedRowKeys = [];
        _that.isEditHistory = false;
      }
    },

    /**
     * 编辑表格行数据弹框-编辑
     */
    editInit(val) {
      this.$refs.editTableRow.editParam.testId = val.testId;
      this.$refs.editTableRow.editParam.partNo = val.partNo;
      this.$refs.editTableRow.editParam.partName = val.partName;
      this.$refs.editTableRow.editParam.cpacCode = val.cpacCode;
      this.$refs.editTableRow.editParam.fndCode = val.fndCode;
      this.$refs.editTableRow.editParam.testType = val.testType || undefined;
      this.$refs.editTableRow.editParam.testSource = val.testSource || undefined;
      this.$refs.editTableRow.editParam.testProject = val.testProject;
      this.$refs.editTableRow.editParam.targetRequire = val.targetRequire;
      this.$refs.editTableRow.editParam.testStandard = val.testStandard;
      this.$refs.editTableRow.editParam.equivalentId = val.equivalentTestId;
      this.$refs.editTableRow.editParam.testSite = val.testSite;
      this.$refs.editTableRow.editParam.testOwner = val.testOwnerId || undefined;
      this.$refs.editTableRow.editParam.testStep = val.testStep;
      this.$refs.editTableRow.editParam.testFrequency = val.testFrequency;
      this.$refs.editTableRow.editParam.sampleNumber = val.sampleNumber;
      this.$refs.editTableRow.editParam.sampleType = val.sampleType;
      this.$refs.editTableRow.editParam.planStartTime = val.planStartTime;
      this.$refs.editTableRow.editParam.planEndTime = val.planEndTime;
      this.$refs.editTableRow.editParam.isEquivalent = val.isEquivalent;
      this.$refs.editTableRow.editParam.isCarryOut = val.isCarryOut === null ? 1 : val.isCarryOut;
      this.$refs.editTableRow.editParam.notCarryOutCause = val.notCarryOutCause;
      this.$refs.editTableRow.isCarryOutFlag = val.isCarryOut === 0;
      this.$refs.editTableRow.dataSource = val.dataSource; // 数据来源 0-新建1-模板2-FMEA3-历史DVP
      this.$refs.editTableRow.initData();
      this.isEditRow = true;
    },

    /**
     * 编辑表格行数据弹框-关闭
     */
    closeEditRowModal() {
      this.isEditRow = false;
    },


    /**
     * 表格操作列-删除
     */
    deleteDvpData(record) {
      let _that = this;
      _that.$confirm({
        title: _that.$t('fmea.warn'),
        content: _that.$t('global-message.warn.delete-componentsDVP-test'),
        icon: 'exclamation-circle',
        okText: _that.$t('global-btn.confirm'),
        cancelText: _that.$t('global-btn.cancel'),
        onOk() {
          let data = {
            dvpId: _that.$route.query.dvpId,
            testId: record.testId,
          };
          _that.$api.planTestDel(data).then(res => {
            if (res.flag) {
              _that.$message.success(res.message);
              _that.initData();
            } else {
              _that.$message.error(res.message);
            }
          });
        },
        onCancel() {}
      });
    },



    /**
     * 申请变更 关闭弹窗
     */
    closeModal() {
      this.applyFlag = false;
      this.applyTableData = [];
    },

    /**
     * 申请变更
     * @param record
     */
    applyChange(record) {
      // 行数据 赋值
      let rowData = [
        // 试验项目
        {
          changeContent: this.$t("plan.dvp.test-project"),
          currentDesc: record.testProject,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 目标要求
        {
          changeContent: this.$t("base.info.development-objective-requirements"),
          currentDesc: record.targetRequire,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 试验标准
        {
          changeContent: this.$t("base.info.Test-standards"),
          currentDesc: record.testStandard,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 试验类型
        {
          changeContent: this.$t("plan.dvp.test-type"),
          currentDesc: this.testTypeMap[record.testType] || '-' ,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 试验来源
        {
          changeContent: this.$t("plan.dvp.test-source"),
          currentDesc: this.testSourceMap[record.testSource] || '-',
          changeDesc: undefined,
          changeReason: undefined
        },
        // 是否开展实验
        {
          changeContent: this.$t("base.info.whether-to-develop-experimental-projects"),
          currentDesc: this.isOrNotMap[record.isCarryOut] || "-",
          changeDesc: record.isCarryOut,
          changeReason: undefined
        },
        // 是否等效
        {
          changeContent: this.$t("plan.dvp.is-it-an-equivalent-test"),
          currentDesc: this.isOrNotMap[record.isEquivalent] || '-',
          changeDesc: record.isEquivalent,
          changeReason: undefined
        },
        // 等效报告编号
        {
          changeContent: this.$t("plan.dvp.equivalent-experiment-report-number"),
          currentDesc: record.equivalentTestCode,
          changeDesc: record.equivalentTestId || undefined,
          changeReason: undefined
        },
        // 试验地点
        {
          changeContent: this.$t("plan.dvp.test-location"),
          currentDesc: record.testSite,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 测试负责人
        {
          changeContent: this.$t("plan.dvp.test-user"),
          currentDesc: record.testOwner,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 计划开始时间
        {
          changeContent: this.$t("plan.dvp.scheduled-start-time"),
          currentDesc: record.planStartTime,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 计划结束时间
        {
          changeContent: this.$t("plan.dvp.scheduled-end-time"),
          currentDesc: record.planEndTime,
          changeDesc: record.planEndTime,
          changeReason: undefined
        },
        // 测试阶段
        {
          changeContent: this.$t("plan.dvp.test-step"),
          currentDesc: record.testSite,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 测试次数
        {
          changeContent: this.$t("plan.dvp.test-count"),
          currentDesc: record.testFrequency,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 样件类型
        {
          changeContent: this.$t("plan.dvp.sample-type"),
          currentDesc: record.sampleType,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 样本数量
        {
          changeContent: this.$t("plan.dvp.number-of-samples"),
          currentDesc: record.sampleNumber,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 不展开实验原因
        {
          changeContent: this.$t("base.info.reason-for-not-conducting-the-experiment"),
          currentDesc: record.notCarryOutCause,
          changeDesc: undefined,
          changeReason: undefined
        }

      ];
      // 赋值给申请变更弹窗的表格
      this.applyTableData = rowData;
      // 调用申请变更弹窗的初始化表格数据方法
      this.$refs.applyChange.initTableData(this.applyTableData);
      this.$refs.applyChange.testId = record.testId;
      this.$refs.applyChange.dvpType = this.dvpType;
      this.$refs.applyChange.notCarryOutDisabled = record.isCarryOut === 0;
      this.$refs.applyChange.isEquivalentDisabled = record.isEquivalent === 1;
      this.$refs.applyChange.dataSource = record.dataSource; // 数据来源 0-新建1-模板2-FMEA3-历史DVP

      // 开启弹窗
      this.applyFlag = true;
    },

    // /**
    //  * 表格上方按钮-导出
    //  */
    // exportFile() {
    //   this.download('/DFMEA/partDvp/dvpPlanExcelExport', {
    //     dvpId: this.$store.getters.dvpId || '',
    //     partCode: this.formData.partCode || '',
    //     partName: this.formData.partName || '',
    //     fndId: this.formData.fndCode || '',
    //     ownerDepartmentId: this.formData.ownerDepartmentId || '',
    //     testOwner: this.formData.testOwner || '',
    //     testType: this.formData.testType || '',
    //     testSource: this.formData.testSource || '',
    //     systemTestSource: this.formData.systemTestSource || '',
    //     targetRequire: this.formData.targetRequire || '',
    //     testStandard: this.formData.testStandard || '',
    //     testSite: this.formData.testSite || '',
    //     planStartTime: this.formData.planStartTime || '',
    //     planEndTime: this.formData.planEndTime || '',
    //   });
    // },

    /**
     * 搜索框-开始时间
     * @param date
     * @param dateString
     */
    handleQueryStartTime(date, dateString) {
      this.formData.planStartStartTime = dateString[0];
      this.formData.planStartEndTime = dateString[1];
    },

    /**
     * 搜索框-结束时间
     * @param date
     * @param dateString
     */
    handleQueryEndTime(date, dateString) {
      this.formData.planEndStartTime = dateString[0];
      this.formData.planEndEndTime = dateString[1];
    },


    /**
     * 表格 - 点击分页中数字触发的方法
     * @param pagination
     */
    handlePageChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.pagination.pageNo = pagination.current;
      this.initData();
    },

    /**
     * 下拉选模糊查询
     * @param input
     * @param option
     * @returns {boolean}
     */
    handleFilterDataList(input,option) {
      return option.componentOptions.children[0].text.toLowerCase().includes(input.toLowerCase());
    },

    viewReport(val) {
      let url = this.$api.baseUrl + '/DFMEA/file/downloadFile.do?id=' + val.equivalentTestId + '&fileType=8';
      fetch(url, {
        method: 'get'
      }).then(res => {
        //读取文件的arrayBuffer
        res.arrayBuffer().then(res => {
          this.$refs.viewModal.isShowModal = true;
          this.$refs.viewModal.fileUrl = res;
          this.$nextTick(() => {
            this.$refs.viewModal.getFileExtension(val.fileName);
          });
        });
      });
      this.download('/DFMEA/file/downloadFile', {
        id: val.equivalentTestId,
        fileType: 8
      });
    }
  }
}

</script>
<style lang="less" scoped>
.content-box {
  padding: 0 12px;
}

.layout-card {
  padding: 12px;
}

.cardOverFlow {
  overflow-x: hidden;
  overflow-y: auto;
}

.table-mr {
  margin-top: 12px;
}

/deep/ .clickContent {
  color: #1890FF;
  cursor: pointer;
}

/deep/ .card .ant-card-head {
  padding: 0 12px !important;
  font-weight: bold;
}

.title-padding {
  padding: 0 12px !important;
}
</style>
