<template>
  <div>
    <a-form>
      <a-row :gutter="24">
        <!--零部件编号-->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('workbench.compoment-number')" required>
            <a-select v-model="editParam.partCode" @change="handlePartCodeSelect" :filter-option="handleFilterDataList" mode="multiple" allowClear :placeholder="$t('global-btn.please-select') + $t('workbench.compoment-number')">
              <a-select-option
                v-for='item in partCodeList'
                :key='item.id'
                :value='item.partId'
              >
                {{ item.partCode }}
              </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('workbench.compoment-name')" required>
            <a-select v-model="editParam.partName"  @change="handlePartNameSelect" :filter-option="handleFilterDataList" mode="multiple" allowClear :placeholder="$t('global-btn.please-select') + $t('workbench.compoment-name')">
              <a-select-option
                v-for='item in partNameList'
                :key='item.id'
                :value='item.partId'
              >
                {{ item.partName }}
              </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.test-type')" required>
            <a-select v-model="editParam.testType" :options="testTypeList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('plan.dvp.please_select-test-type')"></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.test-source')" required>
            <a-select v-model="editParam.testSource" :options="testSourceList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('global-btn.please-select') + $t('plan.dvp.test-source')"></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.test-project')" required>
            <a-input v-model.trim="editParam.testProject" :maxLength='100' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-project')"/>
          </a-form-item>
        </a-col>
        <!--开发目标要求-->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('base.info.development-objective-requirements')" required>
            <a-input v-model.trim="editParam.targetRequire" :maxLength='100' allowClear :placeholder="$t('global-btn.please-enter') + $t('base.info.development-objective-requirements')"/>
          </a-form-item>
        </a-col>
        <!--试验标准-->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('base.info.Test-standards')" required>
            <a-input v-model.trim="editParam.testStandard" :maxLength='500' allowClear :placeholder="$t('global-btn.please-enter') + $t('base.info.Test-standards')"/>
          </a-form-item>
        </a-col>
        <!--等效/非等效-->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('plan.dvp.is-it-an-equivalent-test')">
            <a-radio-group v-model="editParam.isEquivalent" @change="handleEquivalent">
              <a-radio :value="0">
                {{$t('plan.dvp.non-equivalent-experiment') }}
              </a-radio>
              <a-radio :value="1">
                {{ $t('plan.dvp.equivalent-experiment') }}
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <span v-show="editParam.isEquivalent === 0">
          <!--测试地点-->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('plan.dvp.test-site')" required>
              <a-input v-model.trim="editParam.testSite" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-site')"/>
            </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-user')" required>
              <a-select v-model="editParam.testOwner" :options="testOwnerList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('global-btn.please-select') + $t('plan.dvp.test-user')"></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.test-step')" required>
              <a-input v-model.trim="editParam.testStep" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-step')"/>
            </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-count')" required>
              <a-input-number v-model.number="editParam.testFrequency" :defaultValue="0" :min="1" :max="999" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-count')" style="width: 100%"></a-input-number>
            </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')" required>
              <a-input-number v-model.number="editParam.sampleNumber" :defaultValue="0" :min="1" :max="999" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.number-of-samples')" style="width: 100%"></a-input-number>
            </a-form-item>
          </a-col>
          <!--样件类型-->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('plan.dvp.sample-type')" required>
              <a-input v-model.trim="editParam.sampleType" :maxLength='50' allowClear :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.sample-type')"/>
            </a-form-item>
          </a-col>
          <!--计划开始时间-->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('plan.dvp.scheduled-start-time')" required>
               <a-date-picker v-model="editParam.planStartTime" :disabled-date="disabledStartDate" @change="handleEditStartTime" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.scheduled-start-time')" allowClear valueFormat="YYYY/MM/DD" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <!--计划结束时间-->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('plan.dvp.scheduled-end-time')" required>
               <a-date-picker v-model="editParam.planEndTime" :disabled-date="disabledEndDate" @change="handleEditEndTime" :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.scheduled-end-time')"  allowClear valueFormat="YYYY/MM/DD" style="width: 100%" />
            </a-form-item>
          </a-col>
        </span>
        <span v-show="editParam.isEquivalent === 1">
          <!--等效实验报告编号-->
          <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
            <a-form-item :label="$t('plan.dvp.equivalent-experiment-report-number')" required>
              <a-select v-model="editParam.equivalentId" :options="equivalentList" :filter-option="handleFilterDataList" allowClear :placeholder="$t('global-btn.please-select') + $t('plan.dvp.equivalent-experiment-report-number')"></a-select>
            </a-form-item>
          </a-col>
        </span>
        <!--是否推送至零部件模板-->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('plan.dvp.whether-to-push-to-component-template')">
            <a-checkbox :checked="checked" @change="handlePushTemplate">
              {{ $t('plan.dvp.push-to-component-DVP-template') }}
            </a-checkbox>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>


