<template>
  <div>
    <a-modal
      :title=" $t('global-btn.apply-for-changes')"
      :visible="applyFlag"
      :width="1000"
      @ok="save"
      @cancel="closeModal"
      :footer="null"
    >
      <div>
        <a-table
          :columns='tableColumns'
          :dataSource='tableData'
          :pagination='false'
          :rowKey='(record, index) => { return index; }'
          :scroll='{ x: 800, y: tableHeightValue }'
          size="small"
        >
          <!-- 零部件DVP 变更后描述-->
          <template slot='changeDesc' slot-scope='text, record, index'>
            <!--试验类型-->
            <a-select v-if="index === 0" v-model="record.changeDesc" :options="testTypeList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('plan.dvp.please_select-test-type')" style="width: 100%"></a-select>
            <!--试验来源-->
            <a-select v-else-if="index === 1" v-model="record.changeDesc" :options="testSourceList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('global-btn.please-select') + $t('plan.dvp.test-source')" style="width: 100%"></a-select>
            <!--试验项目-->
            <a-input v-else-if="index === 2" v-model.trim="record.changeDesc" :maxLength='128' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-project')"/>
            <!--开发目标要求-->
            <a-input v-else-if="index === 3" v-model.trim="record.changeDesc" :maxLength='500' allowClear :placeholder="$t('global-btn.please-enter') + $t('base.info.development-objective-requirements')"/>
            <!--试验标准-->
            <a-input v-else-if="index === 4" v-model.trim="record.changeDesc" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('base.info.Test-standards')"/>
            <!--等效实验报告编号-->
            <a-select v-else-if="index === 5" v-model="record.changeDesc" :options="equivalentList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('global-btn.please-select') + $t('plan.dvp.equivalent-experiment-report-number')" style="width: 100%"></a-select>
            <!--测试地点-->
            <a-input v-else-if="index === 6" v-model.trim="record.changeDesc" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-site')"/>
            <!--测试负责人 -->
            <a-select v-if="index === 7" v-model="record.changeDesc" :options="testOwnerList"  allowClear style="width: 100%" :placeholder="$t('global-btn.please-select') + $t('plan.dvp.test-user')" ></a-select>
            <!--计划开始时间 -->
            <a-date-picker v-else-if="index === 8" :disabled-date="disabledStartDate" @change='handleStartTime' v-model="record.changeDesc" :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" :placeholder="$t('plan.dvp.please_select-scheduled-end-time')" style="width: 100%" valueFormat="YYYY/MM/DD"/>
            <!--测试阶段-->
            <a-input v-else-if="index === 10" v-model.trim="record.changeDesc" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-step')"/>
            <!--测试次数-->
            <a-input-number v-else-if="index === 11" v-model.number="record.changeDesc" :defaultValue="0" :min="1" :max="999" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-count')" style="width: 100%"></a-input-number>
            <!--样件类型-->
            <a-input v-else-if="index === 12" v-model.trim="record.changeDesc" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.sample-type')"/>
            <!--样本数量-->
            <a-input-number v-else-if="index === 13" v-model.number="record.changeDesc" :defaultValue="0" :min="1" :max="999" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.number-of-samples')" style="width: 100%"></a-input-number>
          </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";

