<template>
  <div class="p12">
    <a-row :gutter="24" class="topCard">
      <!-- DVP计划-检索条件 -->
      <a-card class="topCardMargin p12">
        <a-form layout="vertical">
          <!-- 试验车用途 -->
          <a-col :lg="8" :md="12" :sm="24" :xl="6" :xs="24">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.vehicle-use-description')">
              <a-input
                  v-model="queryParam.vehicleUse"
                  :placeholder="$t('dvp.full.vehicle.dvp.please-enter-vehicle-use-description')"
                  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('dvp.full.vehicle.dvp.vehicle-status-description')">
              <a-input
                  v-model="queryParam.vehicleState"
                  :placeholder="$t('dvp.full.vehicle.dvp.please-enter-vehicle-status-description')"
                  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('dvp.full.vehicle.dvp.vehicle-actual-delivery-time')">
              <a-range-picker v-model="queryParam.prototypeActualTime" @change="changeDeliveryTime" allowClear valueFormat="YYYY-MM-DD" style="width: 100%" />
            </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="advanceExpand ? 6 : 18" :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>
            <!-- 任务状态 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='advanceExpand ? 6 : 18' :xs='24'>
              <a-form-item :label="$t('dvp.full.vehicle.dvp.task-status')">
                <a-select
                    v-model="queryParam.taskStatus"
                    :placeholder="$t('dvp.full.vehicle.dvp.please-select-task-status')"
                    allowClear
                    showSearch
                    @change="changeTaskStatus"
                >
                  <a-icon slot="suffixIcon" type="search"/>
                  <a-select-option
                      v-for="item in taskStatusList"
                      :key="item.value"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- 车辆VIN -->
            <a-col :lg="8" :md="12" :sm="24" :xl="advanceExpand ? 6 : 18" :xs="24">
              <a-form-item :label="$t('dvp.full.vehicle.dvp.vehicle-vin')">
                <a-input
                    v-model="queryParam.vehicleVin"
                    :placeholder="$t('dvp.full.vehicle.dvp.please-enter-vehicle-vin')"
                    allowClear
                    :maxLength='17'
                />
              </a-form-item>
            </a-col>
            <!-- 试验报告编号 -->
            <a-col :lg="8" :md="12" :sm="24" :xl="advanceExpand ? 6 : 18" :xs="24">
              <a-form-item :label="$t('dvp.full.vehicle.dvp.test-report-code')">
                <a-input
                    v-model="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">
                {{ advanceExpand ? $t('plan.dvp.collapse') : $t('plan.dvp.expand') }}
                <a-icon :type="advanceExpand ? 'up' : 'down'"/>
              </a>
              <!-- 重置 -->
              <a-button @click='reset' type="primary" 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="exporBtn" @click='exportFile' style="right: 10px">
            {{ $t('global-btn.export') }}
          </a-button>
        </template>
        <a-table
            ref="tableRefs"
            :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="testReportCode" slot-scope="text,record">
            <span class="clickContent" @click="viewReport(record)" :title="text">{{ record.testReportCode }}</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="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('dvp.full.vehicle.dvp.full-vehicle-performance-module')">
              <a-input
                  v-model="editParam.performanceModule"
                  :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.vehicle-use-description')">
              <a-input
                  v-model="editParam.vehicleUse"
                  :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.vehicle-status-description')">
              <a-input
                  v-model="editParam.vehicleState"
                  :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.vehicle-actual-delivery-time')" required>
              <a-date-picker
                  :placeholder="$t('dvp.full.vehicle.dvp.please-select-vehicle-actual-delivery-time')"
                  class="width100"
                  valueFormat="YYYY/MM/DD"
                  @change='changeDeliveryTime'
                  v-model="editParam.prototypeActualTime"
              />
            </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('dvp.full.vehicle.dvp.please-select-actual-start-time')"
                  class="width100"
                  valueFormat="YYYY/MM/DD"
                  @change='changeStartTime'
                  v-model="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('dvp.full.vehicle.dvp.please-select-actual-end-time')"
                  class="width100"
                  valueFormat="YYYY/MM/DD"
                  @change='changeEndTime'
                  v-model="editParam.actualEndTime"
              />
            </a-form-item>
          </a-col>
          <!-- 车辆VIN -->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('dvp.full.vehicle.dvp.vehicle-vin')" required>
              <a-input
                  v-model="editParam.vin"
                  :placeholder="$t('dvp.full.vehicle.dvp.please-enter-vehicle-vin')"
                  allowClear
                  :maxLength='17'
              />
            </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.test-report-code')" required>
              <a-input
                  v-model="editParam.testReportCode"
                  :placeholder="$t('dvp.full.vehicle.dvp.please-enter-test-report-code')"
                  allowClear
                  :maxLength='100'
              />
            </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.upload-test-report')" required>
              <a-upload-dragger
                  name="file"
                  :multiple="false"
                  action=""
                  :customRequest='editUploadFile'
                  :file-list="fileList"
                  :remove='editRemoveFile'
              >
                <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-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的表头属性变量
					const 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) => {
								col.width = Math.max(x, 130);
							}
						}
					};
					const drag = h('vue-draggable-resizable', { ...dragProps });
					return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
				}
			}
		};
    return {
      /** 查询参数 */
      queryParam: {
        vehicleUse: undefined,          //试验车用途
        vehicleState: undefined,   //车辆状态描述
        prototypeActualTime: undefined,  //样车实际提供时间
        actualStartTime: undefined,     //实际开始时间
        actualEndTime: undefined,       //实际结束时间
        taskStatus: undefined,          //任务状态
        vehicleVin: undefined,          //车辆VIN
        testReportCode: undefined,      //试验报告编号
        dvpId: undefined           // DVP ID
      },
      /** 分页实体 */
      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: 130,
          fixed: 'left',
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true,
        },
        {
          // 整车/白车身
          title: () => this.$t('dvp.full.vehicle.dvp.full-vehicle-white-body'),
          width: 130,
          fixed: 'left',
          align: 'center',
          dataIndex: 'count',
          ellipsis: true
        },
        {
          // 整车性能模块
          title: () => this.$t('dvp.full.vehicle.dvp.full-vehicle-performance-module'),
          width: 200,
          fixed: 'left',
          align: 'center',
          dataIndex: 'performanceModule',
          ellipsis: true
        },
        {
          // 试验车用途描述
          title: () => this.$t('dvp.full.vehicle.dvp.vehicle-use-description'),
          width: 200,
          align: 'center',
          dataIndex: 'vehicleUse',
          ellipsis: true
        },
        {
          // 车辆状态描述
          title: () => this.$t('dvp.full.vehicle.dvp.vehicle-status-description'),
          width: 200,
          align: 'center',
          dataIndex: 'vehicleState',
          ellipsis: true
        },
        {
          // 样车实际提供时间
          title: () => this.$t('dvp.full.vehicle.dvp.vehicle-actual-delivery-time'),
          width: 150,
          align: 'center',
          dataIndex: 'prototypeActualTime',
          ellipsis: true
        },
        {
          // 样车提交延期天数
          title: () => this.$t('dvp.full.vehicle.dvp.vehicle-submission-delay-days'),
          width: 200,
          align: 'center',
          dataIndex: 'daysDeferred',
          ellipsis: true
        },
        {
          // 实际开始时间
          title: () => this.$t('dvp.full.vehicle.dvp.actual-start-time'),
          width: 150,
          align: 'center',
          dataIndex: 'actualStartTime',
          ellipsis: true
        },
        {
          // 实际结束时间
          title: () => this.$t('dvp.full.vehicle.dvp.actual-end-time'),
          width: 150,
          align: 'center',
          dataIndex: 'actualEndTime',
          ellipsis: true
        },
        {
          // 试验周期
          title: () => this.$t('dvp.full.vehicle.dvp.test-cycle'),
          width: 130,
          align: 'center',
          dataIndex: 'testCycle',
          ellipsis: true
        },
        {
          // 任务状态
          title: () => this.$t('dvp.full.vehicle.dvp.task-status'),
          width: 130,
          align: 'center',
          dataIndex: 'taskStatus',
          ellipsis: true,
          customRender: val => {
            let name = this.taskStatusList.find(item => item.value == val).name;
            return name;
          }
        },
        {
          // 车辆VIN
          title: () => this.$t('dvp.full.vehicle.dvp.vehicle-vin'),
          width: 200,
          align: 'center',
          dataIndex: 'vin',
          ellipsis: true
        },
        {
          // 是否上传试验报告
          title: () => this.$t('dvp.full.vehicle.dvp.whether-to-upload-the-test-report'),
          width: 150,
          align: 'center',
          dataIndex: 'isUpload',
          ellipsis: true,
          customRender: val => {
            return val === 0 ? "N" : "Y";
          }
        },
        {
          // 试验报告编号
          title: () => this.$t('dvp.full.vehicle.dvp.test-report-code'),
          width: 200,
          align: 'center',
          dataIndex: 'testReportCode',
          scopedSlots: {
            customRender: 'testReportCode'
          },
        },
        {
          // 操作
          title: () => this.$t('global-constant.operation'),
          dataIndex: 'operation',
          key: 'operation',
          align: 'center',
          width: 130,
          scopedSlots: {
            customRender: 'operation'
          },
          fixed: 'right'
        }
      ],
      /** 任务状态下拉数据 */
      taskStatusList: [
        {
          name: this.$t('dvp.full.vehicle.dvp.not-start'),
          value: 0
        },
        {
          name: this.$t('dvp.full.vehicle.dvp.underway'),
          value: 1
        },
        {
          name: this.$t('dvp.full.vehicle.dvp.done'),
          value: 2
        },
      ],
      /** 表格数据 */
      tableData: [],
      /** 表格Loading */
      tableLoading: false,
      /** 编辑模态框显隐 */
      isEdit: false,
      /** 编辑模态框数据 */
      editParam: {
        performanceModule: undefined,   //整车性能模块
        vehicleUse: undefined,          //试验车用途
        vehicleState: undefined,   //车辆状态描述
        prototypeActualTime: undefined,  //样车实际提供时间
        actualStartTime: undefined,     //实际开始时间
        actualEndTime: undefined,       //实际结束时间
        vin: undefined,          //车辆VIN
        testReportCode: undefined,      //试验报告编号
      },
      /** 试验报告附件list */
      fileList: [],
      /** 高度计算 */
      tableHeight: window.innerHeight - 352 + 'px',
      tableHeightValue: window.innerHeight - 560,
      // 表格总宽度
      tableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,

      advanceExpand: false,
      // 权限
      isLook: false
    }
  },
  watch: {
    columns: {
      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
    }
  },
  created() {
    this.isLook = this.$api.isLook === '1'
    this.list()
    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(250, 250, 250)';
        // 表头外层盒子的的实际样式
        let computedDivStyle = window.getComputedStyle(tableHeaderDiv);
        // 表头外层盒子的的实际高度
        let tableDivHeight = parseFloat(computedDivStyle.getPropertyValue('height'));
        // 表头的实际样式
        let computedTableStyle = window.getComputedStyle(tableHeaderReal);
        // 表头的实际高度
        let tableHeight = parseFloat(computedTableStyle.getPropertyValue('height'));
        // 设置底部外边距，一下会是负值，用于将表头下的数据单元格纵向对齐
        tableHeaderDiv.style.marginBottom = (tableHeight-tableDivHeight)+'px';
      }
    },
    // 获取表格的总宽度
    handleResize() {
      this.tableWidth = this.$refs.tableRefs.$el.offsetWidth;
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal(){
      this.columnsWidth = this.columns.reduce((sum, column) => sum + column.width, 0);
    },
    // 动态修改fixe的属性以便表格样式不出现空白列,并平和各列与表格的总宽度
    changeFixed(){
      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;
      }
    },
    /** 获取列表数据 */
    list() {
      let _this = this;
      _this.tableLoading = true;
      let data = {
        dvpId: _this.$store.getters.dvpId,
        vehicleUse: _this.queryParam.vehicleUse,
        vehicleState: _this.queryParam.vehicleState,
        prototypeActualStartTime: _this.queryParam.prototypeActualStartTime,
        prototypeActualEndTime: _this.queryParam.prototypeActualEndTime,
        actualStartStartTime: _this.queryParam.actualStartStartTime,
        actualStartEndTime: _this.queryParam.actualStartEndTime,
        actualEndStartTime: _this.queryParam.actualEndStartTime,
        actualEndEndTime: _this.queryParam.actualEndEndTime,
        taskStatus: _this.queryParam.taskStatus,
        vehicleVin: _this.queryParam.vehicleVin,
        testReportCode: _this.queryParam.testReportCode,
        pagination: {
          pageSize: _this.pagination.pageSize,
          pageCurrent: _this.pagination.current
        }
      };
      this.$api.initDvpVerifyList(data).then(res => {
        if (!res.flag) {
          this.$notification.error({message: res.message});
        }
        _this.tableData = res.data.data || [];
        _this.pagination.total = res.data.total || 0;
      }).finally(() => {
        _this.tableLoading = false;
      });
    },
    /** 导出 */
    exportFile() {
      this.download('/DFMEA/dvp/fullVehicle/dvpVerifyExcelExport', {
        vehicleUse: this.queryParam.vehicleUse || '',
        vehicleState: this.queryParam.vehicleState || '',
        prototypeActualTime: this.queryParam.prototypeActualTime || '',
        actualStartTime: this.queryParam.actualStartTime || '',
        actualEndTime: this.queryParam.actualEndTime || '',
        taskStatus: this.queryParam.taskStatus || '',
        vehicleVin: this.queryParam.vehicleVin || '',
        testReportCode: this.testReportCode || '',
        dvpId: this.$store.getters.dvpId || '',
      });
    },
    /** 查询 */
    search() {
      this.pagination.pageCurrent = 1;
      this.list()
    },
    /** 重置 */
    reset() {
      this.queryParam.vehicleUse = undefined;
      this.queryParam.vehicleState = undefined;
      this.queryParam.prototypeActualStartTime = undefined;
      this.queryParam.prototypeActualEndTime = undefined;
      this.queryParam.actualStartStartTime = undefined;
      this.queryParam.actualStartEndTime = undefined;
      this.queryParam.actualEndStartTime = undefined;
      this.queryParam.actualEndEndTime = undefined;
      this.queryParam.prototypeActualTime = undefined;
      this.queryParam.actualStartTime = undefined;
      this.queryParam.actualEndTime = undefined;
      this.queryParam.taskStatus = undefined;
      this.queryParam.vehicleVin = undefined;
      this.queryParam.testReportCode = undefined;
      this.advanceExpand = false;
      this.list();
    },
    /** 编辑模态框及模态框数据获取 */
    editInit(data) {
      this.isEdit = true;
      this.editParam = {...this.editParam, ...data};
      // 实验报告回显
      if (data.isUpload && data.isUpload == 1) {
        let fileList = {
            uid: data.fileId,
            name: data.fileName,
            status: 'done',
            fileName: data.fileName,
            fileSize: data.fileSize,
            filePath: data.filePath,
            newFileName: data.newFileName
          };
        this.fileList.push(fileList);
      }
    },
    /**
     * 实验报告，文件上传
     * @param obj 回调对象
     */
    editUploadFile(obj) {
      let _that = this;
      _that.fileList = [];
      if (obj.file.size > 104857600) {
        _that.$message.warning(_that.$t('global-message.warn.uploaded-files-cannot-exceed'));
        return;
      }
      let fd = new FormData();
      fd.append('file', obj.file);
      fd.append('fileType', '17');
      _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: obj.file.uid
          });
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {});
    },
    /**
     * 实验报告，文件删除
     * @param file 文件
     */
    editRemoveFile(file) {
      this.fileList = [];
    },

    /**
     * 校验数据是否正确
     */
    isNull() {
      let _that = this;
      if (!_that.editParam.prototypeActualTime && _that.editParam.vin) {

        _that.$notification.warn({message: _that.$t('dvp.please-enter-the-actual-delivery-time-of-the-sample-vehicle')});
        return false;
      }
      if (!_that.editParam.vin && _that.editParam.prototypeActualTime) {
        _that.$notification.warn({message: _that.$t('dvp.please-enter-the-vehicle-VIN')});
        return false;
      }
      let message = [];
      // 如果样车时间晚于计划结束时间
      if (Date.parse(_that.editParam.prototypeActualTime) > Date.parse(_that.editParam.actualEndTime)) {
        message.push(_that.$t('plan.dvp.prototype-time-can-not-later-than-end-time'));
      }
      if (message && message.length > 0) {
        for (let i = 0; i < message.length; i++) {
          _that.$notification.warning({message: message[i]});
        }
        return false;
      }
      return true;
    },

    /** 编辑 保存 */
    save() {
      let _that = this;
      if (!_that.isNull()) {
        return false;
      }
      let data = {
        dvpId: _that.$store.getters.dvpId,
        testId: _that.editParam.testId,
        prototypeActualTime: _that.editParam.prototypeActualTime,
        actualStartTime: _that.editParam.actualStartTime,
        actualEndTime: _that.editParam.actualEndTime,
        vehicleVin: _that.editParam.vin,
        testReportCode: _that.editParam.testReportCode,
        dvpAddFileModels: _that.fileList
      };
      _that.$api.dvpVerifySave(data).then(res => {
        if (!res.flag) {
          _that.$notification.error({message: res.message});
        }
        _that.$message.success(res.message, 1);
        _that.offModal();
        _that.list();
      });
    },
    /** 编辑 取消 */
    offModal() {
      this.isEdit = false;
      this.editParam = [];
      this.fileList = [];
    },
    /** 样车实际提供时间-选择变化 */
    changeDeliveryTime(data, dateString) {
      if (this.isEdit) {
        this.editParam.prototypeActualTime = dateString;
      } else {
        this.queryParam.prototypeActualStartTime = dateString[0];
        this.queryParam.prototypeActualEndTime = dateString[1];
      }
    },

    /**
     * 样车时间不能选择当天以前 实际结束时间以后
     * @param current
     * @returns {boolean}
     */
    disabledDeliveryDate(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;
      } else {
        this.queryParam.actualEndStartTime = dateString[0];
        this.queryParam.actualEndEndTime = dateString[1];
      }
    },
    /** 任务状态 下拉变化 */
    changeTaskStatus(value, options) {
      this.queryParam.taskStatus = options ? options.data.key : undefined;
    },
    /** 点击分页中数字触发的方法 */
    handleOuterTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.pagination.pageNo = pagination.current;
      this.list();
    },
    // 收起/展开
    toggleAdvance() {
      this.advanceExpand = !this.advanceExpand;
      if(this.advanceExpand) {
        this.tableHeightValue -= 100
      } else {
        this.tableHeightValue = window.innerHeight - 560;
      }
    },
    /***
     * 查看试验报告并下载
     * @param val
     */
    viewReport(val) {
      let url = this.$api.baseUrl + '/DFMEA/file/downloadFile.do?id=' + parseInt(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
      });
    }
  }
}
</script>

<style lang="less" scoped>
.topCardMargin {
  margin-top: -12px;
}
.topCard {
  padding: 0 12px;
}
.exporBtn {
  margin-top: -12px;
  margin-right: -24px;
}

.noPad {
  padding: 0 !important;
}

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