<template>
  <div class="p12">
    <a-row :gutter="24" class="top-card">
      <!-- DVP计划-检索条件 -->
      <a-card class="top-card-margin p12">
        <a-form layout="vertical">
          <!-- 验证内容 -->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('base.info.verification-content')">
              <a-input v-model.trim="queryParam.verify" :placeholder="$t('base.info.please-enter-verification-content')" allowClear :maxLength='500'/>
            </a-form-item>
          </a-col>
          <!-- 试验来源 -->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('plan.dvp.test-source')">
              <a-select v-model="queryParam.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>
            </a-form-item>
          </a-col>
          <!-- 样本类型 -->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('base.info.sample-type')">
              <a-select allowClear v-model="queryParam.sampleType" :options="sampleTypeList" :placeholder="$t('plan.dvp.please-enter-sample-type')"/>
            </a-form-item>
          </a-col>
          <!-- 实际开始时间 -->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.actual-start-time')">
              <a-range-picker v-model="queryParam.actualStartTime" @change="changeStartTime" allowClear valueFormat="YYYY-MM-DD" style="width: 100%" />
            </a-form-item>
          </a-col>
          <span v-show="advanceExpand">
          <!-- 实际结束时间 -->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.actual-end-time')">
              <a-range-picker v-model="queryParam.actualEndTime" @change="changeEndTime" allowClear valueFormat="YYYY-MM-DD" style="width: 100%" />
            </a-form-item>
          </a-col>
          <!--DV是否完成-->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('base.info.is-DV-completed')">
              <a-select v-model="queryParam.isFinish" :placeholder="$t('base.info.please-select-is-DV-completed')">
                <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>
          <!-- DV试验结果 -->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('base.info.DV-test-results')">
              <a-select v-model="queryParam.testResult" :placeholder="$t('base.info.please-select-DV-test-results')" allowClear>
                <a-select-option :value="1">{{ $t('global-btn.pass') }}</a-select-option>
                <a-select-option :value="0">{{ $t('global-btn.fail') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- 试验报告编号 -->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.test-report-code')">
              <a-input v-model.trim="queryParam.testReportCode" :placeholder="$t('dvp.full.vehicle.dvp.please-enter-test-report-code')" allowClear :maxLength='100'/>
            </a-form-item>
          </a-col>
          </span>
          <a-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">
            <a-form-item class='tr' :label="'\xa0'">
              <!-- 展开/收起 -->
              <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="ml10">
                {{ $t('global-btn.reset') }}
              </a-button>
              <!-- 查询 -->
              <a-button @click='search' type="primary" class="ml10">
                {{ $t('global-btn.search') }}
              </a-button>
            </a-form-item>
          </a-col>
        </a-form>
      </a-card>
    </a-row>
    <a-row class="mt10">
      <a-card class="p12" :style="{ height: tableHeight }">
        <template slot="extra">
          <!-- 导出 -->
          <a-button class="exportBtn" @click='exportFile' style="right: 10px">
            {{ $t('global-btn.export') }}
          </a-button>
        </template>
        <a-table
            ref="tableRef"
            :columns="columns"
            :dataSource="tableData"
            :pagination="pagination"
            :rowKey="(record, index) => { return index; }"
            :loading="tableLoading"
            size="small"
            @change="handleOuterTableChange"
            :scroll="{ x: tableWidth, y: tableHeightValue }"
            :components='components'
					  bordered>
          <!-- 序号列 -->
          <template slot='index' slot-scope='text, record, index'>
            <span>{{ (pagination.pageCurrent - 1) * pagination.pageSize + index + 1 }}</span>
          </template>
          <!-- 是否开展实验 -->
          <template slot="isFinish" slot-scope="text, record">
            <span>{{ isOrNotMap[record.isFinish] || '-' }}</span>
          </template>
          <!-- 试验结果 -->
          <template slot="testResult" slot-scope="text, record">
            <span>{{ passOrNotMap[record.testResult] || '-' }}</span>
          </template>
          <!-- 试验结果 -->
          <template slot="testReportCode" slot-scope="text, record">
            <span :title="text" class="clickContent" @click="viewListReport(record)"> {{ record.testReportCode }}</span>
          </template>
          <!-- 整改后试验结果 -->
          <template slot="reformVerifyResult" slot-scope="text, record">
            <span>{{ passOrNotMap[record.reformVerifyResult] || '-' }}</span>
          </template>
          <!-- 样件类型 -->
          <template slot="sampleType" slot-scope="text, record">
            <span>{{ sampleTypeMap[record.sampleType] || '-' }}</span>
          </template>
          <!--操作-->
          <template slot='operation' slot-scope='name, row'>
            <!-- 编辑 -->
            <a href='javascript: void(0);' @click='editInit(row)' :disabled="isLook">
              <a-tooltip :title="$t('global-btn.edit')">
                <i class='iconfont iconicon-bianji'></i>
              </a-tooltip>
            </a>
          </template>
        </a-table>
      </a-card>
    </a-row>
    <!-- 编辑模态框 -->
    <a-modal v-model="isEdit" :title="$t('header.dvp-verify')" @ok="save" @cancel="offModal" :width="1100" :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 :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('plan.dvp.test-source')">
              <a-select v-model="editParam.testSource" :disabled="true" :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>
            </a-form-item>
          </a-col>
          <!-- 样本数量 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('plan.dvp.number-of-samples')">
              <a-input v-model="editParam.count" :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.sample-type')">
              <a-input v-model="sampleTypeMap[editParam.sampleType]" :disabled="true"/>
            </a-form-item>
          </a-col>
          <!-- 实际开始时间 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.actual-start-time')" required>
              <a-date-picker
                :placeholder="$t('global-btn.please-select') + $t('dvp.full.vehicle.dvp.actual-start-time')"
                style="width: 100%"
                valueFormat="YYYY/MM/DD"
                :disabled-date="disabledStartDate"
                @change='changeStartTime'
                :value="editParam.actualStartTime"
              />
            </a-form-item>
          </a-col>
          <!-- 实际结束时间 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.actual-end-time')" required>
              <a-date-picker
                :placeholder="$t('global-btn.please-select') + $t('dvp.full.vehicle.dvp.actual-end-time')"
                style="width: 100%"
                valueFormat="YYYY/MM/DD"
                :disabled-date="disabledEndDate"
                @change='changeEndTime'
                :value="editParam.actualEndTime"
              />
            </a-form-item>
          </a-col>
          <!--DV是否完成-->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('base.info.is-DV-completed')" required>
              <a-select v-model="editParam.isFinish"  :disabled="isFinishDisabled" :placeholder="$t('global-btn.please-select') + $t('base.info.is-DV-completed')">
                <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>
          <!--DV试验结果-->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('base.info.DV-test-results')" required>
              <a-select v-model="editParam.testResult" :disabled="isResultDisabled" :placeholder="$t('global-btn.please-select') + $t('base.info.DV-test-results')">
                <a-select-option :value="1">{{ $t('global-btn.pass') }}</a-select-option>
                <a-select-option :value="0">{{ $t('global-btn.fail') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--   当DV试验结果为通过 则显示试验报告上传组件和试验报告编号输入框   -->
          <!-- 试验报告编号 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24" v-if="editParam.testResult === 1">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.test-report-code')" required>
              <a-input v-model.trim="editParam.testReportCode" :maxLength="100" allowClear :placeholder="$t('global-constant.please-enter') + $t('dvp.full.vehicle.dvp.test-report-code')"/>
            </a-form-item>
          </a-col>
          <!-- 试验报告上传组件 -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24" v-if="editParam.testResult === 1">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.upload-test-report')" required>
              <a-upload-dragger
                name="file"
                :multiple="false"
                action=""
                :customRequest='resultUploadFile'
                :remove='resultRemoveFile'
                :file-list="resultFileList"
              >
                <p class="ant-upload-drag-icon">
                  <a-icon type="inbox"/>
                </p>
                <p class="ant-upload-text">
                  {{ $t('dvp.full.vehicle.dvp.click-drag-file-area') }}
                </p>
                <p class="ant-upload-hint">
                  {{ $t('dvp.full.vehicle.dvp.only-support-single-upload') }}
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
      <a-row :gutter="24">
        <!-- 当DV验证结果为不通过的时候，显示表格 -->
        <div class="p12" v-if="editParam.testResult === 0">
          <!-- 整改记录表格 -->
          <a-form-item :label="$t('base.info.rectification-record')" required>
          <a-table
            ref="editTableRef"
            :columns="editColumns"
            :dataSource="editTableData"
            :pagination="false"
            :rowKey="(record, index) => { return index; }"
            :loading="tableLoading"
            size="small"
            bordered
            :scroll="{ x: editTableWidth, y: editTableHeightValue }"
            :components='components'
          >
            <!-- 整改后试验结果 -->
            <template slot="reformVerifyResult" slot-scope="text, row,index">
              <span v-if="row.logId" > {{ passOrNotMap[row.reformVerifyResult] || '-' }} </span>
              <a-select
                v-else
                v-model="row.reformVerifyResult"
                style="width: 120px"
                @change="handleResult(row,row.reformVerifyResult,index)"
                :placeholder="$t('global-btn.please-select') + $t('base.info.verification-results-after-rectification')"
                :disabled="row.isDisabled"
              >
                <a-select-option :value="0">{{ $t('global-btn.fail') }}</a-select-option>
                <a-select-option :value="1">{{ $t('global-btn.pass') }}</a-select-option>
              </a-select>
            </template>
            <!-- 整改后试验报告编号 -->
            <template slot="testReportCode" slot-scope="text, row">
              <span v-if="row.logId"> {{ row.testReportCode }} </span>
              <a-textarea
                v-else
                autoSize
                v-model.trim="row.testReportCode"
                :maxLength="100" :disabled="row.isDisabled"
                :placeholder="$t('global-btn.please-enter') + $t('base.info.test-report-number-after-rectification')">
              </a-textarea>
            </template>
            <!-- 整改后试验报告 -->
            <template slot="testReportId" slot-scope="text, row, index">
              <div v-if="row.testReportId">
               <span style=' font-size:15px;display:block'>
                 <a-icon type="paper-clip"/>
                 <a style='color:#1890FF' @click="viewReport(row)" :title="text">
                  {{ row.fileName }}
                 </a>
               </span>
              </div>
              <div v-else>
                <!-- 上传 -->
                <a-upload
                  name='file'
                  v-if="row.logId == null"
                  :disabled="row.isDisabled"
                  action=''
                  accept='.jpg,.txt,.png,.doc,.docx,.xls,.xlsx,.pdf,.pptx'
                  :fileList='fileList'
                  :showUploadList="currentRowIndex.indexOf(index) !== -1"
                  :customRequest='addUploadFile'
                  :remove='removeFile'>
                  <a class='operation-btn ml16'>
                    <a-tooltip :title="$t('global-btn.select-file')">
                      <a-icon type="upload" @click="fileShow(index)"/>
                    </a-tooltip>
                  </a>
                </a-upload>
              </div>
            </template>
            <!-- 整改后试验计划 -->
            <template slot="reformVerifyPlan" slot-scope="text, row">
              <span v-if="row.logId"> {{ row.reformVerifyPlan }} </span>
              <a-textarea v-else autoSize v-model.trim="row.reformVerifyPlan" :maxLength="128" :disabled="row.isDisabled" :placeholder="$t('dvp.full.vehicle.dvp.please-enter-the-verification-plan-after-rectification')"></a-textarea>
            </template>
            <!-- 序号列 -->
            <template slot='index' slot-scope='text, record, index'>
              <span>{{ index + 1 }}</span>
            </template>
            <!-- 操作 -->
            <template slot="action" slot-scope="name, row, index">
              <div v-if='row.logId == null'>
                <!-- 保存 -->
                <a class="operate-btn"
                   :disabled="row.isDisabled"
                   @click="saveReform(row)">
                  <a-tooltip :title="$t('global-btn.save')">
                    <a-icon type="check"/>
                  </a-tooltip>
                </a>
                <!-- 取消 -->
                <a class="ml10 operate-btn" :disabled="row.isDisabled" @click="cancel(row)">
                  <a-tooltip :title="$t('global-btn.cancel')">
                    <a-icon type="undo"/>
                  </a-tooltip>
                </a>
              </div>
            </template>
          </a-table>
          </a-form-item>
        </div>
      </a-row>
    </a-modal>
    <!-- 文件预览 -->
    <view-office ref="viewModal"/>
  </div>
</template>

<script>
import moment from "moment";
import VueDraggableResizable from 'vue-draggable-resizable';
import ViewOffice from "@/components/viewOffice/viewOffice";

export default {
  name: "dvpVerify",
  components: {
    VueDraggableResizable,
    ViewOffice
  },
  data() {
    this.components = {
			header: {
				cell: (h, props, children) => {
					const { key, ...restProps } = props;
					// 此处的this.columns 是定义的table的表头属性变量
          let col = null;
          if (this.editParam.testResult === 0) {
            col = this.editColumns.find((col) => {
              const k = col.dataIndex || col.key;
              return k === key;
            });
          } else {
            col = this.columns.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) => {
                if (this.editParam.testResult === 0) {
								  col.width = Math.max(x, 100);
							} else {
                  col.width = Math.max(x, 150); }
              }
						}
					};
					const drag = h('vue-draggable-resizable', { ...dragProps });
					return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
				}
			}
		};
    return {
      /** 查询参数 */
      queryParam: {
        verify: undefined,               // 验证内容
        actualStartTime: undefined,      // 实际开始时间
        actualEndTime: undefined,        // 实际结束时间
        testSource: undefined,          // 试验来源
        sampleType: undefined,         // 样本类型
        testResult: undefined,         // DV试验结果
        testReportCode: undefined,     // 测试报告编号
        isFinish: undefined            // DV是否完成
      },
      /** 样件类型 用于表格插槽显示 */
      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')
      },
      /** 分页实体 */
      pagination: {
        pageCurrent: 1,
        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, //总条数,
        position: "bottom"
      },
      /** 表头信息 */
      columns: [
        {
          // 序号
          title: () => this.$t('dvp.full.vehicle.dvp.serial-number'),
          dataIndex: 'index',
          width: 150,
          fixed: 'left',
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true,
        },
        // 系统名称
        {
          title: () => this.$t('base.info.system-name'),
          width: 180,
          fixed: 'left',
          align: 'center',
          dataIndex: 'systemName',
          ellipsis: true
        },
        // 验证内容
        {
          title: () => this.$t('base.info.verification-content'),
          width: 200,
          fixed: 'left',
          align: 'center',
          dataIndex: 'verify',
          ellipsis: true
        },
        // 样本数量
        {
          title: () => this.$t('plan.dvp.number-of-samples'),
          width: 200,
          align: 'center',
          dataIndex: 'count',
          ellipsis: true
        },
        // 样本类型
        {
          title: () => this.$t('base.info.sample-type'),
          width: 200,
          align: 'center',
          dataIndex: 'sampleType',
          scopedSlots: {
            customRender: 'sampleType'
          }
        },
        // 实际开始时间
        {
          title: () => this.$t('dvp.full.vehicle.dvp.actual-start-time'),
          width: 200,
          align: 'center',
          dataIndex: 'actualStartTime',
          ellipsis: true
        },
        // 实际结束时间
        {
          title: () => this.$t('dvp.full.vehicle.dvp.actual-end-time'),
          width: 200,
          align: 'center',
          dataIndex: 'actualEndTime',
          ellipsis: true
        },
        // DV是否完成
        {
          title: () => this.$t('base.info.is-DV-completed'),
          width: 200,
          align: 'center',
          dataIndex: 'isFinish',
          ellipsis: true,
          scopedSlots: {
            customRender: 'isFinish'
          }
        },
        // DV试验结果
        {
          title: () => this.$t('base.info.DV-test-results'),
          width: 200,
          align: 'center',
          dataIndex: 'testResult',
          ellipsis: true,
          scopedSlots: {
            customRender: 'testResult'
          }
        },
        // 试验报告编号
        {
          title: () => this.$t('dvp.full.vehicle.dvp.test-report-code'),
          width: 200,
          align: 'center',
          dataIndex: 'testReportCode',
          scopedSlots: {
            customRender: 'testReportCode'
          }
        },
        // 整改后验证计划
        {
          title: () => this.$t('base.info.verification-plan-after-rectification'),
          width: 200,
          align: 'center',
          dataIndex: 'reformVerifyPlan',
          ellipsis: true,
        },
        // 整改后验证结果
        {
          title: () => this.$t('base.info.verification-results-after-rectification'),
          width: 200,
          align: 'center',
          dataIndex: 'reformVerifyResult',
          ellipsis: true,
          scopedSlots: {
            customRender: 'reformVerifyResult'
          }
        },
        // 操作
        {
          title: () => this.$t('global-constant.operation'),
          dataIndex: 'operation',
          key: 'operation',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'operation'
          },
          fixed: 'right'
        }
      ],
      /** 表格数据 */
      tableData: [],
      /** 编辑模态框数据 */
      editParam: {
        systemName: undefined,                // 系统名称
        verify: undefined,                    // 验证内容
        testSource: undefined,                // 试验来源
        count: undefined,                     // 样本数量
        sampleType: undefined,                // 样本类型
        actualStartTime: undefined,           // 实际开始时间
        actualEndTime: undefined,             // 实际结束时间
        isFinish: undefined,                   // 是否完成
        testResult: undefined,                  // DV验证结果
        testReportCode: undefined               // 试验报告编号
      },
      /** 编辑 表头信息 */
      editColumns: [
        // 整改次数
        {
          title: () => this.$t('base.info.rectification-frequency'),
          width: 50,
          dataIndex:'index',
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true
        },
        // 整改试验计划
        {
          title: () => this.$t('base.info.verification-plan-after-rectification'),
          width: 150,
          align: 'center',
          dataIndex: 'reformVerifyPlan',
          scopedSlots: {
            customRender: 'reformVerifyPlan'
          },
          ellipsis: true,
        },
        // 整改后验证结果
        {
          title: () => this.$t('base.info.verification-results-after-rectification'),
          width: 80,
          align: 'center',
          dataIndex: 'reformVerifyResult',
          scopedSlots: {
            customRender:'reformVerifyResult'
          },
          ellipsis: true,
        },
        // 整改后试验报告编号
        {
          title: () => this.$t('base.info.test-report-number-after-rectification'),
          width: 150,
          align: 'center',
          dataIndex: 'testReportCode',
          scopedSlots: {
            customRender: 'testReportCode'
          },
          ellipsis: true,
        },
        // 整改后试验报告
        {
          title: () => this.$t('base.info.test-report-after-rectification'),
          width: 150,
          align: 'center',
          dataIndex: 'testReportId',
          scopedSlots: {
            customRender: 'testReportId'
          },
          ellipsis: true,
        },
        //操作
        {
          title: this.$t('global-constant.operation'),
          align: 'center',
          width: 50,
          scopedSlots: {customRender: 'action'},
          ellipsis: true
        }
      ],
      /** 编辑 表格数据 */
      editTableData: [],
      /** 折叠 展开 */
      advanceExpand: false,
      /** 表格Loading */
      tableLoading: false,
      /** 编辑模态框显隐 */
      isEdit: false,
      /** 试验报告附件list */
      fileList: [],
      /** 实际开始时间 */
      actualStartTime: undefined,
      /** 实际结束时间 */
      actualEndTime: undefined,
      /** DV是否完成 选择框 可选/不可选 */
      isFinishDisabled: true,
      /** 高度计算 */
      tableHeight: window.innerHeight - 350 + 'px',
      tableHeightValue: window.innerHeight - 560,
      editTableHeightValue: window.innerHeight - 900,
      // 表格总宽度
      tableWidth: 0,
      editTableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
      editColumnsWidth: 0,
      isLook: false,
      /** 是/否Map 用于表格插槽显示 DV是否完成 */
      isOrNotMap: {
        0: this.$t("global-btn.no"),
        1: this.$t("global-btn.yes")
      },
      /** 通过/不通过Map 用于表格插槽显示 DV验证结果 */
      passOrNotMap: {
        0: this.$t("global-btn.fail"),
        1: this.$t("global-btn.pass")
      },
      /** 样件类型下拉选 */
      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'
        }
      ],
      /** 控制上传文件显示用的 */
      currentRowIndex: [],
      /** DV验证结果 上传文件 */
      resultFileList: [],
      /** 控制DV验证结果选择框 是否可用 当为不通过且整改记录表格有数据时，不可用 */
      isResultDisabled: false
    }
  },
  watch: {
    columns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
          // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
          this.getTableDivCss();
        });
      },
      deep: true,
      immediate: true
    },
    editColumns: {
      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
    },
    editTableWidth: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
          // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
          this.getTableDivCss();
        });
      },
      deep: true,
      immediate: true
    },

  },
  created() {
    this.isLook = this.$api.isLook === '1'
    this.initSystemDvpVerifyList()
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 350 + '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(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() {
      if (this.editParam.testResult === 0) {
        this.editTableWidth = this.$refs.editTableRef.$el.offsetWidth;
      } else {
        this.tableWidth = this.$refs.tableRef.$el.offsetWidth;
      }
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal(){
      if (this.editParam.testResult === 0) {
        this.editColumnsWidth = this.editColumns.reduce((sum, column) => sum + column.width, 0);
      } else {
        this.columnsWidth = this.columns.reduce((sum, column) => sum + column.width, 0);
      }
    },
    // 动态修改fixe的属性以便表格样式不出现空白列,并平和各列与表格的总宽度
    changeFixed(){
      if (this.editParam.testResult === 0) {
        if (this.editColumnsWidth <= this.editTableWidth) {
          // 遍历 columns 数组，将有 fixed 属性的元素的 fixed 值设置为 false（当有固定列时，列宽总和小于表格总宽度时会串行）
          this.editColumns.forEach((column) => {
            if (column.fixed) {
              column.fixed = false;
            }
          });
          // 获取除最后一列以外其他列的宽度总和
          let otherColumnsWidth = this.editColumns.slice(0, -1).reduce((total, column) => {
            return total + column.width;
          }, 0);
          // 将最后一列的宽度设置为剩余宽度，避免页面表头与内容显示串行
          this.editColumns[this.editColumns.length - 1].width = this.editTableWidth - otherColumnsWidth;
        }else {
          // 恢复最后一列原始宽度
          this.editColumns[this.editColumns.length - 1].width = 150;
        }
      } else {
        if (this.columnsWidth <= this.tableWidth) {
          // 遍历 columns 数组，将有 fixed 属性的元素的 fixed 值设置为 false（当有固定列时，列宽总和小于表格总宽度时会串行）
          this.columns.forEach((column) => {
            if (column.fixed) {
              column.fixed = false;
            }
          });
          // 获取除最后一列以外其他列的宽度总和
          let otherColumnsWidth = this.columns.slice(0, -1).reduce((total, column) => {
            return total + column.width;
          }, 0);
          // 将最后一列的宽度设置为剩余宽度，避免页面表头与内容显示串行
          this.columns[this.columns.length - 1].width = this.tableWidth - otherColumnsWidth;
        }else {
          // 恢复固定列原始定位属性
          this.columns[0].fixed='left';
          this.columns[1].fixed='left';
          this.columns[2].fixed='left';
          this.columns[this.columns.length - 1].fixed='right';
          // 恢复最后一列原始宽度
          this.columns[this.columns.length - 1].width = 150;
        }
      }
    },
    /** 获取列表数据 */
    initSystemDvpVerifyList() {
      let _that = this;
      _that.tableLoading = true;
      let data = {
        dvpId: _that.$store.getters.dvpId,
        verify: _that.queryParam.verify,
        actualStartStartTime: _that.queryParam.actualStartStartTime,
        actualStartEndTime: _that.queryParam.actualStartEndTime,
        actualEndStartTime: _that.queryParam.actualEndStartTime,
        actualEndEndTime: _that.queryParam.actualEndEndTime,
        testSource: _that.queryParam.testSource,
        sampleType: _that.queryParam.sampleType,
        testResult: _that.queryParam.testResult,
        testReportCode: _that.queryParam.testReportCode,
        isFinish: _that.queryParam.isFinish,
        pagination: {
          pageSize: _that.pagination.pageSize,
          pageCurrent: _that.pagination.current
        }
      };
      this.$api.initSystemDvpVerifyList(data).then(res => {
        if (!res.flag) {
          this.$notification.error({message: res.message});
        }
        _that.tableData = res.data.data || [];
        _that.pagination.total = res.data.total || 0;
      }).finally(() => {
        _that.tableLoading = false;
      });
    },
    /** 导出 */
    exportFile() {
      this.download('/DFMEA/dvp/system/dvpVerifyExcelExport', {
        dvpId: this.$store.getters.dvpId || '',
        verify: this.queryParam.verify || '',
        testSource: this.queryParam.testSource || '',
        sampleType: this.queryParam.sampleType || '',
        actualStartTime: this.queryParam.actualStartTime || '',
        actualEndTime: this.queryParam.actualEndTime || '',
        isFinish: this.queryParam.isFinish || '',
        testResult: this.queryParam.testResult || '',
        testReportCode: this.queryParam.testReportCode || '',
      });
    },
    /** 查询 */
    search() {
      this.pagination.pageCurrent = 1;
      this.initSystemDvpVerifyList()
    },
    /** 重置 */
    reset() {
      this.queryParam = [];
      this.initSystemDvpVerifyList();
    },

    /** 编辑弹框 表格初始化 */
    editTableDataInit(testId) {
      let data = {
        dvpId: this.$store.getters.dvpId,
        testId: testId
      };
      let _that = this;
      _that.$api.dvpVerifyEditInit(data).then(res => {
        if (!res.flag) {
          _that.$notification.error({message: res.message});
          return false;
        }
        _that.editParam.testSource = res.data.dvpSystemDetail.testSource;
        _that.editParam.testId = res.data.dvpSystemDetail.testId;
        // DV验证结果
        _that.editParam.testResult = res.data.dvpSystemDetail.testResult === null ? undefined : res.data.dvpSystemDetail.testResult;
        // 试验报告编号
        _that.editParam.testReportCode = res.data.dvpSystemDetail.testReportCode;
        _that.resultFileList = [];
        let fileData = res.data;
        // 试验报告回显
        if (fileData.fileId) {
          let resultFileList = {
            uid: fileData.fileId,
            name: fileData.fileName,
            status: 'done',
            fileName: fileData.fileName,
            filePath: fileData.filePath,
            newFileName: fileData.newFileName
          };
          _that.resultFileList.push(resultFileList);
        }
        // DV验证结果选择框是否可用 当DV验证结果为不通过且整改记录表格有数据时，选择框不可用
        _that.isResultDisabled = (res.data.dvpSystemVerifyInitModels).length >= 1 && _that.editParam.testResult === 0;
        // 整改记录表格内容
        _that.editTableData = res.data.dvpSystemVerifyInitModels || [];
        _that.editTableData.forEach( item => {
          if (_that.editTableData.testReportId) {
            let fileList = {
              uid: item.fileId,
              name: item.fileName,
              status: 'done',
              fileName: item.fileName,
              filePath: item.filePath,
              newFileName: item.newFileName
            };
            _that.fileList.push(fileList);
          }
          item.reformVerifyResult = parseInt(item.reformVerifyResult);
        });
        if (_that.editTableData.length === 0  || _that.editTableData[_that.editTableData.length - 1].reformVerifyResult === 0) {
          let addDate = {
            reformVerifyResult: undefined,
            testReportCode: '',
            reformVerifyPlan: ''
          };
          _that.editTableData.push(addDate);
        }
      });
    },

    /** 编辑模态框及模态框数据获取 */
    editInit(row) {
      // 编辑弹框内容
      this.editParam.systemName = row.systemName;
      this.editParam.verify = row.verify;
      this.editParam.sampleType = row.sampleType;
      this.editParam.count = row.count;
      this.editParam.actualStartTime = row.actualStartTime;
      this.editParam.actualEndTime = row.actualEndTime;
      this.actualStartTime = row.actualStartTime;
      this.actualEndTime = row.actualEndTime;
      this.editParam.isFinish = row.isFinish;

      // 当实际开始时间和实际结束时间都有值时，才能选择DV是否完成
      if (this.editParam.actualStartTime && this.editParam.actualEndTime) {
        this.isFinishDisabled = false;
      } else {
        this.isFinishDisabled = true;
      }
      // 表格初始化
      this.editTableDataInit(row.testId);
      this.isEdit = true;
    },


    /** 控制上传文件用的 记录点击行的index  */
    fileShow(val) {
      this.currentRowIndex.push(val);
    },

    /**
     * DV验证结果 上传文件
     * @param file
     */
    resultUploadFile(file) {
      let _that = this;
      if (file.file.size > 104857600) {
        _that.$message.warning(this.$t('global-message.warn.uploaded-files-cannot-exceed'));
        return;
      }
      let fd = new FormData();
      fd.append('file', file.file);
      fd.append('fileType', '17');
      _that.resultFileList = [];
      _that.$api.uploadFile(fd).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          // 当编辑弹框的DV验证结果为通过时，则说明上传的试验报告为resultFileList
          _that.resultFileList.push({
            name: res.data.fileName,
            fileName: res.data.fileName,
            filePath: res.data.filePath,
            fileSize: res.data.fileSize,
            newFileName: res.data.newFileName,
            uid: file.file.uid
          });
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      });
    },

    /**
     * 新建整改记录 上传文件
     * @param file
     */
    addUploadFile(file) {
      let _that = this;
      if (file.file.size > 104857600) {
        _that.$message.warning(this.$t('global-message.warn.uploaded-files-cannot-exceed'));
        return;
      }
      let fd = new FormData();
      fd.append('file', file.file);
      fd.append('fileType', '17');
      _that.fileList = [];
      _that.$api.uploadFile(fd).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.fileList.push({
            name: res.data.fileName,
            fileName: res.data.fileName,
            filePath: res.data.filePath,
            fileSize: res.data.fileSize,
            newFileName: res.data.newFileName,
            uid: file.file.uid
          });
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      });
    },

    /** 文件删除 */
    removeFile(file) {
      let files = this.fileList;
      for (let i = files.length - 1; i >= 0; i--) {
        if (file.uid === files[i].uid) { files.splice(i, 1); }
      }
    },

    /** 文件删除 */
    resultRemoveFile(file) {
      let files = this.resultFileList;
      for (let i = files.length - 1; i >= 0; i--) {
        if (file.uid === files[i].uid) { files.splice(i, 1); }
      }
    },

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

    /** 编辑 保存 */
    save() {
      let _that = this;
      let data = {
        dvpId: _that.$store.getters.dvpId,
        testId: _that.editParam.testId,
        actualStartTime: _that.editParam.actualStartTime,
        actualEndTime: _that.editParam.actualEndTime,
        isComplete: _that.editParam.isFinish,
        testReportCode: _that.editParam.testReportCode,
        testResult: _that.editParam.testResult,
        // 当选择不通过，不传附件
        dvpAddFileModels: _that.editParam.testResult === 0 ? null : _that.resultFileList
      };
      _that.$api.editVerifyTest(data).then(res => {
        if (!res.flag) {
          _that.$notification.error({message: res.message});
        } else {
          _that.$message.success(res.message, 1);
          _that.resultFileList = [];
          _that.offModal();
          _that.initSystemDvpVerifyList();
        }
      });
    },

    /** 编辑 取消 */
    offModal() {
      this.isEdit = false;
      this.isFinishDisabled = true;
      this.editParam.actualEndTime = undefined;
      this.editParam.actualStartTime = undefined;
      this.editParam.isFinish = undefined;
      this.editParam.testResult = undefined;
      this.fileList = [];
    },

    /**
     * 非空校验 判断是否为空
     * @returns {boolean}
     */
    isNull(row) {
      let _that = this;
      let message = [];
      // 实际开始时间
      if (!_that.editParam.actualStartTime) {
        message.push(_that.$t('global-constant.please-select') + _that.$t('dvp.full.vehicle.dvp.actual-start-time'));
      }
      // 实际结束时间
      if (!_that.editParam.actualEndTime) {
        message.push(_that.$t('global-constant.please-select') + _that.$t('dvp.full.vehicle.dvp.actual-end-time'));
      }
      // DV完成
      if (!_that.editParam.isFinish) {
        message.push(_that.$t('global-constant.please-select') + _that.$t('base.info.is-DV-completed'));
      }
      // 试验结果
      if (row.reformVerifyResult === undefined  || row.reformVerifyResult == null) {
        message.push(_that.$t('global-constant.please-select') + _that.$t('base.info.DV-test-results'));
      }
      if (message && message.length > 0) {
        for (let i = 0; i < message.length; i++) {
          _that.$notification.warning({message: message[i]});
        }
        return false;
      }
      return true;
    },


    /** 编辑弹框表格 保存 */
    saveReform(row) {
      // 验证表格上方表单内容是否为空
      if (!this.isNull(row)) {
        return false;
      }

      // 如果选择了通过，但没有上传实验报告，弹出提醒
      if (row.reformVerifyResult === 1 && this.fileList.length < 1) {
        this.$notification.warning({message: this.$t('dvp.full.vehicle.dvp.please-upload-test-report')});
        return false;
      }

      // 如果选择了通过，但没有输入实验报告编号，弹出提醒
      if (row.reformVerifyResult === 1 && row.testReportCode === '') {
        this.$notification.warning({message: this.$t('dvp.full.vehicle.dvp.please-enter-test-report-code')});
        return false;
      }

      // 如果选择了不通过，但没有输入整改后验证计划，弹出提醒
      if (row.reformVerifyResult !== 1 && row.reformVerifyPlan === '') {
        this.$notification.warning({message: this.$t('dvp.full.vehicle.dvp.please-enter-the-verification-plan-after-rectification')});
        return false;
      }

      let _that = this;
      let data = {
        dvpId: _that.$store.getters.dvpId,
        testId: _that.editParam.testId,
        actualStartTime: _that.editParam.actualStartTime,
        actualEndTime: _that.editParam.actualEndTime,
        verifyResult: row.reformVerifyResult,
        verifyPlan: row.reformVerifyPlan,
        reformTestReportCode: row.testReportCode,
        isComplete: _that.editParam.isFinish,
        testReportCode: _that.editParam.testReportCode,
        testResult: _that.editParam.testResult,
        reformDvpAddFileModels: _that.fileList
      };
      _that.$api.editVerifyTest(data).then(res => {
        if (!res.flag) {
          _that.$notification.error({message: res.message});
        } else {
          _that.$message.success(res.message, 1);
          _that.fileList = [];
          // 编辑弹框 表格初始化
          _that.editTableDataInit(_that.editParam.testId);
          _that.initSystemDvpVerifyList();
        }
      });
    },

    /** 编辑弹框表格 取消 */
    cancel(row) {
      row.testResult = 1;
      row.reformVerifyPlan = '';
      row.testReportCode = '';
    },

    /**
     * 开始时间不能选择当天
     * @param current
     * @returns {boolean}
     */
    disabledStartDate(current) {
      return current && current < moment().subtract(1,"day").endOf('day');
    },

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

    /** 实际开始时间-选择变化 */
    changeStartTime(data, dateString) {
      if (this.isEdit) {
        this.editParam.actualStartTime = dateString;
        // 当选择的开始时间大于结束时间时，清空结束时间，让用户重新选择结束时间
        if (Date.parse(this.editParam.actualStartTime) >= Date.parse(this.editParam.actualEndTime)) {
          this.editParam.actualEndTime = undefined;
        }
      } else {
        this.queryParam.actualStartStartTime = dateString[0];
        this.queryParam.actualStartEndTime = dateString[1];
      }
    },
    /** 实际结束时间-选择变化 */
    changeEndTime(data, dateString) {
      if (this.isEdit) {
        this.editParam.actualEndTime = dateString;
        this.isFinishDisabled = false;
      } else {
        this.queryParam.actualEndStartTime = dateString[0];
        this.queryParam.actualEndEndTime = dateString[1];
      }
    },

    /** 整改结果 */
    handleResult(row,testResult,index) {
      // 选择“不通过”，新增一行空白行
      if (parseInt(testResult) === 0) {
        let addDate = {
          reformVerifyResult: undefined,
          testReportCode: '',
          reformVerifyPlan: '',
          isDisabled: true
        };
        this.editTableData.push(addDate);
      }
    },

    /**
     * 查看报告 编辑-整改记录
     * @param val
     */
    viewReport(val) {
      let url = this.$api.baseUrl + '/DFMEA/file/downloadFile.do?id=' + val.fileId + '&fileType=17';
      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.fileId,
        fileType: 17
      });
    },

    /**
     * 查看报告
     * @param val
     */
    viewListReport(val) {
      let url = this.$api.baseUrl + '/DFMEA/file/downloadFile.do?id=' + val.fileId + '&fileType=17';
      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.fileId,
        fileType: 17
      });
    },

    /** 点击分页中数字触发的方法 */
    handleOuterTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.pagination.pageNo = pagination.current;
      this.initSystemDvpVerifyList();
    }
  }
}
</script>

<style lang="less" scoped>
.top-card-margin {
  margin-top: -12px;
}
.top-card {
  padding: 0 12px;
}
.card-overFlow {
  overflow-x: hidden;
  overflow-y: auto;
}
.exportBtn {
  margin-top: -12px;
  margin-right: -24px;
}
/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);
}

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

</style>
