<template>
  <el-col
    :span="16"
    :offset="6"
    v-if="
      activeComp == taskDefinitionKey || childActiveComp == taskDefinitionKey
    "
  >
    <el-form label-width="100px" ref="formRef" :rules="rules" :model="form">
      <el-form-item
        v-if="
          ['QCLeader', 'techLeader', 'produceLeader'].includes(
            taskDefinitionKey
          )
        "
        label="负责人"
        prop="userId"
        style="margin-bottom: 20px"
        :rules="{
          required: true,
          message: '请选择',
          trigger: 'change'
        }"
      >
        <el-select
          v-model="form.userId"
          clearable
          style="width: 100%"
          :filterable="true"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审批建议" prop="reason" style="margin-bottom: 20px">
        <el-input
          type="textarea"
          v-model="form.reason"
          placeholder="请输入审批建议"
        />
      </el-form-item>
    </el-form>
    <div style="margin-left: 10%; margin-bottom: 20px; font-size: 14px">
      <el-button
        icon="el-icon-edit-outline"
        type="success"
        size="mini"
        :loading="isLoading"
        @click="handleAudit(1)"
        >通过
      </el-button>

      <el-button
        icon="el-icon-circle-close"
        type="danger"
        size="mini"
        v-if="taskDefinitionKey !== 'stater'"
        @click="handleAudit(0)"
        >驳回
      </el-button>

      <el-dropdown
        @command="(command) => handleCommand(command)"
        style="margin-left: 30px"
      >
        <span class="el-dropdown-link"
          >更多<i class="el-icon-arrow-down el-icon--right"></i
        ></span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="cancel">作废</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </el-col>
</template>

