<!--
 * @Author: Mm
 * @Date: 2025-05-08 17:46:48
 * @LastEditors: Mm
 * @LastEditTime: 2025-05-26 15:11:19
 * 不写bug的程序员不是一个好程序员!
-->
<template>
  <div v-loading="loading">
    <el-row :gutter="20">
      <el-col :span="24">
        <div v-if="userDepts.length > 1" style="margin-bottom: 10px">
          本次发起部门：
          <el-radio-group v-model="userDeptId">
            <el-radio
              :label="dept.id"
              :key="dept.id"
              v-for="dept in userDepts"
              >{{ dept.name }}</el-radio
            >
          </el-radio-group>
        </div>
        <!--渲染表单-->
        <form-render
          v-if="!loading"
          class="process-form"
          ref="form"
          mode="PC"
          :forms="forms"
          v-model="formData"
          :config="form.formConfig"
        />
      </el-col>
      <el-col :span="9" v-show="false">
        <process-render
          @render-ok="$emit('render-ok')"
          ref="process"
          :pc-mode="!$isMobile()"
          v-if="!loading && userDeptId"
          :process-def-id="form.processDefId"
          :dept-id="userDeptId"
          v-model="processUsers"
          :forms="forms"
          :formData="formData"
          :process="process"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import ProcessRender from '../process/ProcessRender.vue';
import FormRender from '#/views/common/form/FormRender.vue';
import FormDesignRender from '#/views/admin/layout/form/FormDesignRender.vue';
import { getUserDepts } from '#/api/org';
import { getInstanceFormData,approvalTask } from '#/api/processTask';
import { getModelById } from '#/api/modelGroup';
import { startProcess } from '#/api/process';

export default {
  name: 'InitiateProcess',
  components: { FormDesignRender, FormRender, ProcessRender },
  props: {
    code: {
      type: String,
      required: true,
    },
    instanceId: {
      type: String,
      required: false,
    },
    taskId: {
      type: String,
      required: false,
    },
    rwjb: {
      type: String,
      required: false,
    },
    isCxtj: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      formData: {},
      processUsers: {},
      userDepts: [],
      userDeptId: null,
      form: {
        formId: '',
        formName: '',
        logo: {},
        formItems: [],
        process: {},
        remark: '',
      },
    };
  },
  mounted() {
    this.loadFormInfo(this.code);
    this.getUserDept();
  },
  computed: {
    forms() {
      return this.$store.state.design.formItems;
    },
    process() {
      return this.$store.state.design.process;
    },
  },
  methods: {
    getUserDept() {
      getUserDepts(this.$store.state.loginUser.id)
        .then((rsp) => {
          this.userDepts = rsp.data;
          if (this.userDepts.length > 0) {
            this.userDeptId = this.userDepts[0].id;
          }
        })
        .catch((err) => {
          this.$message.error('获取用户部门信息失败');
        });
    },
    loadFormData() {
      if (this.$isNotEmpty(this.instanceId)) {
        getInstanceFormData(this.instanceId)
          .then((rsp) => {
            for (let key in this.formData) {
              this.formData[key] = rsp.data[key];
            }
          })
          .catch((e) => {
            this.$message.error('加载原始数据失败');
          });
      }
    },
    loadFormInfo(id) {
      this.loading = true;
      this.formData = {};
      getModelById(id)
        .then((rsp) => {
          this.loading = false;
          let form = rsp.data;
          form.logo = JSON.parse(form.logo);
          this.form = form;
          //构建表单及校验规则
          this.$store.state.design = form;
          if (this.rwjb) {
            this.formData.field5722983622486 = this.rwjb;
          }

          this.loadFormData();
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error('获取流程模型失败');
        });
    },
    validate(call) {
      this.$refs.form.validate((validForm) => {
        this.$refs.process.validate((validProcess) => {
          call(validForm, validProcess, this.formData);
        });
      });
    },
    submit() {
      let startParams = {
        deptId: this.userDeptId,
        formData: this.formData,
        processUsers: this.processUsers,
        instanceId: this.instanceId,
      };
      if (this.isCxtj) {
        let params = {
          instanceId: this.instanceId,
          taskId: this.taskId,
          comment: {
            text:'',
            attachments:[],
          },
          formData: this.formData,
          signature: '',
          action: 'complete',
          updateSign: false,
          targetNode: null,
          targetUser: null,
          otherNodeUsers: {},
        };
        approvalTask(params).then(res=>{
          this.$message.success('编辑成功,待上级审核');
          this.$emit('ok');
        }).catch(err=>{
            this.$emit('fail');
          this.$message.error('编辑失败');
        })
      } else {
        //this.$message.success("表单填写OK了，提交功能还在开发哦")
        startProcess(this.form.processDefId, startParams)
          .then((rsp) => {
            console.log(rsp, '-------------rsp');

            this.$message.success(rsp.data);
            this.$emit('ok');
          })
          .catch((err) => {
            this.$emit('fail');
            this.$message.error('发起审批失败');
          });
      }
    },
  },
  emits: ['ok', 'fail', 'render-ok'],
};
</script>

<style lang="less" scoped>
.process-form {
  :deep(.el-form-item__label) {
    padding: 0 0;
  }
}
</style>
