<template>
  <div class="p-2">
    <el-card shadow="never">
      <approvalButton
        @submitForm="submitForm"
        @approvalVerifyOpen="approvalVerifyOpen"
        @handleApprovalRecord="handleApprovalRecord"
        :buttonLoading="buttonLoading"
        :id="form.id"
        :status="form.status"
        :pageType="routeParams.type"
      />
    </el-card>
    <el-card shadow="never" style="height: 78vh; overflow-y: auto; margin-top: 10px">
      <div style="width: 400px">
        <el-form ref="leaveFormRef" v-loading="loading" :disabled="routeParams.type === 'view'" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="图纸类型" prop="fileType">
            <el-select v-model="form.fileType" placeholder="请选择图纸类型">
              <el-option v-for="dict in drawing_file_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="版本号" prop="versionNumber">
            <el-input v-model="form.versionNumber" placeholder="请输入版本号" />
          </el-form-item>
          <el-form-item label="文件名称" prop="fileName">
            <el-input v-model="form.fileName" placeholder="请输入文件名称" />
          </el-form-item>
          <el-form-item label="图纸文件" prop="fileUrl">
            <file-upload :limit="1" :fileType="['pdf']" :fileSize="100" v-model="form.fileUrl" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 提交组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />
    <el-dialog draggable v-model="dialogVisible.visible" :title="dialogVisible.title" :before-close="handleClose" width="500">
      <el-select v-model="flowCode" placeholder="Select" style="width: 240px">
        <el-option v-for="item in flowCodeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitFlow()"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Leave" lang="ts">
import { LeaveForm, LeaveQuery, LeaveVO } from '@/api/workflow/leave/types';
import { startWorkFlow } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ApprovalButton from '@/components/Process/approvalButton.vue';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import {  DrawingForm } from '@/api/design/drawing/types';
import { useUserStoreHook } from '@/store/modules/user';
import { updateDrawing, getDrawing, addDrawing } from '@/api/design/drawing';

// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const { drawing_file_type } = toRefs<any>(proxy?.useDict('drawing_file_type'));
const buttonLoading = ref(false);
const loading = ref(true);
//路由参数
const routeParams = ref<Record<string, any>>({});
const flowCodeOptions = [
  {
    value:currentProject.value?.id+ '_changedrawing',
    label: '变更图纸审批'
  },
  {
    value: currentProject.value?.id+ '_blueprintdrawing',
    label: '蓝图审批'
  },
  {
    value: currentProject.value?.id+ '_processdrawing',
    label: '过程图纸审批'
  }
];

const flowCode = ref<string>('');
const status = ref<string>('');
const dialogVisible = reactive<DialogOption>({
  visible: false,
  title: '流程定义'
});
//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
//审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
//按钮组件
const approvalButtonRef = ref<InstanceType<typeof ApprovalButton>>();

const leaveFormRef = ref<ElFormInstance>();
const dialog = reactive({
  visible: false,
  title: '',
  isEdit: false
});
const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: '',
  variables: {}
});
const taskVariables = ref<Record<string, any>>({});

const initFormData: DrawingForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  versionNumber: undefined,
  fileName: undefined,
  fileUrl: undefined,
  fileType: undefined,
  fileSuffix: undefined,
  originalName: undefined,
  remark: undefined,
  file: undefined
};
const data = reactive<PageData<LeaveForm, LeaveQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    fileName: undefined,
    fileType: undefined,
    fileSuffix: undefined,
    fileStatus: undefined,
    originalName: undefined,
    newest: undefined,
    params: {}
  },
  rules: {
    versionNumber: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
    fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
    fileType: [{ required: true, message: '文件类型不能为空', trigger: 'change' }],
    file: [
      {
        validator: (rule, value, callback) => {
          // 新增时必须上传文件
          if (!form.value.fileUrl) {
            callback(new Error('请上传图纸文件'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ]
  }
});

const handleClose = () => {
  dialogVisible.visible = false;
  flowCode.value = '';
  buttonLoading.value = false;
};
const { form, rules } = toRefs(data);

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  leaveFormRef.value?.resetFields();
};

/** 获取详情 */
const getInfo = () => {
  loading.value = true;
  buttonLoading.value = false;
  nextTick(async () => {
    const res = await getDrawing(routeParams.value.id);
    Object.assign(form.value, res.data);
    loading.value = false;
    buttonLoading.value = false;
  });
};

/** 提交按钮 */
const submitForm = (status1: string) => {
  status.value = status1;
  leaveFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      var res;
      if (form.value.id) {
        res = await updateDrawing(form.value).finally(() => (buttonLoading.value = false));
      } else {
        res = await addDrawing(form.value).finally(() => (buttonLoading.value = false));
      }
      if (res.code == 200) {
        dialog.visible = false;
        submit(status.value, res.data);
      }
    }
  });
};

const submitFlow = async () => {
  handleStartWorkFlow(form.value);
  dialogVisible.visible = false;
};
//提交申请
const handleStartWorkFlow = async (data: LeaveForm) => {
  try {
    submitFormData.value.flowCode = flowCode.value;
    submitFormData.value.businessId = data.id;
    //流程变量
    taskVariables.value = {
      // leave4/5 使用的流程变量
      userList: ['1', '3', '4']
    };
    submitFormData.value.variables = taskVariables.value;
    const resp = await startWorkFlow(submitFormData.value);
    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};
//审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.id);
};
//提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};
//审批
const approvalVerifyOpen = async () => {
  submitVerifyRef.value.openDialog(routeParams.value.taskId);
};
// 图纸上传成功之后 开始提交
const submit = async (status, data) => {
  form.value = data;
  if (status === 'draft') {
    buttonLoading.value = false;
    proxy?.$modal.msgSuccess('暂存成功');
    proxy.$tab.closePage(proxy.$route);
    proxy.$router.go(-1);
  } else {
    if ((form.value.status === 'draft' && (flowCode.value === '' || flowCode.value === null)) || routeParams.value.type === 'add') {
      flowCode.value = flowCodeOptions[0].value;
      dialogVisible.visible = true;
      return;
    }
    //说明启动过先随意穿个参数
    if (flowCode.value === '' || flowCode.value === null) {
      flowCode.value = 'xx';
    }
    console.log(data);
    await handleStartWorkFlow(data);
  }
};

onMounted(() => {
  nextTick(async () => {
    routeParams.value = proxy.$route.query;
    reset();

    loading.value = false;
    if (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval') {
      getInfo();
    }
  });
});
</script>
