<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible="processSubmitDialogFlag"
    :title="title"
    append-to-body
    :close-on-click-modal="false"
    :width="isRight ? '800px' : '450px'"
    :before-close="cancel"
    :maxable="true"
    :resizable="true"
  >
    <div style="display: flex; height: 100%; justify-content: space-between">
      <div class="form-box">
        <fm-generate-form
          :data="formSchema"
          :value="form.valueJson"
          :remote="remoteFuncs"
          ref="generateForm"
          class="el-form-box"
        >
          <template v-slot:manage_workorder="scope">
            <div class="manage_workorder">
              <el-input
                v-model="scope.model.manage_workorder.code"
                style="width: 100%"
                @click.native="addWorkOrder('manage_workorder')"
                placeholder="点击选择关联工单"
              ></el-input>
            </div> </template
        ></fm-generate-form>
      </div>

      <div
        style="
          align-self: center;
          display: flex;
          color: #1890ff;
          cursor: pointer;
          width: 15px;
        "
        @click="() => (isRight = !isRight)"
      >
        <span
          style="align-self: center; transform: scale(1.5)"
          :class="isRight ? 'el-icon-caret-left' : 'el-icon-caret-right'"
        ></span>
        <span style="writing-mode: vertical-rl">选择流程</span>
      </div>

      <div style="flex: 1" v-if="isRight">
        <el-form
          ref="processForm"
          class="el-form-box"
          :model="form"
          label-width="80px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="流程分类">
                <ele-tree-select
                  @change="changeLCFL"
                  clearable
                  ref="processTypeRef"
                  filterable
                  :data="LCFLList"
                  v-model="form.LCFL"
                  childrenKey="children"
                  valueKey="id"
                  labelKey="name"
                  placeholder="请选择"
                  default-expand-all
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发起流程">
                <el-select
                  filterable
                  v-model="form.FQLC"
                  @change="changeFQLC"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in processList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="流程名称">
                <el-input v-model="form.name" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="流程标识">
                <el-input v-model="form.key" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <headerTitle
            title="流程执行人/流程图"
            style="margin-top: 30px"
          ></headerTitle>
          <el-table
            :data="datasource"
            height="150px"
            border
            style="margin-bottom: 10px"
          >
            <el-table-column
              label="任务节点"
              align="center"
              prop="taskDefinitionName"
              width="140"
              fixed
            />
            <el-table-column
              label="执行人"
              align="center"
              prop="options"
              min-width="140px"
            >
              <template v-slot="scope">
                <div
                  v-if="
                    scope.row.type !== 60 &&
                    scope.row.type !== 70 &&
                    scope.row.type !== 80 &&
                    scope.row.options.length > 0
                  "
                >
                  <el-tag
                    size="medium"
                    :key="option"
                    v-for="option in scope.row.options"
                  >
                    {{ getAssignRuleOptionName(scope.row, option) }}
                  </el-tag>
                </div>
                <el-tag
                  size="medium"
                  v-if="
                    scope.row.type === 60 ||
                    scope.row.type === 70 ||
                    scope.row.type === 80
                  "
                >
                  {{ getAssignRuleOptionName(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <my-process-viewer
            style="min-width: 100%; height: 200px"
            key="designer"
            v-model="bpmnXML"
          />
        </el-form>
      </div>
    </div>

    <div slot="footer">
      <el-button type="primary" size="small" @click="submit">提交</el-button>
      <el-button size="small" @click="cancel">关闭</el-button>
    </div>

    <SHGDListDialog
      ref="SHGDListDialogRef"
      @changeParent="getSHGDData"
    ></SHGDListDialog>
  </ele-modal>
</template>

<script>
import {
  getModelPage,
  getProcessDefinitionBpmnXML,
  getTaskAssignRuleList,
  listAllUserBind,
  listSimpleUserGroups,
  getModel,
  savePieCarMonad
} from './api';
import { treeClassifyCodeEnum } from '@/enum/dict';
import { listRoles } from '@/api/system/role';
import { listOrganizations } from '@/api/system/organization';
import dictMixins from '@/mixins/dictMixins';
import { getByCode } from '@/api/system/dictionary-data';
import { getProduceTreeByCode } from '@/api/main';
import { topLevel1, topLevel2, topLevel3 } from '@/enum/dict';
import { getToken } from '@/utils/token-util';
import { mapGetters } from 'vuex';
import SHGDListDialog from '@/views/salesServiceManagement/workOrder/components/drawer.vue';

export default {
  name: 'processSubmitDialog',
  mixins: [dictMixins],
  components: {
    SHGDListDialog
  },
  props: {
    processSubmitDialogFlag: {
      type: Boolean,
      default: false
    },
    formSchema: {
      type: Object,
      default: () => ({})
    },
    carByTemplate: {
      type: Object,
      default: () => ({})
    },
    workOrderData: {
      type: Object,
      default: () => ({ id: '', code: '', name: '' })
    }
  },
  data() {
    return {
      title: '用车',
      isRight: false,
      remoteFuncs: {},
      form: {
        LCFL: '',
        FQLC: '',
        processDefinitionId: '',
        name: '',
        key: 'TYCSLC',
        valueJson: {
          manage_workorder: {
            code: '',
            id: '',
            name: ''
          }
        },
        processModelId: ''
      },
      LCFLList: [],
      processList: [],
      datasource: [],
      bpmnXML: null,
      roleOptions: [],
      deptOptions: [],
      userOptions: [],
      userGroupOptions: [],
      dictList: {}
    };
  },
  watch: {
    processSubmitDialogFlag(newVal) {
      if (newVal) {
        this.initDefaultProcessByKey('TYCSLC');
        if (this.workOrderData.id) {
          this.form.valueJson.manage_workorder = {
            id: this.workOrderData.id,
            code: this.workOrderData.code,
            name: this.workOrderData.name
          };
          if (this.$refs.generateForm) {
            this.$refs.generateForm.setData({
              manage_workorder: this.form.valueJson.manage_workorder
            });
          }
        }
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  async created() {
    await this.initProcessBaseData();
    await this.initDefaultProcessByKey('TYCSLC');
  },
  methods: {
    getSHGDData(workOrder) {
      if (!workOrder?.code) {
        this.$message.warning('选中的工单缺少编码，请重新选择');
        return;
      }
      this.$refs.generateForm.getData(false).then((currentFormData) => {
        currentFormData.manage_workorder = {
          code: workOrder.code,
          id: workOrder.id || '',
          name: workOrder.name || ''
        };
        this.$refs.generateForm.setData({
          manage_workorder: currentFormData.manage_workorder
        });
        this.form.valueJson.manage_workorder = currentFormData.manage_workorder;
      });
    },
    addWorkOrder() {
      this.$refs.SHGDListDialogRef.open();
    },
    async initProcessBaseData() {
      const typeObj = await getProduceTreeByCode(
        treeClassifyCodeEnum['PROCESSTYPE']
      );
      this.LCFLList = typeObj[0]?.children || [];
      await this.initBaseOptions();
    },
    async initBaseOptions() {
      const roleRes = await listRoles({ current: 1, size: 9999 });
      this.roleOptions = roleRes.list || [];

      const deptRes = await listOrganizations();
      this.deptOptions = deptRes || [];

      const userRes = await listAllUserBind();
      this.userOptions = userRes || [];

      const userGroupRes = await listSimpleUserGroups();
      this.userGroupOptions = userGroupRes || [];

      await this.getDictList(this.dictEnum['工作流任务分配自定义脚本']);
      await this.getDictList(this.dictEnum['工种类型']);
    },
    async initDefaultProcessByKey(targetKey) {
      try {
        const { list } = await getModelPage({
          pageNo: 1,
          pageSize: 1,
          key: targetKey
        });
        if (list.length === 0) {
          this.$message.warning(
            `未找到标识为【${targetKey}】的流程模型，请检查配置`
          );
          return;
        }
        const defaultModel = list[0];
        this.form.LCFL = defaultModel.category;
        this.form.FQLC = defaultModel.id;
        this.form.name = defaultModel.name;
        this.form.processModelId = defaultModel.id;
        await this.getProcessList(defaultModel.category);
        await this.changeFQLC(defaultModel.id);
      } catch (error) {
        console.error(error);
        this.$message.error('默认流程加载失败，请手动选择流程');
      }
    },
    async changeLCFL(val) {
      this.bpmnXML = null;
      this.form.processDefinitionId = '';
      this.form.FQLC = '';
      await this.getProcessList(val);
    },
    async getProcessList(processTypeId) {
      const { list } = await getModelPage({
        pageNo: 1,
        pageSize: 999,
        processTypeId
      });
      this.processList = list.filter((item) => item.processDefinition);
    },
    async changeFQLC(val) {
      if (!val) return;
      const selectedProcess =
        this.processList.find((item) => item.id === val) || {};
      const processDef = selectedProcess.processDefinition || {};
      this.form.name = selectedProcess.name || this.title;
      this.form.key = selectedProcess.key || 'TYCSLC';
      this.form.processDefinitionId = processDef.id || '';
      this.form.processModelId = val;
      await this.getProcessDefinitionBpmnXMLInfo(val);
      await this.getTaskAssignRuleListInfo({
        modelId: val,
        processDefinitionId: processDef.id
      });
    },
    async getProcessDefinitionBpmnXMLInfo(modelId) {
      const res = await getModel(modelId);
      this.bpmnXML = res.bpmnXml;
    },
    async getTaskAssignRuleListInfo(params) {
      this.datasource = await getTaskAssignRuleList(params);
    },
    getAssignRuleOptionName(row, option) {
      if (row.type === 10) {
        const role = this.roleOptions.find((item) => item.id === option);
        return role?.name || `未知角色(${option})`;
      } else if (row.type === 20 || row.type === 21) {
        const dept = this.deptOptions.find((item) => item.id === option);
        return dept?.name || `未知部门(${option})`;
      } else if (row.type === 22) {
        return (
          this.getDictV(this.dictEnum['工种类型'], option + '') ||
          `未知工种(${option})`
        );
      } else if (row.type === 30 || row.type === 31 || row.type === 32) {
        const user = this.userOptions.find((item) => item.id === option);
        return user?.nickname || user?.name || `未知用户(${option})`;
      } else if (row.type === 40) {
        const group = this.userGroupOptions.find((item) => item.id === option);
        return group?.name || `未知用户组(${option})`;
      } else if (row.type === 50) {
        return (
          this.getDictV(
            this.dictEnum['工作流任务分配自定义脚本'],
            option + ''
          ) || `未知脚本(${option})`
        );
      } else if (row.type === 60) {
        return row.variableName || '变量执行人';
      } else if (row.type === 70) {
        const data = JSON.parse(row.variableName || '{}');
        const levelList = data.direction === 1 ? topLevel2 : topLevel1;
        return (
          levelList.find((item) => item.value === data.topLevel)?.label ||
          '未知层级'
        );
      } else if (row.type === 80) {
        const data = JSON.parse(row.variableName || '{}');
        return (
          topLevel3.find((item) => item.value === data.topLevel)?.label ||
          '未知层级'
        );
      }
      return `未知类型(${option || '无'})`;
    },
    getDictV(dictCode, val) {
      if (!this.dictList[dictCode]) return '';
      return (
        this.dictList[dictCode].find((item) => item.value === val)?.label || ''
      );
    },
    async getDictList(dictCode) {
      const { data: res } = await getByCode(dictCode);
      this.dictList[dictCode] = res.map((item) => {
        const keys = Object.keys(item);
        return { value: keys[0], label: item[keys[0]] };
      });
    },
    generateFormValid(validate = true) {
      return this.$refs.generateForm.getData(validate).then((data) => data);
    },
    // async submit() {
    //   try {
    //     this.form.valueJson = await this.generateFormValid();
    //     const submitData = {
    //       ...this.form,
    //       ...this.carByTemplate,
    //       processType: '1',
    //       variables: { ...this.form.valueJson }
    //     };
    //     console.log(submitData.formJson.makingJson)
    //     this.$emit('formSubmit', submitData);
    //     await savePieCarMonad(submitData);
    //     this.cancel();
    //   } catch (error) {
    //     console.error(error);
    //     this.$message.warning('表单验证失败，请检查填写内容');
    //   }
    // },
    async submit() {
      try {
        const formValue = await this.generateFormValid();
        this.form.valueJson = formValue;

        const workOrderId = this.form.valueJson.manage_workorder.id;
        if (!workOrderId) {
          this.$message.warning('请先选择关联工单');
          return;
        }
        const submitData = {
          ...this.form,
          ...this.carByTemplate,
          processType: '1',
          variables: { ...this.form.valueJson }
        };
        const submitParams = {
          id: workOrderId,
          formJson: submitData
        };

        this.loading = true;
        await savePieCarMonad(submitParams);
        this.$message.success('提交成功');

        this.cancel();
      } catch (error) {
        console.error('提交失败：', error);
        this.$message.error('提交失败，请重试');
      } finally {
        this.loading = false;
      }
    },
    cancel() {
      this.$emit('update:processSubmitDialogFlag', false);
      this.isRight = false;
      this.bpmnXML = null;
      this.datasource = [];
      this.form = {
        ...this.form,
        FQLC: '',
        processDefinitionId: '',
        name: '',
        processModelId: '',
        valueJson: {
          ...this.form.valueJson,
          manage_workorder: { code: '', id: '', name: '' }
        }
      };
      if (this.$refs.generateForm) this.$refs.generateForm.reset();
      if (this.$refs.processForm) this.$refs.processForm.resetFields();
      this.remoteFuncs = {};
    }
  }
};
</script>

<style scoped lang="scss">
.form-box {
  min-width: 400px;
  overflow: auto;
  background: #4298fd0d;
}

::v-deep .el-dialog {
  min-width: 400px;
  .el-dialog__header {
    background: #1890ffd6;
  }
  .el-dialog__title,
  .el-dialog__close {
    color: #ffffff;
  }
}

::v-deep .el-table {
  margin-top: 10px;
  .el-table__header th {
    background: #f5f7fa;
  }
}

::v-deep .bpmn-viewer {
  border: 1px solid #e5e7eb;
  border-radius: 4px;
}
</style>