<template>
  <a-modal v-model="isBatchEdit" :title="$t('header.dvp-verify')" @ok="save" @cancel="closeModal" :width="1000" :maskClosable="false">
    <a-form>
      <!-- 第一行 -->
      <a-row :gutter="24">
        <!-- 零部件编号 -->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('verity.dvp.part.number')" required>
            <a-select v-model="formData.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('verity.dvp.part.name')" required>
            <a-select v-model.trim="formData.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-row>
      <!-- 第二行 -->
      <a-row :gutter="24">
        <!-- FND代码 -->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('verity.dvp.fnd.code')" required>
            <a-select v-model="formData.fndCode" @change="handleFndSelect" :filter-option="handleFilterDataList" mode="multiple" allowClear :placeholder="$t('global-btn.please-select') + $t('verity.dvp.fnd.code')">
              <a-select-option
                v-for='item in fndList'
                :key='item.id'
                :value='item.fndId'
              >
                {{ item.fndCode }}
              </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('verity.dvp.test.project')" required>
            <a-select v-model="formData.testProject" @change="handleTestProjectSelect" :filter-option="handleFilterDataList" mode="multiple" allowClear :placeholder="$t('global-btn.please-select') + $t('verity.dvp.test.project')">
              <a-select-option
                v-for='item in testProjectList'
                :key='item.testId'
                :value='item.testId'
              >
                {{ item.testProject }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第三行 -->
      <a-row :gutter="24">
        <!-- 测试开始日期 -->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('verity.dvp.test.start.date')" required>
            <a-date-picker
              :placeholder="$t('global-btn.please-select') + $t('verity.dvp.test.start.date')"
              class="width100"
              valueFormat="YYYY-MM-DD"
              @change='changeStartTime'
              v-model="formData.testStartTime"
            />
          </a-form-item>
        </a-col>
        <!-- 测试结束日期 -->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('verity.dvp.test.end.date')" required>
            <a-date-picker
              :placeholder="$t('global-btn.please-select') + $t('verity.dvp.test.end.date')"
              class="width100"
              valueFormat="YYYY-MM-DD"
              @change='changeEndTime'
              v-model="formData.testEndTime"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第四行 -->
      <a-row :gutter="24">
        <!-- 是否通过 -->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('verity.dvp.is.pass')" required>
            <a-select
              v-model="formData.isPass"
              :placeholder="$t('global-btn.please-select') + $t('verity.dvp.is.pass')">
              <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-form-item>
        </a-col>
        <!-- 测试结果及分析 -->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('verity.dvp.test.result.analysis')" required>
            <a-input
              v-model.trim="formData.testResultAnalyse"
              :placeholder="$t('global-btn.please-enter') + $t('verity.dvp.test.result.analysis')"
              allowClear
              :maxLength='500'
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第五行 -->
      <a-row :gutter="24">
        <!-- 改进措施计划 -->
        <a-col v-if="formData.isPass === '0'" :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('verity.dvp.improvement.measures')" required>
            <a-input
              v-model.trim="formData.modifiedMeasure"
              :placeholder="$t('global-btn.please-enter') + $t('verity.dvp.improvement.measures')"
              allowClear
              :maxLength='500'
            />
          </a-form-item>
        </a-col>
        <!-- 试验报告编号 -->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('verity.dvp.test.report.number')" required>
            <a-input
              v-model.trim="formData.testReportCode"
              :placeholder="$t('global-btn.please-enter') + $t('verity.dvp.test.report.number')"
              allowClear
              :maxLength='100'
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第六行 -->
      <a-row :gutter="24">
        <!-- 上传试验报告 -->
        <a-col :lg="16" :md="24" :sm="24" :xl="12" :xs="24">
          <a-form-item :label="$t('global-btn.upload.test.report')" required>
            <a-upload-dragger
              name="file"
              :multiple="false"
              action=""
              :customRequest='editUploadFile'
              :remove='editRemoveFile'
              :file-list="fileList"
            >
              <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-row>
    </a-form>
  </a-modal>

</template>

<script>
export default {
  name: 'BatchEdit',
  data() {
    return {
      /** 批量编辑模态框显示/隐藏 */
      isBatchEdit: false,
      /** 表单数据 */
      formData: {
        partCode: undefined,
        partName: undefined,
        fndCode: undefined,
        testSource: undefined,
        testProject: undefined,
        testStartTime: undefined,
        testEndTime: undefined,
        isPass: undefined,
        testReportCode: undefined,
        testResultAnalyse: undefined,
        modifiedMeasure: undefined
      },
      /** 试验来源下拉选项  未确定具体字段-暂时写死*/
      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')
        }
      ],
      /** 零部件编号下拉选项 */
      partCodeList: [],
      /** 零部件名称下拉选项 */
      partNameList: [],
      /** fnd下拉选项 */
      fndList: [],
      /** 试验项目下拉选 */
      testProjectList: [],
      /** 零部件编号、零部件名称、fnd下拉选备用list，当清空其中某一下拉选框的选中数据时，恢复最初的下拉选数据*/
      standByList: [],
      /** 试验项目下拉选  清空选中时恢复最初下拉选数据用*/
      testProjectStandByList: [],
      /** 试验报告附件list */
      fileList: [],
    }
  },
  methods: {
    /**
     * 初始化下拉数据
     */
    initSelectData() {
      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;
          // 每个fnd只保留一个
          this.fndList = partList.filter((item, index) => {
            return partList.findIndex(obj => obj.fndId === item.fndId) === index;
          });
          this.testProjectList = res.data.testProjectList;
          this.testProjectStandByList = res.data.testProjectList;
        }
      });
    },

    /**
     * 关闭批量编辑模态框
     */
    closeModal() {
      this.formData = {};
      this.fileList = [];
      this.isBatchEdit = false;
    },

    /**
     * 保存批量编辑
     */
    save() {
      // 非空校验
      if (!this.isNull()) {
        return false;
      }
      let data = {
        dvpId: this.$store.getters.dvpId,
        testStartTime: this.formData.testStartTime,
        testEndTime: this.formData.testEndTime,
        isPass: this.formData.isPass,
        testReportCode: this.formData.testReportCode,
        testResultAnalyse: this.formData.testResultAnalyse,
        modifiedMeasure: this.formData.modifiedMeasure,
        testReportFileModel: this.fileList[0],
        partIds: this.formData.partCode,
        testIds: this.formData.testProject
      };
      this.$api.verifyTestBatchSave(data).then(res => {
        if (res.flag) {
          this.$emit("initData");
          this.closeModal();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    /**
     * 非空校验 判断是否为空
     * @returns {boolean}
     */
    isNull() {
      let message = [];
      if (!this.formData.partCode) {
        message.push(this.$t('global-btn.please-enter') + this.$t('verity.dvp.part.number'));
      }
      if (!this.formData.partName) {
        message.push(this.$t('global-btn.please-select') + this.$t('verity.dvp.part.name'));
      }
      if (!this.formData.testStartTime) {
        message.push(this.$t('global-btn.please-select') + this.$t('verity.dvp.test.start.date'));
      }
      if (!this.formData.testEndTime) {
        message.push(this.$t('global-btn.please-select') + this.$t('verity.dvp.test.end.date'));
      }
      if (!this.formData.isPass) {
        message.push(this.$t('global-btn.please-select') + this.$t('verity.dvp.is.pass'));
      }
      if (this.formData.isPass === '0') {
        if (!this.formData.modifiedMeasure) {
          message.push(this.$t('global-constant.please-enter') + this.$t('verity.dvp.improvement.measures'));
        }
      }
      if (!this.formData.testReportCode) {
        message.push(this.$t('global-constant.please-enter') + this.$t('verity.dvp.test.report.number'));
      }
      if (!this.formData.testResultAnalyse) {
        message.push(this.$t('global-constant.please-enter') + this.$t('verity.dvp.test.result.analysis'));
      }

      if (this.fileList.length === 0) {
        message.push(this.$t('global-btn.please-select') + this.$t('verity.dvp.test.report'));
      }
      if (message && message.length > 0) {
        for (let i = 0; i < message.length; i++) {
          this.$notification.warning({message: message[i]});
        }
        return false;
      }
      return true;
    },

    /**
     * 零部件编号级联下拉选择
     * @param val
     * @param options
     */
    handlePartCodeSelect(val, options) {
      if (options && options.length > 0) {
        this.partNameList = [];
        this.fndList = [];
        this.testProjectList = [];
        this.formData.partName = [];
        this.formData.fndCode = [];
        this.formData.testProject = [];
        options.forEach( item => {
          this.partCodeList.forEach( partCode => {
            // 将选中的零部件编号对应的零部件名称放入零部件名称下拉选list和已选中的零部件名称list中
            if (partCode.id === item.data.key) {
              this.partNameList.push(partCode)
              this.formData.partName.push(partCode.partId);
              // 将选中的零部件编号对应的fnd放入fnd下拉选list中
              if (!this.fndList.find(obj => obj.fndId === partCode.fndId)) {
                this.fndList.push(partCode);
              }
              // 将选中的零部件编号对应的试验项目放入试验项目下拉选list和已选中的试验项目list中
              this.testProjectStandByList.filter(item => item.partId === partCode.partId).forEach(obj => {
                this.testProjectList.push(obj);
                // this.formData.testProject.push(obj.testId);
              });

              // 将选中的零部件编号对应的fnd放入已选中的fndList中
              if (this.formData.fndCode.length > 0 && !this.formData.fndCode.some(obj => obj === partCode.fndId)) {
                this.formData.fndCode.push(partCode.fndId);
              } else if (this.formData.fndCode.length === 0) {
                this.formData.fndCode.push(partCode.fndId);
              }
            }
          });
        });
      } else {
        this.partNameList = this.standByList;
        this.partCodeList = this.standByList;
        this.testProjectList = this.testProjectStandByList;
        this.formData.partName = [];
        this.formData.fndCode = [];
        this.formData.testProject = [];
        this.fndList = this.standByList.filter((item, index) => {
          return this.standByList.findIndex(obj => obj.fndId === item.fndId) === index;
        });
      }
    },

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

              if (!this.fndList.find(obj => obj.fndId === partName.fndId)) {
                this.fndList.push(partName);
              }

              this.testProjectStandByList.filter(item => item.partId === partName.partId).forEach(obj => {
                this.testProjectList.push(obj);
                // this.formData.testProject.push(obj.testId);
              });

              if (this.formData.fndCode.length > 0 && !this.formData.fndCode.some(obj => obj === partName.fndId)) {
                this.formData.fndCode.push(partName.fndId);
              } else if (this.formData.fndCode.length === 0) {
                this.formData.fndCode.push(partName.fndId);
              }
            }
          });
        });
      } else {
        this.partNameList = this.standByList;
        this.partCodeList = this.standByList;
        this.testProjectList = this.testProjectStandByList;
        this.formData.partCode = [];
        this.formData.fndCode = [];
        this.formData.testProject = [];
        this.fndList = this.standByList.filter((item, index) => {
          return this.standByList.findIndex(obj => obj.fndId === item.fndId) === index;
        });
      }
    },

    /**
     * fnd编号级联下拉选择
     * @param val
     */
    handleFndSelect(val) {
      if (val && val.length > 0) {
        this.formData.partCode = [];
        this.formData.partName = [];
        this.formData.testProject = [];
        this.partCodeList = [];
        this.partNameList = [];
        this.testProjectList = [];

        let selectedList = [];
        val.forEach(selection => {
          this.fndList.filter(item => item.fndId === selection).forEach(obj => {
            selectedList.push(obj);
          });
          // 下拉选项 级联
          this.standByList.filter(item => item.fndId === selection).forEach(obj => {
            this.partCodeList.push(obj);
            this.partNameList.push(obj);
          });
          // 选中选项 级联
          this.standByList.filter(item => item.fndId === selection).forEach(obj => {
            this.formData.partCode.push(obj.partId);
            this.formData.partName.push(obj.partId);
          });
        });

        selectedList.forEach(selected => {
          this.testProjectStandByList.filter(item => item.partId === selected.partId).forEach( obj => {
            this.testProjectList.push(obj);
            // this.formData.testProject.push(obj.testId);
          });
        });

      } else {
        this.partCodeList = this.standByList;
        this.partNameList = this.standByList;
        this.testProjectList = this.testProjectStandByList;
        this.fndList = this.standByList.filter((item, index) => {
          return this.standByList.findIndex(obj => obj.fndId === item.fndId) === index;
        });
        this.formData.partName = [];
        this.formData.partCode = [];
        this.formData.testProject = [];
      }
    },

    /**
     * 试验项目级联下拉选
     * @param val
     */
    handleTestProjectSelect(val) {
      if (val && val.length > 0) {
        this.formData.partCode = [];
        this.formData.partName = [];
        this.formData.fndCode = [];
        this.partCodeList = [];
        this.partNameList = [];
        this.fndList = [];

        let selectionList = [];
        val.forEach(selection => {
          this.testProjectList.filter(item => item.testId === selection).forEach(obj => {
            selectionList.push(obj);
          });
        });

        selectionList.forEach(selected => {
          // 下拉选项 级联
          this.standByList.filter(item => item.partId === selected.partId).forEach(obj => {
            this.partCodeList.push(obj);
            this.partNameList.push(obj);
            this.fndList.push(obj);
          });

          // 选中选项 级联
          this.standByList.filter(item => item.partId === selected.partId).forEach(obj => {
            this.formData.partCode.push(obj.partId);
            this.formData.partName.push(obj.partId);
            this.formData.fndCode.push(obj.fndId);
          });
        });

        // 去重
        this.partCodeList = this.partCodeList.filter((value, index, self) => {
          return self.findIndex(item => item.partId === value.partId) === index;
        });

        this.partNameList = this.partNameList.filter((value, index, self) => {
          return self.findIndex(item => item.partId === value.partId) === index;
        });

        this.fndList = this.fndList.filter((item, index) => {
          return this.fndList.findIndex(obj => obj.fndId === item.fndId) === index;
        });

        this.formData.partCode = this.formData.partCode.filter((value, index, self) => {
          return self.findIndex(item => item === value) === index;
        });

        this.formData.partName = this.formData.partName.filter((value, index, self) => {
          return self.findIndex(item => item === value) === index;
        });

        this.formData.fndCode = this.formData.fndCode.filter((value, index, self) => {
          return self.findIndex(item => item === value) === index;
        });

      } else {
        this.partCodeList = this.standByList;
        this.partNameList = this.standByList;
        this.fndList = this.standByList.filter((item, index) => {
          return this.standByList.findIndex(obj => obj.fndId === item.fndId) === index;
        });
        this.formData.partName = [];
        this.formData.partCode = [];
        this.formData.fndCode = [];
      }
    },

    /** 实际开始时间-选择变化 */
    changeStartTime(data, dateString) {
      this.formData.testStartTime = dateString;
      // 当选择的开始时间大于结束时间时，清空结束时间，让用户重新选择结束时间
      if (Date.parse(this.formData.testStartTime) >= Date.parse(this.formData.testEndTime)) {
        this.formData.testEndTime = undefined;
      }
    },
    /** 实际结束时间-选择变化 */
    changeEndTime(data, dateString) {
      this.formData.testEndTime = dateString;
    },

    /**
     * 试验报告文件上传
     * @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);
      });
    },

    /**
     * 试验报告文件删除
     */
    editRemoveFile() {
      this.fileList = [];
    },

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


  }
};
</script>

<style lang="less" scoped>

</style>
