<template>
  <ele-modal
    :visible="formParserDialogFlag"
    title="审批"
    :width="modelWidth"
    :centered="true"
    :close-on-click-modal="false"
    append-to-body
    :before-close="cancel"
    :maxable="true"
    :resizable="true"
  >
    <fm-generate-form
      v-if="Object.keys(form?.formJson || {}).length !== 0"
      :data="jsonData"
      :value="form.valueJson"
      ref="generateForm"
    >
      <template v-slot:blank_adopzrdd="scope">
        <div v-for="(item, index) in scope.model.blank_adopzrdd" :key="index">
          <div class="blank_adopzrdd">
            <span>{{ index + 1 }}报销事项：</span>
            <el-input
              v-model="scope.model.blank_adopzrdd[index].remark"
              type="textarea"
              style="width: calc(100% - 80px)"
            ></el-input>
          </div>
          <div class="blank_adopzrdd">
            <span>金额：</span>
            <el-input
              v-model="scope.model.blank_adopzrdd[index].price"
              type="number"
              style="width: calc(100% - 80px)"
            ></el-input>
          </div>
        </div>
      </template>
      <!-- 客户名称 -->
      <template v-slot:eom_contact="scope">
        <div class="eom_contact">
          <el-input
            v-model="scope.model.eom_contact.name"
            style="width: 100%"
            :disabled="view"
          ></el-input>
        </div>
      </template>
      <!-- 关联工单 -->
      <template v-slot:manage_workorder="scope">
        <div class="manage_workorder">
          <el-input
            v-model="scope.model.manage_workorder.code"
            style="width: 100%"
            :disabled="view"
          ></el-input>
        </div>
      </template>
      <!-- 差旅 -->
      <template v-slot:blank_business_component="scope">
        <businessComponent
          ref="blank_business_component"
          id="blank_business_component"
          :generateForm="$refs.generateForm"
          :info="scope.model"
          :view="view"
        ></businessComponent>
      </template>

      <!-- 印章使用 -->
      <template v-slot:blank_use_seal="scope">
        <useSealComponent
          ref="blank_use_seal"
          id="blank_use_seal"
          :generateForm="$refs.generateForm"
          :info="scope.model"
          :view="view"
        ></useSealComponent>
      </template>

      <!-- 资质使用 -->
      <template v-slot:blank_use_qualification="scope">
        <useQualificationComponent
          ref="blank_use_qualification"
          id="blank_use_qualification"
          :generateForm="$refs.generateForm"
          :info="scope.model"
          :view="view"
        ></useQualificationComponent>
      </template>

      <!-- 产品规格 -->
      <template v-slot:blank_product_specification="scope">
        <productSpecificationComponent
          ref="blank_product_specification"
          id="blank_product_specification"
          :generateForm="$refs.generateForm"
          :info="scope.model"
          :view="view"
        ></productSpecificationComponent>
      </template>

      <!-- 事件 -->
      <template v-slot:blank_event_component="scope">
        <eventComponent
          ref="blank_event_component"
          id="blank_event_component"
          :generateForm="$refs.generateForm"
          :info="scope.model"
          :view="view"
        ></eventComponent>
      </template>

      <!-- 补发 -->
      <template v-slot:blank_reissue_component="scope">
        <reissueComponent
          ref="blank_reissue_component"
          id="blank_reissue_component"
          :generateForm="$refs.generateForm"
          :info="scope.model"
          :view="view"
        ></reissueComponent>
      </template>
    </fm-generate-form>

    <outboundXTBG
      v-if="form.taskDefinitionKey == 'CGYSP'"
      :biz-type="4"
      :source-biz-no="form?.processInstance.id"
      ref="outboundXTBGRef"
    ></outboundXTBG>
    <div slot="footer" class="dialog-footer">
      <el-form label-width="100px" ref="formRef" :model="form">
        <!-- prop="reason" -->
        <el-form-item
          label="审批建议"
          style="margin-bottom: 20px"
          :rules="{
            required: true,
            message: '',
            trigger: 'blur'
          }"
        >
          <el-input
            type="textarea"
            v-model="form.reason"
            placeholder="请输入审批建议"
          />
        </el-form-item>
      </el-form>
      <el-button
        icon="el-icon-edit-outline"
        type="success"
        size="mini"
        @click="handleAudit(1)"
        v-if="form.taskDefinitionKey != 'CGYSP'"
        >通过
      </el-button>
      <el-button
        icon="el-icon-edit-outline"
        type="success"
        size="mini"
        :loading="isSaveLoading"
        @click="storemanApprove(1)"
        v-if="form.taskDefinitionKey == 'CGYSP'"
        >出库
      </el-button>
      <el-button
        icon="el-icon-circle-close"
        type="danger"
        size="mini"
        @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>
  </ele-modal>
</template>
<script>
import Parser from '@/components/FormGenerator/components/parser/Parser.vue';
import outboundXTBG from '@/views/bpm/outgoingManagement/outboundXTBG.vue';
import {
  approveTaskWithVariables,
  cancelTask,
  rejectTask
} from '@/api/bpm/task';
import { getToken } from '@/utils/token-util';
import storageApi from '@/api/warehouseManagement';

