<template>
  <div>
    <a-row class="content-box">
      <a-card class="layout-card">
        <a-form layout='vertical'>
          <a-row :gutter="24">
            <!--系统名称-->
            <a-col :lg='6' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('base.info.system-name')">
                <a-input
                  v-model.trim="formData.systemName"
                  :maxLength='500'
                  :placeholder="$t('base.info.please-enter-system-name')"
                  allowClear/>
              </a-form-item>
            </a-col>
            <!--需求资源-->
            <a-col :lg='6' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('base.info.required.resources')">
                <a-input
                  v-model.trim="formData.assets"
                  :maxLength='500'
                  :placeholder="$t('base.info.please-enter-required.resources')"
                  allowClear/>
              </a-form-item>
            </a-col>
            <!--验证内容-->
            <a-col :lg='6' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('base.info.verification-content')">
                <a-input
                  v-model.trim="formData.verify"
                  :maxLength='50'
                  :placeholder="$t('base.info.please-enter-verification-content')"
                  allowClear/>
              </a-form-item>
            </a-col>
            <!--开发目标要求-->
            <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('base.info.development-objective-requirements')">
                <a-input
                  v-model.trim="formData.targetRequire"
                  :maxLength='50'
                  :placeholder="$t('base.info.please-enter-development-objective-requirements')"
                  allowClear/>
              </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'
                    :placeholder="$t('base.info.please-enter-test-standards')"
                    allowClear/>
							</a-form-item>
						</a-col>
            <!--是否开展实验项目-->
							<a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
								<a-form-item :label="$t('base.info.whether-to-develop-experimental-projects')">
									<a-select v-model="formData.isCarryOut" allowClear :placeholder="$t('base.info.please-enter-whether-to-develop-experimental-projects')">
                    <a-select-option :value="1">{{ $t('global-btn.yes') }}</a-select-option>
                    <a-select-option :value="0">{{ $t('global-btn.no') }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            <!--试验来源 DVP模板/DFMEA:0/1-->
            <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('plan.dvp.test-source')">
                <a-select v-model="formData.testSource" :placeholder="$t('plan.dvp.please-enter-test-source')" allowClear>
                    <a-select-option :value="0">{{ $t('plan.dvp.test-source-dvp-template') }}</a-select-option>
                    <a-select-option :value="1">{{ $t('plan.dvp.test-source-DFMEA') }}</a-select-option>
                    <a-select-option :value="2">{{ $t('plan.dvp.test-source-manual-modification') }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
              <!--试验资质 是/否:1/0-->
              <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
                <a-form-item :label="$t('plan.dvp.test-qualification')">
                  <a-select v-model="formData.testCertification" :placeholder="$t('plan.dvp.please-enter-test-qualification')" allowClear>
                    <a-select-option :value="1">{{ $t('global-btn.yes') }}</a-select-option>
                    <a-select-option :value="0">{{ $t('global-btn.no') }}</a-select-option>
                  </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-location')">
                <a-input
                  v-model.trim="formData.testSite"
                  :maxLength='50'
                  :placeholder="$t('plan.dvp.please-enter-test-location')"
                  allowClear/>
              </a-form-item>
            </a-col>
            <!--试验责任方-->
            <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('base.info.test-responsible-party')">
                <a-select allowClear v-model="formData.testOwner" :options="testOwnerList" @change="handleTestOwner" :placeholder="$t('plan.dvp.please_select-study-director')"></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-stage')">
                  <a-select allowClear v-model="formData.testStage" :options="testStageList"  :placeholder="$t('plan.dvp.please-enter-test-stage')"/>
                </a-form-item>
              </a-col>
            <!--样件类型-->
            <a-col :lg='6' :md='24' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('plan.dvp.sample-type')">
                <a-select allowClear v-model="formData.sampleType" :options="sampleTypeList" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.sample-type')"/>
              </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-start-time')">
                <a-range-picker v-model="startTime" @change="handleStartTime" allowClear valueFormat="YYYY-MM-DD" style="width: 100%" />
              </a-form-item>
            </a-col>
            <!--计划结束时间-->
            <a-col :xl='6' :lg='6' :md='24' :sm='24' :xs='24'>
              <a-form-item :label="$t('plan.dvp.scheduled-end-time')">
                <a-range-picker v-model="endTime" @change="handleEndTime" 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' type="primary" class="mr10">
                  {{ $t('global-btn.reset') }}
                </a-button>
                <!-- 查询 -->
                <a-button @click='search' type="primary" class="mr10">
                  {{ $t('global-btn.search') }}
                </a-button>
              </a-col>
            </a-form-item>
          </a-row>
        </a-form>
      </a-card>
      <a-card class="layout-card" :style="{ height: tableHeight }">
        <a-form-item class='tr' >
          <!-- 导出 -->
          <a-button @click='exportFile'>
            {{ $t('global-btn.export') }}
          </a-button>
        </a-form-item>
        <a-table
            ref="tableRefs"
            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'
            :components='components'
					  bordered
        >
          <!-- 序号列 -->
          <template slot='index' slot-scope='text, record, index'>
            <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
          </template>
          <!-- 试验来源 -->
          <template slot="testSource" slot-scope="text, record">
            <span>{{ testSourceMap[record.testSource] || '-' }}</span>
          </template>
          <!-- 是否开展实验 -->
          <template slot="isCarryOut" slot-scope="text, record">
            <span>{{ isOrNotMap[record.isCarryOut] || '-' }}</span>
          </template>
          <!-- 试验资质 -->
          <template slot="testCertification" slot-scope="text, record">
            <span>{{ isOrNotMap[record.testCertification] || '-' }}</span>
          </template>
          <!-- 样件类型 -->
          <template slot="sampleType" slot-scope="text, record">
            <span>{{ sampleTypeMap[record.sampleType] || '-' }}</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>
            </span>
          </template>
        </a-table>
      </a-card>
    </a-row>
    <!-- 编辑模态框 -->
    <a-modal v-model="isEdit" :title="$t('plan.dvp.edit-dvp')" @ok="save" @cancel="offModal" :width="1000" :maskClosable="false">
      <a-row :gutter="24">
        <a-form>
          <!-- 系统名称 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('base.info.system-name')">
              <a-input
                v-model="editParam.systemName"
                :disabled="true"
              />
            </a-form-item>
          </a-col>
          <!-- 验证内容 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('base.info.verification-content')">
              <a-input
                v-model="editParam.verify"
                :disabled="true"
              />
            </a-form-item>
          </a-col>
          <!-- 开发目标要求 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('base.info.development-objective-requirements')">
              <a-input
                v-model="editParam.targetRequire"
                :disabled="true"
              />
            </a-form-item>
          </a-col>
          <!-- 试验标准 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('base.info.Test-standards')">
              <a-input
                v-model="editParam.testStandard"
                :disabled="true"
              />
            </a-form-item>
          </a-col>
          <!-- 需求资源 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('base.info.required-resources (vehicle rack)')">
              <!-- 当试验来源是模板（testSource = 0）时不可编辑，是FMEA（testSource = 1）时可以编辑 -->
              <a-input
                allowClear
                v-model="editParam.assets"
                :disabled="this.editParam.testSource === 0"
                :placeholder="$t('base.info.please-required-resources (vehicle rack)')"
              />
            </a-form-item>
          </a-col>
          <!-- 是否开展实验项目 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('base.info.whether-to-develop-experimental-projects')">
              <a-select v-model="editParam.isCarryOut" allowClear @change="handleCarryOut" :placeholder="$t('base.info.please-enter-whether-to-develop-experimental-projects')">
                <a-select-option :value="1">{{ $t('global-btn.yes') }}</a-select-option>
                <a-select-option :value="0">{{ $t('global-btn.no') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
      <a-row v-if="causeShowFlag" :gutter="24">
        <a-form>
          <!-- 试验责任方 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('base.info.test-responsible-party')">
              <a-select allowClear v-model="editParam.testOwnerId" :options="testOwnerList" @change="handleEditTestOwner" :placeholder="$t('plan.dvp.please_select-study-director')"></a-select>
            </a-form-item>
          </a-col>
          <!--试验资质-->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('plan.dvp.test-qualification')">
              <a-select allowClear v-model="editParam.testCertification"  :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-qualification')">
                <a-select-option :value="1">{{ $t('global-btn.yes') }}</a-select-option>
                <a-select-option :value="0">{{ $t('global-btn.no') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- 试验地点 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('plan.dvp.test-location')">
              <a-input
                v-model.trim="editParam.testSite"
                :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-location')"
                allowClear
                :maxLength='17'
              />
            </a-form-item>
          </a-col>
          <!-- 试验阶段 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('plan.dvp.test-stage')">
              <a-select allowClear v-model="editParam.testStage" :options="testStageList"  :placeholder="$t('plan.dvp.please-enter-test-stage')"/>
            </a-form-item>
          </a-col>
          <!-- 试验频次 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('plan.dvp.test-frequency')">
              <a-select allowClear v-model="editParam.testFrequency" :options="frequencyList"  :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-frequency')"/>
            </a-form-item>
          </a-col>
          <!-- 样本数量 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('plan.dvp.number-of-samples')">
              <a-select allowClear v-model="editParam.count" :options="countList"  :placeholder="$t('plan.dvp.please_select-number-of-vehicles')"/>
            </a-form-item>
          </a-col>
          <!-- 样件类型 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item required :label="$t('plan.dvp.sample-type')">
              <a-select allowClear v-model="editParam.sampleType" :options="sampleTypeList" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.sample-type')"/>
            </a-form-item>
          </a-col>
          <!--计划开始时间-->
          <a-col :lg='16' :md='24' :sm='24' :xl='12' :xs='24'>
            <a-form-item required :label="$t('plan.dvp.scheduled-start-time')">
              <a-date-picker v-model="editParam.planStartTime" :disabled-date="disabledStartDate" @change="handleEditStartTime" allowClear valueFormat="YYYY/MM/DD" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <!--计划结束时间-->
          <a-col :lg='16'  :md='24' :sm='24' :xl='12'  :xs='24'>
            <a-form-item required :label="$t('plan.dvp.scheduled-end-time')">
              <a-date-picker v-model="editParam.planEndTime"
              :disabled="this.editParam.testSource === 1"
              :disabled-date="disabledEndDate"
              @change="handleEditEndTime"
              style="width: 100%"
              valueFormat="YYYY/MM/DD"
              allowClear />
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
      <!--不开展试验原因-->
      <a-row v-else :gutter="24">
        <a-form>
          <a-col :xl='24' :lg='24' :md='24' :sm='24' :xs='24'>
            <a-form-item required :label="$t('base.info.reason-for-not-conducting-the-experiment')">
              <a-textarea rows='6' v-model.trim="editParam.notCarryOutCause" style="width: 100%;" :placeholder="$t('base.info.please-enter-reason-for-not-conducting-the-experiment')" :maxLength='50'></a-textarea>
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
    </a-modal>
    <ApplyForChange
      :applyFlag="applyFlag"
      :applyTableData="applyTableData"
      :dvpType="dvpType"
      @closeModal="closeModal"
      @initData="initData"
      ref="applyChange">
    </ApplyForChange>
  </div>
</template>

<script>

import ApplyForChange from "./applyChange/applyForChange";
import {getUrlParam} from "../../../common/common";
import moment from "moment";
import VueDraggableResizable from 'vue-draggable-resizable';

export default {
  components: {
    ApplyForChange,
    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, 100);
							}
						}
					};
					const drag = h('vue-draggable-resizable', { ...dragProps });
					return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
				}
			}
		};
    return{
      /** 查询数据 */
      formData:{
        systemName: undefined,          // 系统名称
        assets: undefined,              // 需求资源
        verify: undefined,              // 验证内容
        testSource: undefined,          // 试验来源
        targetRequire: undefined,       // 开发目标要求
        testStandard: undefined,        // 试验标准
        isCarryOut: undefined,          // 是否开展
        testCertification: undefined,   // 试验资质
        testSite: undefined,            // 试验地点
        testOwner: undefined,           // 试验负责人
        testStage: undefined,           // 试验阶段
        sampleType: undefined,          // 样本类型
        planStartTime: undefined,      // 计划开始时间
        planEndTime: undefined,        // 计划结束时间
      },
      /** 编辑弹框 用于记录初始值 */
      planStartTime: undefined,
      planEndTime: undefined,
      /** 清除时间选框用的 */
      endTime: undefined,
      startTime: undefined,
      /** 编辑模态框显隐 */
      isEdit: false,
      /** 编辑模态框数据 */
      editParam: {
        systemName: undefined,               // 系统名称
        dvpId: undefined,                    // DVP ID
        testId: undefined,                   // 试验ID
        isCarryOut: undefined,               // 是否开展试验项目 0否 1是
        notCarryOutCause: undefined,         // 不开展试验原因
        testOwnerId: undefined,              // 试验负责人
        testCertification: undefined,        // 试验资质
        testSite: undefined,                 // 试验地点
        testStage: undefined,                // 试验阶段
        testFrequency: undefined,            // 试验频率
        count: undefined,                    // 样本数量
        sampleType: undefined,               // 样本类型
        planStartTime: undefined,            // 计划开始时间
        planEndTime: undefined,              // 计划结束时间
        assets: undefined                    // 需求资源
      },
      /** 折叠 展开 */
      advanceExpand: false,
      /** 不适用原因文本框显示/隐藏 */
      causeShowFlag: true,
      /** 试验责任方 */
      testOwnerList: [],
      /** 分页 */
      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,
      },
      /** 表格高度 */
      tableHeight: window.innerHeight - 352 + 'px',
      tableHeightValue: window.innerHeight - 560,
      // 表格总宽度
      tableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
      /** 表格加载状态 */
      tableLoading: false,
      /** 表格数据 */
      tableData: [],
      /** 表格列 */
      tableColumns: [
        //序号
        {
          title: this.$t('plan.dvp.serial-number'),
          dataIndex: 'index',
          width: 100,
          fixed: 'left',
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true
        },
        //系统名称
        {
          title: this.$t('base.info.system-name'),
          width: 180,
          dataIndex: 'systemName',
          align: 'center',
          ellipsis: true
        },
        //需求资源(整车,台架)
        {
          title: this.$t('base.info.required-resources (vehicle rack)'),
          width: 180,
          dataIndex: 'assets',
          align: 'center',
          ellipsis: true
        },
        //试验来源
        {
          title: this.$t('plan.dvp.test-source'),
          width: 120,
          dataIndex: 'testSource',
          align: 'center',
          ellipsis: true,
          scopedSlots: {
            customRender: 'testSource'
          }
        },
        //验证内容
        {
          title: this.$t('base.info.verification-content'),
          width: 180,
          dataIndex: 'verify',
          align: 'center',
          ellipsis: true
        },
        //开发目标要求(接受标准)
        {
          title: this.$t('base.info.development-objective-requirements (acceptance criteria)'),
          width: 180,
          dataIndex: 'targetRequire',
          align: 'center',
          ellipsis: true
        },
        //试验标准
        {
          title: this.$t('base.info.Test-standards'),
          width: 180,
          dataIndex: 'testStandard',
          align: 'center',
          ellipsis: true
        },
        //是否开展实验项目
        {
          title: this.$t('base.info.whether-to-develop-experimental-projects'),
          width: 150,
          dataIndex: 'isCarryOut',
          align: 'center',
          ellipsis: true,
          scopedSlots: {
            customRender: 'isCarryOut'
          }
        },
        //不开展实验原因
        {
          title: this.$t('base.info.reason-for-not-conducting-the-experiment'),
          width: 200,
          dataIndex: 'notCarryOutCause',
          align: 'center',
          ellipsis: true
        },
        //试验责任方
        {
          title: this.$t('base.info.test-responsible-party'),
          width: 120,
          dataIndex: 'testOwner',
          align: 'center',
          ellipsis: true
        },
        //试验资质
        {
          title: this.$t('plan.dvp.test-qualification'),
          width: 180,
          dataIndex: 'testCertification',
          align: 'center',
          ellipsis: true,
          scopedSlots: {
            customRender: 'testCertification'
          }
        },
        //试验地点
        {
          title: this.$t('plan.dvp.test-location'),
          width: 120,
          dataIndex: 'testSite',
          align: 'center',
          ellipsis: true
        },
        //试验阶段
        {
          title: this.$t('plan.dvp.test-stage'),
          width: 120,
          dataIndex: 'testStageName',
          align: 'center',
          ellipsis: true
        },
        //试验频次
        {
          title: this.$t('plan.dvp.test-frequency'),
          width: 120,
          dataIndex: 'testFrequency',
          align: 'center',
          ellipsis: true
        },
        //样本数量
        {
          title: this.$t('plan.dvp.number-of-samples'),
          width: 100,
          dataIndex: 'count',
          align: 'center',
          ellipsis: true
        },
        //样件类型
        {
          title: this.$t('plan.dvp.sample-type'),
          width: 120,
          dataIndex: 'sampleType',
          align: 'center',
          scopedSlots: {
            customRender: 'sampleType'
          }
        },
        //计划开始时间
        {
          title: this.$t('plan.dvp.scheduled-start-time'),
          width: 150,
          dataIndex: 'planStartTime',
          align: 'center',
          ellipsis: true
        },
        //计划结束时间
        {
          title: this.$t('plan.dvp.scheduled-end-time'),
          width: 150,
          dataIndex: 'planEndTime',
          align: 'center',
          ellipsis: true
        },
        //操作
        {
          title: this.$t('global-constant.operation'),
          dataIndex: 'action',
          align: 'center',
          width: 100,
          fixed: 'right',
          scopedSlots: {customRender: 'action'},
          ellipsis: true
        }
      ],
      /** 试验来源Map 用于表格插槽显示 */
      testSourceMap: {
        0: this.$t("plan.dvp.test-source-dvp-template"),
        1: this.$t("plan.dvp.test-source-DFMEA"),
        2: this.$t("plan.dvp.test-source-manual-modification")
      },
      /** 是/否Map 用于表格插槽显示 试验资质/是否开展试验 */
      isOrNotMap: {
        0: this.$t("global-btn.no"),
        1: this.$t("global-btn.yes")
      },
      /** 试验频次下拉选 */
      frequencyList: [
        {
          label: 1,
          value: 1
        },
        {
          label: 2,
          value: 2
        },
        {
          label: 3,
          value: 3
        },
        {
          label: 4,
          value: 4
        },
        {
          label: 5,
          value: 5
        }
      ],
      /** 样件数量下拉选 */
      countList: [
        {
          label: 1,
          value: 1
        },
        {
          label: 2,
          value: 2
        },
        {
          label: 3,
          value: 3
        },
        {
          label: 4,
          value: 4
        },
        {
          label: 5,
          value: 5
        },
        {
          label: 6,
          value: 6
        },
        {
          label: 7,
          value: 7
        },
        {
          label: 8,
          value: 8
        },
        {
          label: 9,
          value: 9
        }
      ],
      /** 样件类型下拉选 */
      sampleTypeList: [
        {
          label: this.$t('plan.dvp.sample-type.soft-modules'),
          value: '0'
        },
        {
          label: this.$t('plan.dvp.sample-type.hard-module'),
          value: '1'
        },
        {
          label: this.$t('plan.dvp.sample-type.fixture-parts'),
          value: '2'
        }
      ],
      /** 样件类型 用于表格插槽显示 */
      sampleTypeMap: {
        0: this.$t('plan.dvp.sample-type.soft-modules'),
        1: this.$t('plan.dvp.sample-type.hard-module'),
        2: this.$t('plan.dvp.sample-type.fixture-parts')
      },
      /** 试验阶段下拉选项 */
      testStageList: [],
      /** 申请变更弹窗标识 */
      applyFlag: false,
      /** 申请变更弹窗表格数据 */
      applyTableData: [],
      /** 变更申请按钮显隐 */
      applyButtonFlag: false,
      /** 权限 */
      isLook: false,
      /** dvpType system:系统DVP，components:零部件DVP */
      dvpType: "system"

    }
  },
  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.getTestOwner();
    this.getProjectNodeList();
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 352 + 'px';
      this.tableHeightValue = window.innerHeight - 560;
    };
    // 监听页面窗体大小变化
    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.tableRefs.$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 = 150;
      }
    },
    /**
     * 初始化表格数据
     */
    initData() {
      let _that = this;
      _that.tableLoading = true;
      _that.formData.dvpId = _that.$store.getters.dvpId;
      _that.formData.pagination = {
        pageSize: _that.pagination.pageSize,
        pageCurrent: _that.pagination.current
      }
      _that.$api.initDvpPlanList(_that.formData).then(res => {
        if (res.flag) {
          _that.tableData = res.data.data;
          _that.pagination.total = res.data.total;
        } 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 ;
        }
      });
    },
    /**
     * 获取试验负责人下拉选项
     */
    getTestOwner() {
      let data = {
        dvpId: this.$store.getters.dvpId,
        dvpType: this.$store.getters.dvpType
      }
      // 获取DVP团队成员中有编辑权限的用户
      this.$api.getSystemDvpTeamMember(data).then(res => {
        if (res.flag) {
          let userList = res.data.teamMemberModels;
          userList.forEach(item =>{
            if (item.permission === 1){
              let options = {
                label: item.name,
                value: item.userId
              };
              this.testOwnerList.push(options);
            }
          });
          // 是否包含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);
          }
        }
      });
    },

    /**
     * 查询
     */
    search() {
      this.initData();
    },

    /**
     * 重置
     */
    reset() {
      this.startTime = undefined;
      this.endTime = undefined;
      this.formData = {};
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.advanceExpand = false;
      this.initData();
    },

    /**
     * 收起/展开
     */
    toggleAdvance() {
      this.advanceExpand = !this.advanceExpand;
      if(this.advanceExpand) {
        this.tableHeightValue -= 180
      } else {
        this.tableHeightValue = window.innerHeight - 560;
      }
    },

    /**
     * 非空校验 判断是否为空
     * @returns {boolean}
     */
    isNull() {
      let _that = this;
      let message = [];
      // 是否开展试验项目
      if (_that.editParam.isCarryOut == undefined && _that.editParam.isCarryOut == null) {
        message.push(_that.$t('global-constant.please-enter') + _that.$t('base.info.whether-to-develop-experimental-projects'));
      } else if (_that.editParam.isCarryOut === 1) { // 如果点击是，则校验以下值，点击否只校验不适用原因
        // 试验责任人
        if (!_that.editParam.testOwnerId) {
          message.push(_that.$t('global-constant.please-enter') + _that.$t('base.info.test-responsible-party'));
        }
        // 试验资质
        if (_that.editParam.testCertification == undefined && _that.editParam.testCertification == null) {
          message.push(_that.$t('global-constant.please-select') + _that.$t('plan.dvp.test-qualification'));
        }
        // 样本数量
        if (!_that.editParam.count) {
          message.push(_that.$t('global-constant.please-select') + _that.$t('plan.dvp.number-of-samples'));
        }
        // 试验地点
        if (!_that.editParam.testSite) {
          message.push(_that.$t('global-constant.please-enter') + _that.$t('plan.dvp.test-location'));
        }
        // 试验阶段
        if (!_that.editParam.testStage) {
          message.push(_that.$t('global-constant.please-select') + _that.$t('plan.dvp.test-stage'));
        }
        // 试验频次
        if (!_that.editParam.testFrequency) {
          message.push(_that.$t('global-constant.please-select') + _that.$t('plan.dvp.test-frequency'));
        }
        // 样件类型
        if (!_that.editParam.sampleType) {
          message.push(_that.$t('global-constant.please-select') + _that.$t('plan.dvp.sample-type'));
        }
        // 计划开始时间
        if (!_that.editParam.planStartTime) {
          message.push(_that.$t('global-constant.please-select') + _that.$t('plan.dvp.scheduled-start-time'));
        }
        // 计划结束时间
        if (!_that.editParam.planEndTime) {
          message.push(_that.$t('global-constant.please-select') + _that.$t('plan.dvp.scheduled-end-time'));
        }
        // 需求资源
        if (!_that.editParam.assets) {
          message.push(_that.$t('global-constant.please-enter') + _that.$t('plan.dvp.required-resources (vehicle rack)'))
        }
      } else {
        // 不适用原因
        if (!_that.editParam.notCarryOutCause || _that.editParam.notCarryOutCause.trim().length === 0) {
          message.push(_that.$t('global-btn.please-enter') + _that.$t('base.info.reason-for-not-conducting-the-experiment'));
        }
      }
      if (message && message.length > 0) {
        for (let i = 0; i < message.length; i++) {
          _that.$notification.warning({message: message[i]});
        }
        return false;
      }
      return true;
    },

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

    /** 编辑 保存 */
    save() {
      if (!this.isNull()) {
        return false;
      }
      // 如果是否开展试验选择了否，则清除试验相关的信息
      if (this.editParam.isCarryOut === 0) {
        this.editParam.planEndTime = undefined;
        this.editParam.planStartTime = undefined;
        this.editParam.count = undefined;
        this.editParam.sampleType = undefined;
        this.editParam.testOwnerId = undefined;
        this.editParam.testFrequency = undefined;
        this.editParam.testStage = undefined;
        this.editParam.testSite = undefined;
        this.editParam.testCertification = undefined;
      } else { // 如果选择了是，则清除不适用原因
        this.editParam.notCarryOutCause = undefined;
      }

     let data = {
       dvpId: this.editParam.dvpId,
       testId: this.editParam.testId,
       isCarryOut: this.editParam.isCarryOut,
       notCarryOutCause: this.editParam.notCarryOutCause,
       testOwnerId: this.editParam.testOwnerId,
       testCertification: this.editParam.testCertification,
       testSite: this.editParam.testSite,
       testStage: this.editParam.testStage,
       testFrequency: this.editParam.testFrequency,
       count: this.editParam.count,
       sampleType: this.editParam.sampleType,
       planStartTime: this.editParam.planStartTime,
       planEndTime: this.editParam.planEndTime,
       assets: this.editParam.assets
     };
      this.$api.editTest(data).then(res => {
        if (!res.flag) {
          this.$notification.error({message: res.message});
        } else {
          this.$notification.success({message: res.message});
          this.initData();
          this.isEdit = false;
        }
      });
    },

    /**
     * 编辑弹框 初始化
     */
    editInit(val) {
      //以下写法会导致更改编辑弹框内容，连同编辑弹框外的表格对应的字段也更改
      // this.editParam = val;
      //所以这样写 this.editParam = {...val};
      //或者如下写，挨个赋值
      this.editParam.isCarryOut = (val.isCarryOut === 0 || val.isCarryOut === 1) ? val.isCarryOut : undefined;
      this.editParam.systemName = val.systemName;
      this.editParam.assets = val.assets;
      this.editParam.verify = val.verify;
      this.editParam.testSource = val.testSource;
      this.editParam.targetRequire = val.targetRequire;
      this.editParam.testCertification = val.testCertification || undefined;
      this.editParam.planEndTime = val.planEndTime;
      this.editParam.planStartTime = val.planStartTime;
      this.editParam.count = val.count || undefined;
      this.editParam.sampleType = val.sampleType || undefined;
      this.editParam.testOwnerId = val.testOwnerId;
      this.editParam.testFrequency = val.testFrequency || undefined;
      this.editParam.testStage = val.testStage || undefined;
      this.editParam.testSite = val.testSite;
      this.editParam.testStandard = val.testStandard;
      this.editParam.notCarryOutCause = val.notCarryOutCause;
      this.editParam.dvpId = this.$store.getters.dvpId;
      this.editParam.testId = val.testId;
      this.testOwnerList.forEach( item => {
        if (item.label === val.testOwner) {
          this.editParam.testOwnerId = item.value;
        }
      });
      this.planStartTime = val.planStartTime;
      this.planEndTime = val.planEndTime;
      if (val.isCarryOut === 0) {
        this.causeShowFlag = false;
      } else {
        this.causeShowFlag = true;
      }
      this.isEdit = true;
    },

    /**
     * 获取试验阶段下拉选项（项目节点）
     */
    getProjectNodeList() {
      this.$api.getSysDvpProjectNodeList({dvpId: this.$store.getters.dvpId}).then(res => {
        if (res.flag) {
          let data = res.data || [];
          data.forEach(item => {
            let selectOption = {
              label: item.milestoneName,
              value: item.id
            };
            this.testStageList.push(selectOption);
          });
        } else {
          this.$message.error(res.message);
          this.testStageList = [];
        }
      });
    },


    /** 编辑 取消 */
    offModal() {
      this.isEdit = false;
      this.editParam.isCarryOut = undefined;
      this.editParam.planEndTime = undefined;
      this.editParam.planStartTime = undefined;
      this.editParam.count = undefined;
      this.editParam.sampleType = undefined;
      this.editParam.testOwnerId = undefined;
      this.editParam.testFrequency = undefined;
      this.editParam.testStage = undefined;
      this.editParam.testSite = undefined;
      this.editParam.testCertification = undefined;
      this.editParam.assets = undefined;
    },
    /**
     * 导出
     */
    exportFile() {
      this.download('/DFMEA/dvp/system/dvpPlanExcelExport', {
        dvpId: this.$store.getters.dvpId || '',
        systemName: this.formData.systemName || '',
        assets: this.formData.assets || '',
        verify: this.formData.verify || '',
        testSource: this.formData.testSource || '',
        targetRequire: this.formData.targetRequire || '',
        testStandard: this.formData.testStandard || '',
        isCarryOut: this.formData.isCarryOut || '',
        testCertification: this.formData.testCertification || '',
        testSite: this.formData.testSite || '',
        testOwner: this.formData.testOwner || '',
        testStage: this.formData.testStage || '',
        sampleType: this.formData.sampleType || '',
        planStartTime: this.formData.planStartTime || '',
        planEndTime: this.formData.planEndTime || '',
      });
    },

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

    /**
     * 计划开始时间 时间选择器Change方法 查询
     */
    handleStartTime(date, dateString){
      this.formData.planStartStartTime = dateString[0];
      this.formData.planStartEndTime = dateString[1];
    },

    /**
     * 计划结束时间 时间选择器Change方法 查询
     */
    handleEndTime(date, dateString){
      this.formData.planEndStartTime = dateString[0];
      this.formData.planEndEndTime = dateString[1];
    },

    /**
     * 开始时间不能选择当天
     * @param current
     * @returns {boolean}
     */
    disabledStartDate(current) {
      // return current && current < moment().subtract(1,"day").endOf('day');
      // 有结束时间，则返回不能选择日期为结束时间之后的日期
      if (this.editParam.planEndTime) {
        return current && current > moment(this.editParam.planEndTime).endOf('day');
      } else { // 无开始时间，则返回不能选择日期为当前时间之前的日期
        return current && current < moment().subtract(1,"day").endOf('day');
      }
    },

    /**
     * 结束时间不能选择开始时间前的时间
     * @param current
     * @returns {boolean}
     */
    disabledEndDate(current) {
      // 有开始时间，则返回不能选择日期为开始时间之前的日期
      if (this.editParam.planStartTime) {
        return current && current < moment(this.editParam.planStartTime).endOf('day');
      } else { // 无开始时间，则返回不能选择日期为当前时间之前的日期
        return current && current < moment().subtract(1,"day").endOf('day');
      }
    },

    /**
     * 计划开始时间 时间选择器Change方法 编辑
     */
    handleEditStartTime(date, dateString){
      if (!dateString) {
        this.editParam.planStartTime = "";
        return;
      }
      this.editParam.planStartTime = dateString;
      // 当选择的开始时间大于结束时间时，清空结束时间，让用户重新选择结束时间
      // if (Date.parse(this.editParam.planStartTime) > Date.parse(this.editParam.planEndTime)) {
      //   this.editParam.planEndTime = undefined;
      //   this.$confirm({
      //     title: this.$t('fmea.warn'),
      //     content: this.$t('fmea.task.management.whether-to-delete-the-dvp-task'),
      //     icon: 'exclamation-circle',
      //     okText: _that.$t('report.confirm'),
      //     cancelText: _that.$t('workbench.cancel'),
      //     onOk() {
      //       _that.delTasks(taskIds);
      //     },
      //     onCancel() {
      //     }
      //   });
      // }
    },
    /**
     * 计划结束时间 时间选择器Change方法 编辑
     */
    handleEditEndTime(date, dateString) {
      if (!dateString) {
        this.editParam.planEndTime = "";
        return;
      }
      this.editParam.planEndTime = dateString;
    },

    /**
     * 试验负责人下拉改变 查询
     * @param val
     */
    handleTestOwner(val) {
      this.formData.testOwner = val;
    },

    /**
     * 试验负责人下拉改变 编辑
     * @param val
     */
    handleEditTestOwner(val) {
      this.editParam.testOwnerId = val;
    },

    /**
     * 样本数量下拉改变 编辑
     * @param val
     */
    handleCount(val) {
      this.editParam.count = val;
    },

    /**
     * 是否开展实验项目 编辑
     * @param val
     */
    handleCarryOut(val){
      this.editParam.isCarryOut = val;
      // 当选择了不开展试验 val=0,开展试验表单标志causeShowFlag = false,不开展试验表单显示
      if (val === 0) {
        this.causeShowFlag = false;
      } else {
        this.causeShowFlag = true;
      }
    },
    /**
     * 申请变更
     * @param record
     */
    applyChange(record) {
      // 行数据 赋值
      let rowData = [
        // 是否开展实验
        {
          changeContent: this.$t("base.info.whether-to-develop-experimental-projects"),
          currentDesc: this.isOrNotMap[record.isCarryOut] || "-",
          changeDesc: undefined,
          changeReason: undefined
        },
        // 试验负责人
        {
          changeContent: this.$t("base.info.test-responsible-party"),
          currentDesc: record.testOwner,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 试验资质
        {
          changeContent: this.$t("plan.dvp.test-qualification"),
          currentDesc: this.isOrNotMap[record.testCertification] || "-",
          changeDesc: undefined,
          changeReason: undefined
        },
        // 试验地点
        {
          changeContent: this.$t("plan.dvp.test-location"),
          currentDesc: record.testSite,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 试验阶段
        {
          changeContent: this.$t("plan.dvp.test-stage"),
          currentDesc: record.testStageName,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 试验频率
        {
          changeContent: this.$t("plan.dvp.test-frequency"),
          currentDesc: record.testFrequency,
          changeDesc: undefined,
          changeReason: undefined
        },
        // 样本类型
        {
          changeContent: this.$t("plan.dvp.sample-type"),
          currentDesc: this.sampleTypeMap[record.sampleType] || '-',
          changeDesc: undefined,
          changeReason: undefined
        },
        // 样本数量
        {
          changeContent: this.$t("plan.dvp.number-of-samples"),
          currentDesc: record.count,
          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: undefined,
          changeReason: undefined
        },
        // 不展开实验原因
        {
          changeContent: this.$t("base.info.reason-for-not-conducting-the-experiment"),
          currentDesc: "-",
          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.testSource = record.testSource;
      // 是否显示不开展试验原因
      if (record.isCarryOut === 1 || record.isCarryOut === undefined || record.isCarryOut === null) {
        this.$refs.applyChange.causeShowFlag = true;
      }
      // 开启弹窗
      this.applyFlag = true;
    }
  }
}

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

.layout-card {
 padding: 12px;
}

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

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