<script setup lang="ts">
import type { FormExpose } from 'ant-design-vue/es/form/Form';
import type { User } from '../interface';
import { selectUser } from '@pubinfo/module-rbac';
import { useToggle } from '@vueuse/core';
import { message } from 'ant-design-vue';

import {
  getBpmTaskListByReturn,
  postBpmTaskApprove,
  postBpmTaskCopy,
  postBpmTaskCreateSign,
  postBpmTaskDelegate,
  postBpmTaskDeleteSign,
  postBpmTaskReject,
  postBpmTaskReturn,
  postBpmTaskTransfer,
} from '@/api/modules/bpmTask/guanlihoutailiuchengrenwushili';
import { postBpmProcessInstanceCancelByStartUser } from '@/api/modules/bpmTask/guanlihoutailiuchengshili';
import { OperationButtonType } from '../../flow-create/flow-model/createComponents/flow/ts/enum';

defineOptions({
  name: 'DrawerHandle',
});

const emit = defineEmits(['submit']);

const optTypeNameMap: Record<OperationButtonType, any> = {
  [OperationButtonType.APPROVE]: { optType: '通过', userType: '', textArea: '审批意见' },
  [OperationButtonType.REJECT]: { optType: '拒绝', userType: '', textArea: '审批意见' },
  [OperationButtonType.COPY]: { optType: '抄送', userType: '抄送人', textArea: '抄送意见' },
  [OperationButtonType.TRANSFER]: { optType: '转办', userType: '新审批人', textArea: '转办意见' },
  [OperationButtonType.DELEGATE]: { optType: '委派', userType: '接受人', textArea: '委派意见' },
  [OperationButtonType.ADD_SIGN]: { optType: '加签', userType: '加签处理人', textArea: '加签意见' },
  [OperationButtonType.RETURN]: { optType: '退回', userType: '', textArea: '退回理由' },
  [OperationButtonType.DELETE_SIGN]: { optType: '减签', userType: '减签人员', textArea: '减签理由' },
  [OperationButtonType.CANCEL]: { optType: '取消', userType: '', textArea: '取消理由' },

};
const form = ref<API.BpmCategorySaveReqVO | any>();

const [open, setOpen] = useToggle(false);
const formRef = ref<FormExpose>();
const state = reactive({
  optType: 0,
  optTypeName: '',
  id: '',
});
const processInstance = ref<any>(null);
const targetTaskDefinitionKey = ref<string>('');
const returnList = ref<any[]>([]);
const deleteSignTaskId = ref<string>('');
const deleteSignList = ref<any[]>([]);
const userList = ref<User[]>([]);
const formData = ref({
  reason: '',
});

async function onOpen(optKey: number, runningTask: any, processInstanceTemp: any) {
  // console.log('state.optType: ', optKey);
  state.optType = optKey;
  if (state.optType === (OperationButtonType.DELETE_SIGN)) {
    deleteSignList.value = runningTask?.children || [];
  }
  if (state.optType === (OperationButtonType.RETURN)) {
    const response = await getBpmTaskListByReturn({ id: runningTask?.id });
    returnList.value = response.data || [];
  }
  if (processInstanceTemp) {
    processInstance.value = processInstanceTemp;
  }
  state.optTypeName = optTypeNameMap[optKey as unknown as OperationButtonType]?.optType || '';
  state.id = runningTask?.id ?? '';
  userList.value = [];
  formData.value.reason = '';
  setOpen(true);
}

function openUserSelect() {
  selectUser({
    multiple: true,
    modelValue: userList.value,
    onSubmit: (selectedUsers: any[]) => {
      userList.value = [...selectedUsers];
    },
  });
}

function deleteUser(user: User) {
  userList.value = userList.value.filter(u => u.userId !== user.userId);
}

/** 获取减签人员标签 */
function getDeleteSignUserLabel(task: any) {
  const deptName = task?.assigneeUser?.deptName || task?.ownerUser?.deptName;
  const nickname = task?.assigneeUser?.nickname || task?.ownerUser?.nickname;
  return `${nickname} ( 所属部门：${deptName} )`;
}

const [loading, setLoading] = useToggle(false);