import businessComponent from '@/BIZComponents/processSubmitDialog/components/businessComponent.vue';
import useSealComponent from '@/BIZComponents/processSubmitDialog/components/useSealComponent.vue';
import useQualificationComponent from '@/BIZComponents/processSubmitDialog/components/useQualificationComponent.vue';
import productSpecificationComponent from '@/BIZComponents/processSubmitDialog/components/productSpecificationComponent.vue';
import eventComponent from '@/BIZComponents/processSubmitDialog/components/eventComponent.vue';
import reissueComponent from '@/BIZComponents/processSubmitDialog/components/reissueComponent.vue';
import { processInstanceValueJsonChange } from '@/api/bpm/processInstance';

export default {
  name: 'formParserDialog',
  components: { Parser, outboundXTBG },
  components: {
    businessComponent,
    useSealComponent,
    useQualificationComponent,
    productSpecificationComponent,
    eventComponent,
    reissueComponent
  },
  props: {
    businessId: {
      default: ''
    },
    formParserDialogFlag: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      index: '',
      jsonData: {},
      width: '30%',
      isSaveLoading: false,
      view: true
    };
  },
  computed: {
    modelWidth() {
      let width =
        this.jsonData.config?.platform && this.jsonData.config.platform === 'pc'
          ? 1100
          : 450;
      if (this.form?.taskDefinitionKey == 'CGYSP') {
        return (width = '70%');
      }
      return width + 'px';
    }
  },
  methods: {
    open(row) {
      this.form = _.cloneDeep(row);
      console.log(this.form.taskDefinitionKey, 'this.form.taskDefinitionKey');

      this.jsonData = JSON.parse(this.form.formJson.makingJson);
      this.jsonData.config.dataSource &&
        this.jsonData.config.dataSource.forEach((item) => {
          item.headers = {
            Authorization: getToken()
          };
          // item.url = item.url && item.url.replace('/api', this.APIUrl);
        });
        this.$nextTick(async() => {
          let data = await this.$refs.generateForm.getData(false);
          console.log('data~~~~~', data);
          // this.$refs.generateForm.disabled(['input_bonus_distribution_ratio', 'input_manager_approval_fee'], true)
          let arr = Object.keys(data)?.filter((item) => item != 'input_bonus_distribution_ratio' && item != 'input_manager_approval_fee')
          console.log(arr, 'arr');
          this.$refs.generateForm.disabled(arr, true)
        })
        
    },
    cancel() {
      this.$emit('update:formParserDialogFlag', false);
    },
    async handleAudit(status) {
      // await processInstanceValueJsonChange({
      //   processInstanceId: this.form.processInstanceId,
      //   valueJson: this.$refs.generateForm.getData(false)
      // })
      // console.log('form', this.form);
      // console.log('processInstanceValueJsonChange', this.$refs.generateForm.getData(false));
      // return
      await this._approveTaskWithVariables(status);
    },

    async storemanApprove(status) {
      let storageData = await this.$refs.outboundXTBGRef.getReturnStorage();
      console.log(storageData);

      // 出库来源isSkip 0-正常  1-外部(外部跳过内部审核流程)
      storageData.isSkip = 1;
      storageData.isMes = 1;
      try {
        this.isSaveLoading = true;
        await storageApi.outStorage(storageData);
        approveTaskWithVariables({
          id: this.form.id,
          reason: this.form.reason,
          businessId: this.businessId,
          variables: {
            pass: true
          }
        }).then((res) => {
          if (res.data.code != '-1') {
            this.$message.success(`出库成功！`);
            this.$emit('reload');
            this.cancel();
          }
          this.isSaveLoading = false;
        });
      } catch (error) {
        this.isSaveLoading = false;
        console.error('出库失败：', error);
      }
    },

    async _approveTaskWithVariables(status) {
      let variables = {
        pass: !!status
      };
      let API = !!status ? approveTaskWithVariables : rejectTask;

      API({
        id: this.form.id,
        reason: this.form.reason,
        businessId: this.businessId,
        variables
      }).then((res) => {
        if (res.data.code != '-1') {
          let params = {
            status,
            title: status === 0 ? '驳回' : ''
          };
          this.$message.success(`审批${params.title}成功！`);
          this.$emit('reload');
          this.cancel();
        }
      });
    },

    //更多
    handleCommand(command) {
      if (command === 'cancel') {
        this.$confirm('是否确认作废？', {
          type: 'warning',
          cancelButtonText: '取消',
          confirmButtonText: '确定'
        })
          .then(() => {
            cancelTask({
              taskId: this.form.id,
              id: this.form.processInstance.id,
              reason: this.form.reason
            })
              .then(() => {
                this.$emit('reload');
                this.cancel();
              })
              .catch(() => {
                this.$message.error('流程作废失败');
              });
          })
          .catch(() => {});
      }
    }
  }
};
</script>
<style scoped lang="scss">
.blank_adopzrdd {
  display: flex;
  align-items: center;
  > span {
    display: inline-block;
    width: 80px;
  }
  margin-bottom: 10px;
}
</style>
