<template>
  <div>
    <a-modal
      :title=" $t('global-btn.apply-for-changes')"
      :visible="applyFlag"
      :width="1000"
      :maskClosable="false"
      @ok="save"
      @cancel="closeModal"
      :footer="null"
    >
      <div>
        <a-table
          ref="tableRefs"
          :columns='tableColumns'
          :dataSource='tableData'
          :pagination='false'
          :rowKey='(record, index) => { return index; }'
          :scroll='{ x: tableWidth, y: tableHeightValue }'
          size="small"
          bordered
          :components='components'
        >
          <!-- 变更后描述 -->
          <template slot='changeDesc' slot-scope='text, record, index'>
            <!-- 输入框 -->
            <a-input v-if="slotInputFlag(record.changeContent) === 1" v-model.trim="record.changeDesc" :placeholder="$t('global-constant.please-enter')"></a-input>
            <!-- 数字输入框 -->
            <a-input-number v-else-if="slotInputFlag(record.changeContent) === 2" v-model.number="record.changeDesc" :min="1" :max="999" :placeholder="$t('plan.dvp.please_select-number-of-vehicles')" style="width: 100%"></a-input-number>
            <!-- 试验类型 -->
            <a-select v-else-if="index === 1" v-model="record.changeDesc" :options="testTypeList" allowClear style="width: 100%" :placeholder="$t('plan.dvp.please_select-test-type')"></a-select>
            <!-- 试验负责人 -->
            <a-select v-else-if="index === 5" v-model="record.changeDesc" :options="testOwnerList" allowClear style="width: 100%" :placeholder="$t('plan.dvp.please_select-study-director')"></a-select>
            <!-- 项目节点 -->
            <a-select v-else-if="index === 6" v-model="record.changeDesc" :options="projectNodeList" allowClear style="width: 100%" :placeholder="$t('plan.dvp.please_select-project-node')"></a-select>
            <!-- 样车提供时间 -->
            <a-date-picker v-else-if="index === 7" @change='handlePlanTime' v-model="record.changeDesc" :placeholder="$t('global-btn.please-select')" style="width: 100%" valueFormat="YYYY/MM/DD"/>
            <!-- 计划开始时间 -->
            <a-date-picker v-else-if="index === 8" :disabled-date="disabledStartDate" @change='handleStartTime' v-model="record.changeDesc" :placeholder="$t('global-btn.please-select')" style="width: 100%" valueFormat="YYYY/MM/DD"/>
            <!-- 计划结束时间 -->
            <a-date-picker v-else-if="index === 9" :disabled-date="disabledEndDate" @change='handleEndTime' v-model="record.changeDesc" :placeholder="$t('global-btn.please-select')" style="width: 100%" valueFormat="YYYY/MM/DD"/>
            <!--动态下拉选框-->
            <a-select v-else-if="index > 9" v-model="record.changeDesc" :options="selectDataList[tableDataLength - index]" allowClear style="width: 100%" :placeholder="$t('global-constant.please-select')"></a-select>
          </template>
          <!-- 变更原因 -->
          <template slot='changeReason' slot-scope='text, record'>
            <a-textarea autoSize v-model.trim="record.changeReason" :maxLength="500" :placeholder="$t('base.info.please-enter-change-reason')"></a-textarea>
          </template>
          <!-- 操作列 -->
          <template slot="action" slot-scope="text, record">
            <span>
              <!-- 取消 -->
              <a class="ml10 operate-btn" @click="reset(record)">
                <a-tooltip :title="$t('global-btn.reset')">
                  <a-icon type="undo"/>
                </a-tooltip>
              </a>
            </span>
          </template>
        </a-table>
        <!-- 弹窗footer -->
        <div slot="footer" class="mt10 text-right">
          <a-button @click="closeModal">
            {{ $t('global-btn.cancel') }}
          </a-button>
          <a-button class="ml10" type="primary" @click="save()">
            {{ $t('global-btn.confirm') }}
          </a-button>
        </div>
      </div>
    </a-modal>
    <!-- 提交审批 -->
    <submit-approval
      ref='submitApproval'
      :title='submitApprovalTitle'
      :visible='submitApprovalVisible'
      :rfmeaType="'D'"
      @close='submitApprovalVisible = false'
    />
  </div>
</template>

<script>

import SubmitApproval from '@/components/SubmitApprovalModal';
import moment from "moment";
import VueDraggableResizable from 'vue-draggable-resizable';