<script>
  import { uploadQualityFile } from '@/api/classifyManage';
  import {
    approveTaskWithVariablesAPI,
    saleReturnUpdateAPI,
    updateReceiptAPI,
    returnHandleProcessCancel
  } from '@/api/bpm/components/saleManage/saleorder';
  import { listAllUserBind } from '@/api/system/organization';
  import { EventBus } from './eventBus.js';
  import outin from '@/api/warehouseManagement/outin';
  // 流程实例的详情页，可用于审批
  //qcId techId produceId
  export default {
    name: '',
    components: {
      //   Parser
    },
    props: {
      businessId: {
        default: ''
      },
      taskId: {
        default: ''
      },
      id: {
        default: ''
      },
      taskDefinitionKey: {
        default: ''
      }
    },
    data() {
      return {
        form: {
          userId: '',
          reason: ''
        },
        submitParams: {
          QCLeader: 'qcId',
          techLeader: 'techId',
          produceLeader: 'produceId'
        },
        rules: {
          reason: {
            required: true,
            message: '请输入审批建议',
            trigger: 'blur'
          },
          userId: { required: true, message: '请选择指派人', trigger: 'change' }
        },
        isLoading: false,
        userOptions: [],
        activeComp: '',
        permissionType: '',
        childActiveComp: ''
      };
    },
    async created() {
      this.userOptions = [];
      listAllUserBind().then((data) => {
        this.userOptions.push(...data);
      });
      this.activeComp = this.taskDefinitionKey;
      EventBus.$on('getActiveCompValue', (row) => {
        this.activeComp = row.activeComp;
        this.childActiveComp = row.childActiveComp;
        this.permissionType = row.permissionType;
        console.log(this.childActiveComp, this.taskDefinitionKey, '=====');
      });
    },
    mounted() {},
    methods: {
      // 修改内部重量
      async innerFillWeightQuality(data, pass) {
        let boolen = data.qualityInspectionStatus;
        if (boolen) {
          approveTaskWithVariablesAPI({
            id: this.taskId,
            reason: this.form.reason,
            variables: {
              pass: !!pass
            }
          }).then((res) => {
            if (res.code != '-1') {
              this.$emit('handleAudit', {
                status: pass,
                title: !pass ? '驳回' : ''
              });
            }
          });
        } else {
          this.$message.error('保存错误');
        }
      },
      // 修改外部重量
      async outerFillWeightQuality(data, pass) {
        let boolen = data.qualityInspectionStatus;
        if (boolen) {
          approveTaskWithVariablesAPI({
            id: this.taskId,
            reason: this.form.reason,
            variables: {
              pass: !!pass
            }
          }).then((res) => {
            if (res.code != '-1') {
              this.$emit('handleAudit', {
                status: pass,
                title: !pass ? '驳回' : ''
              });
            }
          });
        } else {
          this.$message.error('保存错误');
        }
      },
      // 外协返修质检入库
      async interiorStorageToOutsourcingQuality(data, pass) {
        console.log(data);
        // if (data.qualityInspector.qualityFile.length == 0) {
        //   return this.$message.error('请上传回执附件！');
        // }
        let boolen = data.qualityInspectionStatus;
        if (boolen) {
          if (
            data.qualityInspector.qualityFile &&
            data.qualityInspector.qualityFile.length > 0
          ) {
            await uploadQualityFile(data.qualityInspector);
          }
          approveTaskWithVariablesAPI({
            id: this.taskId,
            reason: this.form.reason,
            variables: {
              pass: !!pass
            }
          }).then((res) => {
            if (res.code != '-1') {
              this.$emit('handleAudit', {
                status: pass,
                title: !pass ? '驳回' : ''
              });
            }
          });
        } else {
          this.$message.error('请完成质检');
        }
      },
      // 外协返修物品入库
      async interiorStorageToOutsourcing(data, pass) {
        let storageData = data.returnStorageData;
        // 入库来源storageSource 0-正常  1-外部(外部跳过内部审核流程)
        storageData.storageSource = 1;
        console.log(storageData);
        // 获取货位信息(判断货位信息是否填写)
        let houseListLength = storageData.outInDetailAddPOList.map((item) => {
          return item.houseList.length;
        });
        let boolen = houseListLength.every((item) => item > 0);
        if (boolen) {
          try {
            this.isLoading = true;
            const res = await outin.save(storageData);
            data.outerInReceiptId = res.data[0];
            await updateReceiptAPI(data);
            approveTaskWithVariablesAPI({
              id: this.taskId,
              reason: this.form.reason,
              variables: {
                pass: !!pass
              }
            }).then((res) => {
              if (res.code != '-1') {
                this.$emit('handleAudit', {
                  status: pass,
                  title: !pass ? '驳回' : ''
                });
              }
              this.isLoading = false;
            });
          } catch (error) {
            this.isLoading = false;
            console.error('保存失败：', error);
          }
        } else {
          this.$message.error('请选择物品货位信息');
        }
      },
      // 物品出库给外协
      async outboundToOutsourcing(data, pass) {
        let storageData = data.returnStorageData;
        // 入库来源storageSource 0-正常  1-外部(外部跳过内部审核流程)
        storageData.storageSource = 1;
        console.log(storageData);
        try {
          this.isLoading = true;
          const res = await outin.saveNew(storageData);
          data.outerOutReceiptId = res.data[0];
          await updateReceiptAPI(data);
          approveTaskWithVariablesAPI({
            id: this.taskId,
            reason: this.form.reason,
            variables: {
              pass: !!pass
            }
          }).then((res) => {
            if (res.code != '-1') {
              this.$emit('handleAudit', {
                status: pass,
                title: !pass ? '驳回' : ''
              });
            }
            this.isLoading = false;
          });
        } catch (error) {
          this.isLoading = false;
          console.error('保存失败：', error);
        }
      },
      // 内部生产物品入库
      async interiorProductionStorage(data, pass) {
        console.log('data.returnStorageData---------', data.returnStorageData);
        let storageData = data.returnStorageData;
        // 入库来源storageSource 0-正常  1-外部(外部跳过内部审核流程)
        storageData.storageSource = 1;
        console.log(storageData);
        // 获取货位信息(判断货位信息是否填写)
        let houseListLength = storageData.outInDetailAddPOList.map((item) => {
          return item.houseList.length;
        });
        let boolen = houseListLength.every((item) => item > 0);
        if (boolen) {
          try {
            this.isLoading = true;
            const res = await outin.save(storageData);
            data.innerInReceiptId = res.data[0];
            await updateReceiptAPI(data);
            approveTaskWithVariablesAPI({
              id: this.taskId,
              reason: this.form.reason,
              variables: {
                pass: !!pass
              }
            }).then((res) => {
              if (res.code != '-1') {
                this.$emit('handleAudit', {
                  status: pass,
                  title: !pass ? '驳回' : ''
                });
              }
              this.isLoading = false;
            });
          } catch (error) {
            this.isLoading = false;
            console.error('保存失败：', error);
          }
        } else {
          this.$message.error('请选择物品货位信息');
        }
      },
      // 内部生产入库质检
      async interiorProductionStorageQuality(data, pass) {
        console.log(data);
        // if (data.qualityInspector.qualityFile.length == 0) {
        //   return this.$message.error('请上传回执附件！');
        // }
        let boolen = data.qualityInspectionStatus;
        if (boolen) {
          if (
            data.qualityInspector.qualityFile &&
            data.qualityInspector.qualityFile.length > 0
          ) {
            await uploadQualityFile(data.qualityInspector);
          }
          approveTaskWithVariablesAPI({
            id: this.taskId,
            reason: this.form.reason,
            variables: {
              pass: !!pass
            }
          }).then((res) => {
            if (res.code != '-1') {
              this.$emit('handleAudit', {
                status: pass,
                title: !pass ? '驳回' : ''
              });
            }
          });
        } else {
          this.$message.error('请完成质检');
        }
      },
      // 销售退货入库
      async salesReturnsInStorage(data, pass) {
        // 获取销售退货入库信息
        console.log('data.returnStorageData--------', data.returnStorageData);
        let storageData = data.returnStorageData;
        // 是否已经入库
        if (storageData.isStorage) {
          try {
            this.isLoading = true;
            approveTaskWithVariablesAPI({
              id: this.taskId,
              reason: this.form.reason,
              variables: {
                pass: !!pass
              }
            }).then((res) => {
              if (res.code != '-1') {
                this.$emit('handleAudit', {
                  status: pass,
                  title: !pass ? '驳回' : ''
                });
              }
              this.isLoading = false;
            });
          } catch (error) {
            this.isLoading = true;
          }
        } else {
          // 入库来源storageSource 0-正常  1-外部(外部跳过内部审核流程)
          storageData.storageSource = 1;
          // 获取货位信息(判断货位信息是否填写)
          let houseListLength = storageData.outInDetailAddPOList.map((item) => {
            return item.houseList.length;
          });
          let boolen = houseListLength.every((item) => item > 0);
          if (boolen) {
            try {
              this.isLoading = true;
              const res = await outin.save(storageData);
              data.returnInReceiptId = res.data[0];
              await saleReturnUpdateAPI(data);
              approveTaskWithVariablesAPI({
                id: this.taskId,
                reason: this.form.reason,
                variables: {
                  pass: !!pass
                }
              }).then((res) => {
                if (res.code != '-1') {
                  this.$emit('handleAudit', {
                    status: pass,
                    title: !pass ? '驳回' : ''
                  });
                }
                this.isLoading = false;
              });
            } catch (error) {
              this.isLoading = false;
              console.error('保存失败：', error);
            }
          } else {
            this.$message.error('请选择物品货位信息');
          }
        }
      },
      //保存表格数据
      async handleAudit(pass) {
        let data = await this.getTableValue();
        let updateCode = '1'; //判断saleReturnUpdateAPI方法是否执行成功
        this.$refs.formRef.validate(async (validate) => {
          if ((!validate || !data) && !!pass)
            return this.$message.warning('有必填项未填，请检查');
          if (this.taskDefinitionKey === 'storeman' && !!pass) {
            // 销售退货入库节点
            this.salesReturnsInStorage(data, pass);
          } else if (this.taskDefinitionKey === 'innerStoremanIn' && !!pass) {
            // 内部生产物品入库
            this.interiorProductionStorage(data, pass);
          } else if (this.taskDefinitionKey === 'innerInQC' && !!pass) {
            // 内部生产入库质检
            this.interiorProductionStorageQuality(data, pass);
          } else if (this.taskDefinitionKey === 'outerStoremanOut' && !!pass) {
            // 物品出库给外协
            this.outboundToOutsourcing(data, pass);
          } else if (this.taskDefinitionKey === 'outerStoremanIn' && !!pass) {
            // 外协返修物品入库
            this.interiorStorageToOutsourcing(data, pass);
          } else if (this.taskDefinitionKey === 'outerInQC' && !!pass) {
            // 外协返修质检入库
            this.interiorStorageToOutsourcingQuality(data, pass);
          } else if (this.taskDefinitionKey === 'innerFillWeight' && !!pass) {
            // 修改内部重量
            this.innerFillWeightQuality(data, pass);
          } else if (this.taskDefinitionKey === 'outerFillWeight' && !!pass) {
            // 修改外部重量
            this.outerFillWeightQuality(data, pass);
          } else {
            if (this.permissionType == 'update' && !!pass)
              updateCode = await saleReturnUpdateAPI(data);
            if (typeof updateCode !== 'string') return;
            let variables = {
              pass: !!pass
            };
            if (this.submitParams[this.taskDefinitionKey]) {
              variables[this.submitParams[this.taskDefinitionKey]] =
                this.form.userId;
            }
            approveTaskWithVariablesAPI({
              id: this.taskId,
              reason: this.form.reason,
              variables
            }).then((res) => {
              if (res.code != '-1') {
                this.$emit('handleAudit', {
                  status: pass,
                  title: !pass ? '驳回' : ''
                });
              }
            });
          }
        });
      },
      getTableValue() {
        return new Promise((resolve, reject) => {
          this.$emit('getTableValue', async (data) => {
            resolve(await data);
          });
        });
      },

      //更多
      handleCommand(command) {
        if (command === 'cancel') {
          this.$confirm('是否确认作废？', {
            type: 'warning',
            cancelButtonText: '取消',
            confirmButtonText: '确定'
          })
            .then(() => {
              returnHandleProcessCancel({
                id: this.taskId,
                reason: this.form.reason,
                businessId: this.businessId
              })
                .then(() => {
                  this.$emit('handleClose');
                })
                .catch(() => {
                  this.$message.error('流程作废失败');
                });
            })
            .catch(() => {});
        }
      }
    },
    beforeDestroy() {
      EventBus.$off('getActiveCompValue');
    }
  };
</script>

<style lang="scss"></style>
