<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 - 120 }'
          size="small"
          bordered
          :components='components'
        >
          <!-- 系统DVP 变更后描述-->
          <template slot='changeDesc' slot-scope='text, record, index'>
            <!-- 是否开展试验 -->
            <a-select v-if="index === 0" v-model="record.changeDesc" style="width: 100%" @change="handleCarryOut" allowClear :placeholder="$t('base.info.please-enter-whether-to-develop-experimental-projects')">
              <a-select-option :value="1">{{ $t('global-btn.yes') }}</a-select-option>
              <a-select-option :value="0">{{ $t('global-btn.no') }}</a-select-option>
            </a-select>
            <!-- 试验负责人 -->
            <a-select v-if="index === 1" v-model="record.changeDesc" :options="testOwnerList" :disabled="!causeShowFlag" allowClear style="width: 100%" :placeholder="$t('plan.dvp.please_select-study-director')"></a-select>
            <!-- 试验资质 -->
            <a-select v-else-if="index === 2" v-model="record.changeDesc" :disabled="!causeShowFlag" style="width: 100%" :placeholder="$t('plan.dvp.please-enter-test-qualification')" allowClear>
              <a-select-option :value="1">{{ $t('global-btn.yes') }}</a-select-option>
              <a-select-option :value="0">{{ $t('global-btn.no') }}</a-select-option>
            </a-select>
            <!-- 试验地点 -->
            <a-input v-else-if="index === 3" v-model.trim="record.changeDesc" :disabled="!causeShowFlag" :placeholder="$t('global-constant.please-enter')"></a-input>
            <!-- 试验阶段 -->
            <a-select v-else-if="index === 4" v-model="record.changeDesc" :options="testStageList" :disabled="!causeShowFlag" allowClear style="width: 100%" :placeholder="$t('plan.dvp.please-enter-test-stage')"/>
            <!-- 试验频次 -->
            <a-select v-else-if="index === 5" v-model="record.changeDesc" :options="frequencyList" :disabled="!causeShowFlag" allowClear style="width: 100%" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-frequency')"/>
            <!-- 样件类型 -->
            <a-select v-else-if="index === 6" v-model="record.changeDesc" :options="sampleTypeList" :disabled="!causeShowFlag" allowClear style="width: 100%" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.sample-type')"/>
            <!-- 样本数量 -->
            <a-select v-else-if="index === 7" v-model="record.changeDesc" :options="countList" :disabled="!causeShowFlag" allowClear style="width: 100%" :placeholder="$t('plan.dvp.please_select-number-of-vehicles')"/>
            <!-- 计划开始时间 -->
            <a-date-picker v-else-if="index === 8" :disabled-date="disabledStartDate" @change='handleStartTime' v-model="record.changeDesc" :disabled="!causeShowFlag" :placeholder="$t('plan.dvp.please_select-scheduled-start-time')" style="width: 100%" valueFormat="YYYY/MM/DD"/>
            <!-- 计划结束时间 -->
            <a-date-picker v-else-if="index === 9"  :disabled-date="disabledEndDate" @change='handleEndTime' v-model="record.changeDesc" :disabled="!causeShowFlag || testSource === 1" :placeholder="$t('plan.dvp.please_select-scheduled-end-time')" style="width: 100%" valueFormat="YYYY/MM/DD"/>
            <!-- 不开展试验原因 -->
            <a-textarea v-if="index === 10" autoSize v-model.trim="record.changeDesc" :disabled="causeShowFlag" :maxLength="500" :placeholder="$t('base.info.please-enter-change-reason')"></a-textarea>
          </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: []
    },

    dvpType: {
      type: String,
      default: undefined
    }

  },

  data() {
    this.components = {
			header: {
				cell: (h, props, children) => {
					const { key, ...restProps } = props;
					// 此处的this.columns 是定义的table的表头属性变量
					const col = this.tableColumns.find((col) => {
						const k = col.dataIndex || col.key;
						return k === key;
					});
					if (!col || !col.width) {
						return h('th', { ...restProps }, [...children]);
					}
					const dragProps = {
						key: col.dataIndex || col.key,
						class: 'table-draggable-handle',
						attrs: {
							w: 10,
							x: col.width,
							z: 1,
							axis: 'x',
							draggable: true,
							resizable: false
						},
						on: {
							dragging: (x, y) => {
								col.width = Math.max(x, 90);
							}
						}
					};
					const drag = h('vue-draggable-resizable', { ...dragProps });
					return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
				}
			}
		};
    return {
      /**试验负责人*/
      testOwnerList: [],
      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
        }
      ],
      /** 样件类型下拉选 */
      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'
        }
      ],
      /** 试验频次下拉选 */
      frequencyList: [
        {
          label: 1,
          value: 1
        },
        {
          label: 2,
          value: 2
        },
        {
          label: 3,
          value: 3
        },
        {
          label: 4,
          value: 4
        },
        {
          label: 5,
          value: 5
        }
      ],
      /** 样件数量下拉选 */
      countList: [
        {
          label: 1,
          value: 1
        },
        {
          label: 2,
          value: 2
        },
        {
          label: 3,
          value: 3
        },
        {
          label: 4,
          value: 4
        },
        {
          label: 5,
          value: 5
        },
        {
          label: 6,
          value: 6
        },
        {
          label: 7,
          value: 7
        },
        {
          label: 8,
          value: 8
        },
        {
          label: 9,
          value: 9
        }
      ],
      /** 试验阶段下拉选项 */
      testStageList: [],
      tableData: [],
      tableDataLength: 0,
      tableHeight: window.innerHeight - 360 + 'px',
      tableHeightValue: window.innerHeight - 480,
      testId: undefined,
      /** 提交审批：标题 */
      submitApprovalTitle: '',
      /** 提交审批：开关 */
      submitApprovalVisible: false,
      // 部门id
      departmentId: undefined,
      // 是否显示不展开试验原因
      causeShowFlag: false,
      // 表格总宽度
      tableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
      testSource: undefined
    };
  },
  watch: {
    tableColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
        });
      },
      deep: true,
      immediate: true
    },
    tableWidth:{
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
        });

      },
      deep: true,
      immediate: true
    }
  },

  mounted() {
    this.getTestOwner();
    this.getProjectNodeList();
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 360 + 'px';
      this.tableHeightValue = window.innerHeight - 480;
    };
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
  },
  //剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 获取表格的总宽度
    handleResize() {
      this.tableWidth = this.causeShowFlag ? 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 = 100;
      }
    },
    /**
     * 初始化表格数据
     * @param val
     */
    initTableData(val) {
      this.tableData = val;
      this.tableDataLength = val.length - 1;
    },

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


    /**
     * 获取试验负责人下拉选项
     */
    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);
          }
        }
      });
    },

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

    /**
     * 清空单行编辑数据
     */
    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 data = {
        dvpId: _that.$store.getters.dvpId,
        testId: _that.testId,
        isCarryOut: _that.tableData[0].changeDesc,
        isCarryOutCause: _that.tableData[0].changeReason,
        testCertification: _that.tableData[2].changeDesc,
        testCertificationCause: _that.tableData[2].changeReason,
        testOwnerId: _that.tableData[1].changeDesc,
        testOwnerIdCause: _that.tableData[1].changeReason,
        testSite: _that.tableData[3].changeDesc,
        testSiteCause: _that.tableData[3].changeReason,
        testStage: _that.tableData[4].changeDesc,
        testStageCause: _that.tableData[4].changeReason,
        testFrequency: _that.tableData[5].changeDesc,
        testFrequencyCause: _that.tableData[5].changeReason,
        count: _that.tableData[7].changeDesc,
        countCause: _that.tableData[7].changeReason,
        sampleType: _that.tableData[6].changeDesc,
        sampleTypeCause: _that.tableData[6].changeReason,
        planStartTime: _that.tableData[8].changeDesc,
        planStartTimeCause: _that.tableData[8].changeReason,
        planEndTime: _that.tableData[9].changeDesc,
        planEndTimeCause: _that.tableData[9].changeReason,
        notCarryOutCause: _that.tableData[10].changeDesc,
        notCarryOutCauseChange: _that.tableData[10].changeReason
      };
      // 打开审批弹框
      _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.dvpType = '1';
      _that.$refs.submitApproval.inputArgs.departmentId = _that.$store.getters.ownerDepartmentId;
      _that.$refs.submitApproval.inputArgs.testId = _that.testId;
      _that.$refs.submitApproval.inputArgs.approveType = '57';
      _that.$refs.submitApproval.inputArgs.data = data;
      _that.$refs.submitApproval.inputArgs.delayFlag = false;
      _that.submitApprovalVisible = true;
    },

    /**
     * 是否开展实验项目 编辑
     * @param val
     */
    handleCarryOut(val){
      this.tableData[0].changeDesc = val;
      // 当是否展开试验选择“否”时,其他输入和选择都置灰
      if (val === 0) {
        this.causeShowFlag = false;
      } else {
        this.causeShowFlag = true;
      }
      this.$forceUpdate();
    },


    /**
     * 开始时间不能选择当天
     * @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;
    },

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