export default {
  name: "AddDvpTest",
  components: {
    SubmitApproval,
    VueDraggableResizable
  },
  props: {
    applyFlag: {
      type: Boolean,
      default: false
    },
    applyTableData: {
      type: Array,
      default: []
    }
  },
  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, 80);
							}
						}
					};
					const drag = h('vue-draggable-resizable', { ...dragProps });
					return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
				}
			}
		};
    return {
      /** 动态下拉选框  */
      selectDataList: [],
      /** 试验类型字典  */
      testTypeList: [
        {
          label: this.$t("plan.dvp.test-type-mule-car"),
          value: "0"
        },
        {
          label: this.$t("plan.dvp.test-type-know-the-real-situation"),
          value: "1"
        },
        {
          label: this.$t("plan.dvp.test-type-alignment"),
          value: "2"
        },
        {
          label: this.$t("plan.dvp.test-type-check-and-accept"),
          value: "3"
        },
        {
          label: this.$t("plan.dvp.test-type-consistence"),
          value: "4"
        }
      ],
      /**试验负责人*/
      testOwnerList: [],
      /**项目节点*/
      projectNodeList: [],
      planStartTime: undefined,
      planEndTime: undefined,
      tableColumns: [
        // 变更内容
        {
          title: this.$t('base.info.change-content'),
          dataIndex: 'changeContent',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // 当前描述
        {
          title: this.$t('base.info.current-description'),
          dataIndex: 'currentDesc',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // 变更后描述
        {
          title: this.$t('base.info.description-after-change'),
          dataIndex: 'changeDesc',
          width: 100,
          align: 'center',
          ellipsis: true,
          scopedSlots: {
            customRender: 'changeDesc'
          }
        },
        // 变更原因
        {
          title: this.$t('base.info.change-reason'),
          dataIndex: 'changeReason',
          width: 100,
          align: 'center',
          ellipsis: true,
          scopedSlots: {
            customRender: 'changeReason'
          }
        },
        // 操作
        {
          title: this.$t('global-constant.operation'),
          dataIndex: 'action',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'action'},
          ellipsis: true
        }
      ],
      tableData: [],
      tableDataLength: 0,
      tableHeight: window.innerHeight - 360 + 'px',
      tableHeightValue: window.innerHeight - 418,
      // 表格总宽度
      tableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
      testId: undefined,
      /** 提交审批：标题 */
      submitApprovalTitle: '',
      /** 提交审批：开关 */
      submitApprovalVisible: false,
      // 部门id
      departmentId: undefined,
    };
  },
  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.getProjectNodeList();
    this.getTestOwner();
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 360 + 'px';
      this.tableHeightValue = window.innerHeight - 418;
    };
    // 监听页面窗体大小变化
    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.submitApprovalVisible ? this.$refs.tableRefs.$el.offsetWidth : 0;
    },
    // 计算表格各列宽度总和
    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[this.tableColumns.length - 1].width = 150;
      }
    },
    // 初始化表格数据
    initTableData(val) {
      this.tableData = val;
      this.tableDataLength = val.length - 1;
    },

    /**
     * 获取项目节点下拉选项
     */
    getProjectNodeList() {
      let data = {
        dvpId: this.$store.getters.dvpId
      };
      this.$api.getProjectNodeList(data).then(res => {
        if (res.flag){
          let nodeList = res.data.dynamicConfig;
          nodeList.forEach(item => {
            let options = {
              label: item.name,
              value: item.id
            }
            this.projectNodeList.push(options);
          });
        }
      });
    },
    /**
     * 获取试验负责人下拉选项
     */
    getTestOwner() {
      let data = {
        dvpId: this.$store.getters.dvpId,
        dvpType: this.$store.getters.dvpType
      }
      //获取DVP团队成员中有编辑权限的用户
      this.$api.getDvpTeamMember(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);
          }
        }
      });
    },

    /**
     * 初始化下拉选数据
     */
    initSelectList(dvpId) {
      let data = {
        dvpId: dvpId
      };
      this.$api.initSelectList(data).then(res => {
        if (res.flag){
          let selectList = res.data;
          if (selectList && selectList.length > 0) {
            selectList.forEach(item => {
              let config = item.configOption;
              let selectData = {};
              selectData.id = item.id;
              selectData.name = item.name;
              selectData.configData = [];
              if (config && config.length > 0) {
                config.forEach(eachData => {
                  let eachOption = {};
                  eachOption.key = item.id;
                  eachOption.value = eachData.id;
                  eachOption.label = eachData.name;
                  selectData.configData.push(eachOption);
                });
              };
              this.selectDataList.push(selectData.configData);
            });
          };
          this.selectDataList = this.selectDataList.reverse();
        }
      });
    },

    /**
     * 表格插槽 输入框判断
     * return flag
     * flag = 1输入框  2数字输入框
     */
    slotInputFlag(val) {
      let flag = 0;
      switch (val) {
        case this.$t("dvp.full.vehicle.dvp.vehicle-use-description"):
          return flag = 1;
          break;
        case this.$t("plan.dvp.test-location"):
          return flag = 1;
          break;
        case this.$t("plan.dvp.description-of-the-vehicle-status"):
          return flag = 1;
          break;
        case this.$t("plan.dvp.number-of-vehicles"):
          return flag = 2;
          break;
        default:
          return flag = 3;
          break;
      }

    },

    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
      this.selectDataList = [];
    },

    /**
     * 清空单行编辑数据
     */
    reset(val) {
      val.changeDesc = undefined;
      val.changeReason = undefined;
    },

    /**
     * 整理数据 如果无变更后描述，但有变更原因，需要清除变更原因
     */
    buildData() {
      let _that = this;
      for (let i = 0; i < _that.tableDataLength; i++) {
        if (!_that.tableData[i].changeDesc && _that.tableData[i].changeReason) {
          _that.tableData[i].changeReason = "";
        }
      }
    },
    /**
     *  保存
     * @returns {boolean}
     */
    save() {
      let _that = this;
      _that.buildData();
      // 动态行数据整理
      let addTestConfig = [];
      for (let i = _that.tableDataLength; i > 9; i--) {
        if (_that.tableData[i].changeDesc) {
          let configId = undefined;
          _that.selectDataList.forEach(item => {
            item.forEach( itemKey => {
              if (_that.tableData[i].changeDesc === itemKey.value) {
                configId = itemKey.key;
              }
            });
          });
          let config = {
            configId: configId,
            id: _that.tableData[i].changeDesc,
            changeCause: _that.tableData[i].changeReason
          };
          addTestConfig.push(config);
        }
      }
      _that.tableLoading = true;
      // 请求参数整理
      let data = {
        dvpId: _that.$store.getters.dvpId,
        testId: _that.testId,
        vehicleUse: _that.tableData[0].changeDesc,
        vehicleUseCause: _that.tableData[0].changeReason,
        vehicleState: _that.tableData[2].changeDesc,
        vehicleStateCause: _that.tableData[2].changeReason,
        testType: _that.tableData[1].changeDesc || undefined,
        testTypeCause: _that.tableData[1].changeReason,
        vehicleCountCause: _that.tableData[3].changeReason,
        vehicleCount: _that.tableData[3].changeDesc || undefined,
        testSite: _that.tableData[4].changeDesc,
        testSiteCause: _that.tableData[4].changeReason,
        engineerUserCause: _that.tableData[5].changeReason,
        engineerUserId: _that.tableData[5].changeDesc,
        projectNodeId: _that.tableData[6].changeDesc,
        projectNodeCause: _that.tableData[6].changeReason,
        prototypePlanTime: _that.tableData[7].changeDesc,
        prototypePlanTimeCause: _that.tableData[7].changeReason,
        planStartTime: _that.tableData[8].changeDesc,
        planStartTimeCause: _that.tableData[8].changeReason,
        planEndTime: _that.tableData[9].changeDesc,
        planEndTimeCause: _that.tableData[9].changeReason,
        addTestConfig: addTestConfig.length > 0 ? addTestConfig : undefined,
      };
      // 打开审批弹框
      _that.submitApprovalTitle = _that.$t('global-btn.apply-for-changes') + _that.$t("global-btn.submit-approval");
      _that.$refs.submitApproval.inputArgs.dvpId = _that.$store.getters.dvpId;
      _that.$refs.submitApproval.inputArgs.testId = _that.testId;
      _that.$refs.submitApproval.inputArgs.dvpType = '0';
      _that.$refs.submitApproval.inputArgs.departmentId = _that.$store.getters.ownerDepartmentId;
      _that.$refs.submitApproval.inputArgs.approveType = '52';
      _that.$refs.submitApproval.inputArgs.data = data;
      _that.$refs.submitApproval.inputArgs.delayFlag = false;
      _that.submitApprovalVisible = true;

    },

    /**
     * 样车提供时间 时间选择器Change方法
     */
    handlePlanTime(date, dateString) {
      if (!dateString) {
        this.tableData[7].changeDesc = "";
        return;
      }
      this.tableData[7].changeDesc = dateString;
    },

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

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

    },

    /**
     * 计划开始时间 时间选择器Change方法
     */
    handleStartTime(date, dateString) {
      if (!dateString) {
        this.tableData[8].changeDesc = "";
        return;
      }
      this.tableData[8].changeDesc = dateString;
      // 当选择的开始时间大于结束时间时，清空结束时间，让用户重新选择结束时间
      if (Date.parse(this.tableData[8].changeDesc) > Date.parse(this.tableData[9].changeDesc)) {
        this.tableData[9].changeDesc = undefined;
      }
    },
    /**
     * 计划结束时间 时间选择器Change方法
     */
    handleEndTime(date, dateString) {
      if (!dateString) {
        this.tableData[9].changeDesc = "";
        return;
      }
      this.tableData[9].changeDesc = dateString;
    },
  }
};
</script>
<style lang='less' scoped>
.text-right {
  text-align: right;
}

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