<template>
  <el-col :span="16" :offset="6">
    <el-form label-width="100px" ref="formRef" :model="form">
      <el-form-item
        label="质检员"
        prop="qualityInspector"
        style="margin-bottom: 20px"
        :rules="{
          required: true,
          message: '请选择',
          trigger: 'change'
        }"
        v-if="taskDefinitionKey == 'QCLeaderApprove'"
      >
        <el-select
          v-model="form.qualityInspector"
          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"
        :rules="{
          required: true,
          message: '请选择',
          trigger: 'change'
        }"
      >
        <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="isSaveLoading"
        @click="handleAudit(1)"
        >通过
      </el-button>
      <el-button
        icon="el-icon-circle-close"
        type="danger"
        size="mini"
        @click="handleAudit(0)"
        v-if="!['starter'].includes(taskDefinitionKey)"
        >驳回
      </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>

      <!-- <el-button
        icon="el-icon-circle-close"
        type="danger"
        size="mini"
        @click="handleBackList"
        >退回
      </el-button> -->
      <!-- <el-button
        icon="el-icon-circle-close"
        type="danger"
        size="mini"
        @click="handleAudit(0)"
        v-if="taskDefinitionKey != 'productionSupervisorApprove1'"
        >不通过
      </el-button>
      <el-button
        icon="el-icon-edit-outline"
        type="primary"
        size="mini"
        v-if="taskDefinitionKey != 'productionSupervisorApprove1'"
        @click="handleUpdateAssignee"
        >转办
      </el-button> -->
    </div>
  </el-col>
</template>

<script>
  import { uploadQualityFile } from '@/api/classifyManage';
  import { listAllUserBind } from '@/api/system/organization';
  import outin from '@/api/warehouseManagement/outin';
  import { cancel } from '@/api/bpm/components/saleManage/entrustedReceive';
  import { approveTaskWithVariables } from '@/api/bpm/task';
  import { getWarehouseListByIds } from '@/api/bpm/components/saleManage/saleorder';

  // 流程实例的详情页，可用于审批
  export default {
    name: '',
    components: {
      //   Parser
    },
    props: {
      businessId: {
        default: ''
      },
      taskId: {
        default: ''
      },
      id: {
        default: ''
      },
      taskDefinitionKey: {
        default: ''
      }
    },
    data() {
      return {
        userOptions: [],
        isSaveLoading: false,
        form: {
          reason: ''
        },
        tabOptions: [
          { key: 'starter', permissionType: 'update', name: '发起人申请' },
          {
            key: 'deptLeaderApprove',
            permissionType: 'view',
            name: '部门主管审批'
          },
          {
            key: 'storeManagerApprove',
            permissionType: 'view',
            name: '仓管出库'
          },
          { key: 'QCLeaderApprove', permissionType: 'view', name: '质检主管' },
          {
            key: 'qualityInspection',
            permissionType: 'view',
            name: '质检员质检'
          },
          {
            key: 'qualityInspectionFeedback',
            permissionType: 'view',
            name: '质检员反馈'
          }
        ]
      };
    },
    created() {
      this.userOptions = [];
      listAllUserBind().then((data) => {
        this.userOptions.push(...data);
      });
    },
    methods: {
      /** 处理转办审批人 */
      handleUpdateAssignee() {
        this.$emit('handleUpdateAssignee');
      },
      /** 退回 */
      handleBackList() {
        this.$emit('handleBackList');
      },

      async handleAudit(status) {
        let storemanIds = '';
        let permissionType = this.tabOptions.find(
          (item) => item.key == this.taskDefinitionKey
        )?.permissionType;
        if (permissionType === 'update') {
          await this.getTableValue();
        }
        if (this.taskDefinitionKey === 'QCLeaderApprove' && status) {
          if (!this.form.qualityInspector) {
            return this.$message.error('请选择质检员！');
          }
        }

        if (this.taskDefinitionKey === 'deptLeaderApprove') {
          let arr = await this.getTableValue();
          let ids = arr.productList.map((item) => item.warehouseId);
          let data = await getWarehouseListByIds(ids || []);
          storemanIds = [...new Set(data.map((item) => item.ownerId))].join(
            ','
          );
        }

        if (this.taskDefinitionKey === 'qualityInspection' && status) {
          let arr = await this.getTableValue(); // 是否全部已检
          if (!arr.isAllChecked) {
            return this.$message.error('请完成质检！');
          }
        }

        if (this.taskDefinitionKey === 'qualityInspectionFeedback' && status) {
          let arr = await this.getTableValue();
          // if (arr.qualityInspector.qualityFile.length == 0) {
          //   return this.$message.error('请上传回执附件！');
          // }
          // await uploadQualityFile(arr.qualityInspector);
          if (
            arr.qualityInspector.qualityFile &&
            arr.qualityInspector.qualityFile.length > 0
          ) {
            await uploadQualityFile(arr.qualityInspector);
          }
        }

        if (this.taskDefinitionKey === 'storeManagerApprove' && status) {
          let res = await this.getTableValue();
          let storageData = res.returnStorageData;
          console.log(storageData);
          // 入库来源storageSource 0-正常  1-外部(外部跳过内部审核流程)
          storageData.storageSource = 1;
          try {
            this.isSaveLoading = true;
            await outin.save(storageData);
            approveTaskWithVariables({
              id: this.taskId,
              reason: this.form.reason,
              variables: {
                pass: true
              }
            }).then((res) => {
              if (res.code != '-1') {
                this.$emit('handleAudit', {
                  status: 1,
                  title: '入库'
                });
              }
              this.isSaveLoading = false;
            });
          } catch (error) {
            this.isSaveLoading = false;
            this.$message.error('保存失败');
          }
        } else {
          await this._approveTaskWithVariables(status, storemanIds);
        }
      },
      async _approveTaskWithVariables(status, storemanIds) {
        let variables = {
          pass: !!status,
          storemanIds
        };
        if (this.form.qualityInspector) {
          variables['qualityInspector'] = this.form.qualityInspector;
        }
        approveTaskWithVariables({
          id: this.taskId,
          reason: this.form.reason,
          variables
        }).then((res) => {
          if (res.data.code != '-1') {
            this.$emit('handleAudit', {
              status,
              title: status === 0 ? '驳回' : ''
            });
          }
        });
      },

      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(() => {
              cancel({
                id: this.taskId,
                reason: this.form.reason,
                businessId: this.businessId
              })
                .then(() => {
                  this.$emit('handleClose');
                })
                .catch(() => {
                  this.$message.error('流程作废失败');
                });
            })
            .catch(() => {});
        }
      }
    }
  };
</script>

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