function onAction(type?: string) {
  if (userList.value.length === 0 && [3, 4, 5, 7].includes(state.optType)) {
    message.warning('请至少选择一个用户');
    return;
  }
  setLoading(true);
  let apiRequest: any;
  let params: any = {};
  switch (state.optType) {
    case OperationButtonType.APPROVE:
      apiRequest = postBpmTaskApprove;
      params = {
        id: state.id,
        reason: formData.value.reason,
        variables: {},
      };
      break;
    case OperationButtonType.REJECT:
      apiRequest = postBpmTaskReject;
      params = {
        id: state.id,
        reason: formData.value.reason,
      };
      break;
    case OperationButtonType.COPY:
      apiRequest = postBpmTaskCopy;
      params = {
        id: state.id,
        copyUserIds: userList.value.map(user => user.userId),
        reason: formData.value.reason,
      };
      break;
    case OperationButtonType.TRANSFER:
      apiRequest = postBpmTaskTransfer;
      params = {
        id: state.id,
        assigneeUserId: userList.value.map(u => u.userId).join(','),
        reason: formData.value.reason,
      };
      break;
    case OperationButtonType.DELEGATE:
      apiRequest = postBpmTaskDelegate;
      params = {
        id: state.id,
        delegateUserId: userList.value.map(user => user.userId).join(','),
        reason: formData.value.reason,
      };
      break;
    case OperationButtonType.ADD_SIGN:
      apiRequest = postBpmTaskCreateSign;
      params = {
        id: state.id,
        userIds: userList.value.map(user => user.userId),
        reason: formData.value.reason,
        type,
      };
      break;
    case OperationButtonType.DELETE_SIGN:
      apiRequest = postBpmTaskDeleteSign;
      params = {
        id: deleteSignTaskId.value,
        reason: formData.value.reason,
      };
      break;
    case OperationButtonType.RETURN:
      apiRequest = postBpmTaskReturn;
      params = {
        id: state.id,
        targetTaskDefinitionKey: targetTaskDefinitionKey.value,
        reason: formData.value.reason,
      };
      break;
    case OperationButtonType.CANCEL:
      apiRequest = postBpmProcessInstanceCancelByStartUser;
      params = {
        id: processInstance.value.id,
        reason: formData.value.reason,
      };
      break;
    default:
      setLoading(false);
      message.error('未知的操作类型');
  }
  apiRequest(params).then(() => {
    message.success(`操作成功`);
    emit('submit');
    close();
  }).finally(() => {
    setLoading(false);
  });
}

function close() {
  setOpen(false);
}

defineExpose({
  open: onOpen,
});
</script>

<template>
  <a-drawer
    v-model:open="open"
    :title="`流程处理 - ${state.optTypeName}`"
    placement="right"
    :width="520"
    destroy-on-close
    :footer-style="{ textAlign: 'right' }"
    @close="close"
  >
    <a-form
      ref="formRef"
      :model="form"
      :label-col="{ span: 5 }"
    >
      <a-form-item v-if="[3, 4, 5, 7].includes(state.optType)" :label="optTypeNameMap[state.optType as unknown as OperationButtonType]?.userType" name="name" :rules="[{ required: true }]">
        <div v-if="userList.length > 0" mb-4px>
          <a-tag v-for="(user, index) in userList" :key="index" closable @close="deleteUser(user)">
            {{ user.userName }}
          </a-tag>
        </div>
        <a-button type="primary" size="small" @click="openUserSelect">
          添加
        </a-button>
      </a-form-item>

      <a-form-item v-if="state.optType === OperationButtonType.DELETE_SIGN" label="减签人员" name="reason" :rules="[{ required: true }]">
        <a-select v-model="deleteSignTaskId" clearable style="width: 100%;">
          <a-select-option
            v-for="item in deleteSignList"
            :key="item.id"
            :label="getDeleteSignUserLabel(item)"
            :value="item.id"
          >
            {{ getDeleteSignUserLabel(item) }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <!-- 退回节点 -->
      <a-form-item v-if="state.optType === OperationButtonType.RETURN" label="退回节点" name="targetTaskDefinitionKey" :rules="[{ required: true }]">
        <a-select v-model:value="targetTaskDefinitionKey" clearable style="width: 100%;">
          <a-select-option
            v-for="item in returnList"
            :key="item.taskDefinitionKey"
            :value="item.taskDefinitionKey"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item :label="optTypeNameMap[state.optType as unknown as OperationButtonType]?.textArea" name="reason">
        <a-textarea v-model:value="formData.reason" :rows="3" placeholder="请输入意见" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="close">
          取消
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.CANCEL" type="primary" :loading="loading" @click="onAction()">
          确定
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.APPROVE" type="primary" :loading="loading" @click="onAction()">
          通过
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.REJECT" type="primary" :loading="loading" @click="onAction()">
          拒绝
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.COPY" type="primary" :loading="loading" @click="onAction()">
          抄送
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.TRANSFER" type="primary" :loading="loading" @click="onAction()">
          转办
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.DELEGATE" type="primary" :loading="loading" @click="onAction()">
          委派
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.ADD_SIGN" type="primary" :loading="loading" @click="onAction('before')">
          向前加签
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.ADD_SIGN" type="primary" :loading="loading" @click="onAction('after')">
          向后加签
        </a-button>
        <a-button v-if="state.optType === OperationButtonType.RETURN" type="primary" :loading="loading" @click="onAction()">
          退回
        </a-button>
      </a-space>
    </template>
  </a-drawer>
</template>