export default {
  name: "AddDvpTest",
  components: {
    SubmitApproval
  },
  props: {

    applyFlag: {
      type: Boolean,
      default: false
    },

    applyTableData: {
      type: Array,
      default: []
    },

    dvpType: {
      type: String,
      default: undefined
    }

  },

  data() {
    return {
      /**试验负责人*/
      testOwnerList: [],
      tableColumns: [
        // 变更内容
        {
          title: this.$t('base.info.change-content'),
          dataIndex: 'changeContent',
          align: 'center',
          ellipsis: true
        },
        // 当前描述
        {
          title: this.$t('base.info.current-description'),
          dataIndex: 'currentDesc',
          align: 'center',
          ellipsis: true
        },
        // 变更后描述
        {
          title: this.$t('base.info.description-after-change'),
          dataIndex: 'changeDesc',
          align: 'center',
          ellipsis: true,
          scopedSlots: {
            customRender: 'changeDesc'
          }
        },
        // 变更原因
        {
          title: this.$t('base.info.change-reason'),
          dataIndex: 'changeReason',
          align: 'center',
          ellipsis: true,
          scopedSlots: {
            customRender: 'changeReason'
          }
        },
        // 操作
        {
          title: this.$t('global-constant.operation'),
          align: 'center',
          width: 80,
          scopedSlots: { customRender: 'action'},
          ellipsis: true
        }
      ],
      tableData: [],
      tableDataLength: 0,
      tableHeight: window.innerHeight - 360 + 'px',
      tableHeightValue: window.innerHeight - 418,
      testId: undefined,
      /** 提交审批：标题 */
      submitApprovalTitle: '',
      /** 提交审批：开关 */
      submitApprovalVisible: false,
      // 部门id
      departmentId: undefined,
      // 是否显示不展开试验原因
      causeShowFlag: false,
      /** 试验类型下拉选项 */
      testTypeList: [
        {
          value: '1',
          label: this.$t('dvp.appearance')
        },
        {
          value: '2',
          label: this.$t('dvp.size')
        },
        {
          value: '3',
          label: this.$t('dvp.material-regulations')
        },
        {
          value: '4',
          label: this.$t('dvp.performance-and-functionality')
        }
      ],
      /** 试验来源下拉选项 */
      testSourceList: [
        {
          value: '1',
          label: this.$t('dvp.drawing')
        },
        {
          value:  '2',
          label: this.$t('dvp.KPC')
        },
        {
          value: '3',
          label: this.$t('dvp.web-require')
        },
        {
          value: '4',
          label: this.$t('dvp.standard')
        },
        {
          value: '5',
          label: this.$t('dvp.laws-and-regulations')
        }
      ],
      /** 等效实验报告编号下拉选项 */
      equivalentList: []
    };
  },

  mounted() {
    this.getTestOwner();
    this.getReportCodeList();
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 360 + 'px';
      this.tableHeightValue = window.innerHeight - 418;
    };
  },
  methods: {

    /**
     * 初始化表格数据
     * @param val
     */
    initTableData(val) {
      this.tableData = val;
      this.tableDataLength = val.length - 1;
    },

    /**
     * 获取等效试验报告下拉选
     */
    getReportCodeList() {
      // 获取等效报告下拉选
      let data = {
        dvpId: this.$store.getters.dvpId
      };
      this.$api.getPartList(data).then( res => {
        if (res.flag) {
          // 等效报告 下拉选项
          let reportList = res.data.equivalentTestList;
          reportList.forEach(item => {
            let reportOptions = {
              label: item.reportCode,
              value: item.id
            }
            this.equivalentList.push(reportOptions);
          });
        }
      });
    },

    /**
     * 获取试验负责人下拉选项
     */
    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,
        testType: _that.tableData[0].changeDesc,
        testTypeCause: _that.tableData[0].changeReason,
        testSource: _that.tableData[1].changeDesc,
        testSourceCause: _that.tableData[1].changeReason,
        equivalentId: _that.tableData[5].changeDesc,
        equivalentIdCause: _that.tableData[5].changeReason,
        testProject: _that.tableData[2].changeDesc,
        testProjectCause: _that.tableData[2].changeReason,
        targetRequire: _that.tableData[3].changeDesc,
        targetRequireCause: _that.tableData[3].changeReason,
        testStandard: _that.tableData[4].changeDesc,
        testStandardCause: _that.tableData[4].changeReason,
        testSite: _that.tableData[6].changeDesc,
        testSiteCause: _that.tableData[6].changeReason,
        testUserId: _that.tableData[7].changeDesc,
        testUserIdCause: _that.tableData[7].changeReason,
        testStep: _that.tableData[10].changeDesc,
        testStepCause: _that.tableData[10].changeReason,
        testFrequency: _that.tableData[11].changeDesc,
        testFrequencyCause: _that.tableData[11].changeReason,
        sampleNumber: _that.tableData[13].changeDesc,
        sampleNumberCause: _that.tableData[13].changeReason,
        sampleType: _that.tableData[12].changeDesc,
        sampleTypeCause: _that.tableData[12].changeReason,
        planStartTime: _that.tableData[8].changeDesc,
        planStartTimeCause: _that.tableData[8].changeReason,
        planEndTime: _that.tableData[9].changeDesc,
        planEndTimeCause: _that.tableData[9].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 = '2';
      _that.$refs.submitApproval.inputArgs.departmentId = _that.$store.getters.ownerDepartmentId;
      _that.$refs.submitApproval.inputArgs.testId = _that.testId;
      _that.$refs.submitApproval.inputArgs.approveType = '23';
      _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) {
      return current && current < moment(this.tableData[8].changeDesc).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;
}
</style>