<script>


import moment from "moment";

export default {
  data() {
    return {
      /** 编辑数据 */
      editParam: {
        isEquivalent: 0
      },
      /** 零部件编号/名称下拉选项 */
      partCodeList: [],
      /** 级联 用的零部件名称下拉选项 */
      partNameList: [],
      /** 零部件编号、零部件名称当清空其中某一下拉选框的选中数据时，恢复最初的下拉选数据*/
      standByList: [],
      /** 试验类型下拉选项 */
      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')
        }
      ],
      /** 试验负责人下拉选项 */
      testOwnerList: [],
      /** 等效实验报告编号下拉选项 */
      equivalentList: [],
      /** 是否推送 是否勾选 */
      checked: false
    }
  },
  mounted() {
    this.initSelectData();
  },
  methods: {

    /**
     * 初始化下拉数据
     */
    initSelectData() {
      this.equivalentList = [];
      this.testOwnerList = [];
      let data = {
        dvpId: this.$store.getters.dvpId
      };
      this.$api.getPartList(data).then( res => {
        if (res.flag) {
          let partList = res.data.partList;
          this.partCodeList = partList;
          this.partNameList = partList;
          this.standByList = partList;
          // 等效报告 下拉选项
          let reportList = res.data.equivalentTestList;
          reportList.forEach(item => {
            let reportOptions = {
              label: item.reportCode,
              value: item.id
            }
            this.equivalentList.push(reportOptions);
          });
        }
      });

      // 获取团队成员 用于测试负责人下拉选
      this.$api.getDvpTeamMember({dvpId: this.$store.getters.dvpId,dvpType: this.$store.getters.dvpType}).then(res => {
        if (res.flag) {
          let userList = res.data.teamMemberModels;
          let engineerList = res.data.engineerModels;
          userList.forEach(item => {
            if (item.permission === 1){
              let options = {
                label: item.name,
                value: item.userId
              };
              this.testOwnerList.push(options);
            }
          });
          // 工程师数据处理
          engineerList.forEach(data => {
            let index = this.testOwnerList.findIndex(item => item.value === data.userId);
            if (index === -1) {
              let tempData = {
                label: data.name,
                value: data.userId
              };
              this.testOwnerList.push(tempData);
            }
          });
          // 是否包含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);
          }
        }
      });
    },

    /**
     * 零部件编号级联下拉选择
     * @param val
     * @param options
     */
    handlePartCodeSelect(val, options) {
      if (options && options.length > 0) {
        this.partNameList = [];
        this.editParam.partName = [];
        options.forEach( item => {
          this.partCodeList.forEach( partCode => {
            // 将选中的零部件编号对应的零部件名称放入零部件名称下拉选list和已选中的零部件名称list中
            if (partCode.id === item.data.key) {
              this.partNameList.push(partCode)
              this.editParam.partName.push(partCode.partId);
            }
          });
        });
      } else {
        this.partNameList = this.standByList;
        this.partCodeList = this.standByList;
        this.editParam.partName = [];
      }
    },

    /**
     * 零部件名称级联下拉选择 同上 零部件编号级联
     * @param val
     * @param options
     */
    handlePartNameSelect(val, options) {
      if (options && options.length > 0) {
        this.partCodeList = [];
        this.editParam.partCode = [];
        options.forEach( item => {
          this.partNameList.forEach( partName => {
            if (partName.id === item.data.key) {
              this.partCodeList.push(partName)
              this.editParam.partCode.push(partName.partId);
            }
          });
        });
      } else {
        this.partNameList = this.standByList;
        this.partCodeList = this.standByList;
        this.editParam.partCode = [];
      }
    },

		/**
		 * 非空校验 判断是否为空
		 * @returns {boolean}
		 */
		isNull() {
			let _that = this;
			let message = [];
      // 零部件编号
			if (!_that.editParam.partCode || this.editParam.partCode.length === 0) {
				message.push(_that.$t('global-btn.please-select') + _that.$t('workbench.compoment-number'));
			}
      // 零部件名称
			if (!_that.editParam.partName) {
				message.push(_that.$t('global-btn.please-select') + _that.$t('workbench.compoment-name'));
			}
      // 试验类型
			if (!_that.editParam.testType) {
				message.push(_that.$t('plan.dvp.please_select-test-type'));
			}
      // 试验来源
			if (!_that.editParam.testSource) {
				message.push(_that.$t('global-btn.please-select') + _that.$t('plan.dvp.test-source'));
			}
      // 试验项目
			if (!_that.editParam.testProject) {
				message.push(_that.$t('global-btn.please-enter') + _that.$t('plan.dvp.test-project'));
			}
      // 开发目标要求
			if (!_that.editParam.targetRequire) {
				message.push(_that.$t('global-btn.please-enter') + _that.$t('base.info.development-objective-requirements'));
			}
      // 试验标准
			if (!_that.editParam.testStandard) {
				message.push(_that.$t('global-btn.please-enter') + _that.$t('base.info.Test-standards'));
			}
      // 非等效试验时校验以下数据
      if (_that.editParam.isEquivalent === 0) {
        // 测试地点
        if (!_that.editParam.testSite) {
          message.push(_that.$t('global-btn.please-enter') + _that.$t('plan.dvp.test-site'));
        }
        // 测试负责人
        if (!_that.editParam.testOwner) {
          message.push(_that.$t('global-btn.please-select') + _that.$t('plan.dvp.test-user'));
        }
        // 测试阶段
        if (!_that.editParam.testStep) {
          message.push(_that.$t('global-btn.please-enter') + _that.$t('plan.dvp.test-step'));
        }
        // 测试次数
        if (!_that.editParam.testFrequency) {
          message.push(_that.$t('global-btn.please-enter') + _that.$t('plan.dvp.test-count'));
        }
        // 样本数量
        if (!_that.editParam.sampleNumber) {
          message.push(_that.$t('global-btn.please-enter') + _that.$t('plan.dvp.number-of-samples'));
        }
        // 样件类型
        if (!_that.editParam.sampleType) {
          message.push(_that.$t('global-btn.please-enter') + _that.$t('plan.dvp.sample-type'));
        }
        // 计划开始时间
        if (!_that.editParam.planStartTime) {
          message.push(_that.$t('global-btn.please-select') + _that.$t('plan.dvp.scheduled-start-time'));
        }
        // 计划结束时间
        if (!_that.editParam.planEndTime) {
          message.push(_that.$t('global-btn.please-select') + _that.$t('plan.dvp.scheduled-end-time'));
        }
      } else {
        // 等效实现时校验
        // 等效试验报告编号
        if (!_that.editParam.equivalentId) {
          message.push(_that.$t('global-btn.please-select') + _that.$t('plan.dvp.equivalent-experiment-report-number'));
        }
        _that.editParam.testSite = null;
        _that.editParam.testOwner = null;
        _that.editParam.testStep = null;
        _that.editParam.testFrequency = null;
        _that.editParam.sampleNumber = null;
        _that.editParam.sampleType = null;
        _that.editParam.planStartTime = null;
        _that.editParam.planEndTime = null;
      }
			if (message && message.length > 0) {
				for (let i = 0; i < message.length; i++) {
					_that.$notification.warning({message: message[i]});
				}
				return false;
			}
			return true;
		},

    /**
     * 保存
     */
    saveDvpEdit() {
      // 非空校验
      if (!this.isNull()) {
				return false;
			}
      // 零部件编号处理
      let partCodeList = [];
      if (this.editParam.partCode && this.editParam.partCode.length > 0) {
        this.editParam.partCode.forEach(item => {
          let obj = this.partCodeList.find(val => { return val.id === item})?.partCode;
          partCodeList.push(obj);
        });
      }
      let data = {
        dvpId: this.$store.getters.dvpId,
        partCodeList: partCodeList,
        partIds: this.editParam.partCode,
        testType: this.editParam.testType,
        testSource: this.editParam.testSource,
        testProject: this.editParam.testProject,
        targetRequire: this.editParam.targetRequire,
        testStandard: this.editParam.testStandard,
        equivalentId: this.editParam.equivalentId,
        testSite: this.editParam.testSite,
        testUserId: this.editParam.testOwner,
        testStep: this.editParam.testStep,
        testFrequency: this.editParam.testFrequency,
        sampleNumber: this.editParam.sampleNumber,
        sampleType: this.editParam.sampleType,
        planStartTime: this.editParam.planStartTime,
        planEndTime: this.editParam.planEndTime,
        isPush: this.editParam.isPushTemplate
      };
      this.$api.planTestAdd(data).then(res => {
        if (res.flag) {
          this.$message.success(res.message);
          this.$emit("initData");
          this.$emit("cancelEditDvp");
        } else {
          this.$message.error(res.message);
        }
      });
    },

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

    /**
     * 等效/非等效
     * @param e
     */
    handleEquivalent(e) {
      this.editParam.isEquivalent = e.target.value;
      // 以下写法，会导致频繁切换后，输入不了数据
      // 如果选择了非等效,清除等效报告ID
      // if (this.editParam.isEquivalent === 0) {
      //   this.editParam.equivalentId = undefined;
      // }
      // else if (this.editParam.isEquivalent === 1) {  // 如果选择了等效,清除测试地点、测试负责人、测试阶段、测试次数、计划开始时间、计划结束时间
      //
      // }
    },

    /**
     * 是否推送至零部件模板
     * @param e
     */
    handlePushTemplate(e) {
      if (e.target.checked) {
        this.editParam.isPushTemplate = 0;
        this.checked = true;
      } else {
        this.editParam.isPushTemplate = undefined;
        this.checked = false;
      }
    },

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

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

    /**
     * 计划开始时间 时间选择器Change方法 编辑
     */
    handleEditStartTime(date, dateString){
      if (!dateString) {
        this.editParam.planStartTime = "";
        return;
      }
      this.editParam.planStartTime = dateString;
      // 当选择的开始时间大于结束时间时，清空结束时间，让用户重新选择结束时间
      if (Date.parse(this.editParam.planStartTime) > Date.parse(this.editParam.planEndTime)) {
        this.editParam.planEndTime = undefined;
      }
    },
    /**
     * 计划结束时间 时间选择器Change方法 编辑
     */
    handleEditEndTime(date, dateString) {
      if (!dateString) {
        this.editParam.planEndTime = "";
        return;
      }
      this.editParam.planEndTime = dateString;
    }
  }
}

</script>

<style lang="less" scoped>

</style>
