<template>
  <BasicModal width="60%" v-bind="$attrs" @register="registerModal" :title="title">
    <template #footer v-if="type == 'detail'"> </template>
    <template #footer v-else>
      <template v-if="modelNodeType == NodeType.Parallel">
        <a-button type="primary" :loading="iconLoading" @click="audit('Pass')">通过</a-button>
        <a-button type="primary" :loading="iconLoading" danger @click="audit('Reject')">退回</a-button>
      </template>
      <template v-else-if="modelNodeType == NodeType.Common">
        <a-button v-if="transpondvisible" type="primary" @click="transpond">转发</a-button>
      </template>
      <template v-else-if="modelNodeType == NodeType.Branch">
        <a-button type="primary" :loading="iconLoading" @click="audit('Pass')">归档</a-button>
        <a-button type="primary" :loading="iconLoading" danger @click="audit('Reject')">退回</a-button>
      </template>
    </template>
    <div class="container">
      <div class="model-left">
        <a-descriptions :column="1" title="业务内容" bordered style="height: 38vh;overflow: scroll;">
          <a-descriptions-item label="编号">{{ detailData.businessNumber }}</a-descriptions-item>
          <a-descriptions-item label="标题">{{ detailData.title }}</a-descriptions-item>
          <a-descriptions-item label="类型">{{
            detailData.type == 1 ? '耕地破坏鉴定' : ''
          }}</a-descriptions-item>
          <a-descriptions-item label="附件">
            <div style="cursor: pointer; color: #0960bd; text-decoration: underline"
              v-for="(item, index) in detailData.attachmentsArr" :key="index" :title="item.name"
              @click="sikpBtn(item.url)">
              {{ item.name }}</div>
          </a-descriptions-item>
        </a-descriptions>
        <!-- // todo: 如果流程的上一个操作是县区进行填报，则进行选择组织架构选择部门进行转发处理
      如果上一个流程是审核员审核，则判断各位审核员的提交结果否通过审核，如果不是全部通过，则可以进行退回操作
      如果上一个流程是县区进行填报，则且存在之前的退回建议，则需要展示退回建议内容
      -->
        <div style="margin-top: 10px" v-if="commentvisible">
          <a-divider style="height: 2px; background-color: #c5cedb" />
          <a-textarea v-model:value="comment" :rows="4" placeholder="请输入审核意见" />
        </div>
      </div>
      <div class="model-right">
        <a-timeline>
          <a-timeline-item v-for="item in workitems" :key="item.workitemId" :color="getcolor(item.status)">
            <p>处理部门：<a-tag color="blue">{{ item.orgName }}</a-tag></p>
            <p>处 理 人：{{ item.handlerName }}</p>
            <p v-if="item.auditResult">处理结果：{{ item.auditResult == 'Pass' ? '通过' : '退回' }}</p>
            <p>处理备注：{{ item.comment }}</p>
            <p>处理时间：{{ item.handleTime }}</p>
          </a-timeline-item>
        </a-timeline>
      </div>
    </div>
    <TranspondModel @register="registerTranspondModel" @success="handleSuccess" :workItemId="workItemId" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { BasicModal, useModalInner, useModal } from '@/components/Modal';
import { useUserStore } from '@/store/modules/user';
import { handleWorkitem, detail } from '@/api/demo/handlingmanagement';
import { useMessage } from '@/hooks/web/useMessage';
import { getAppEnvConfig } from '@/utils/env';
import { Base64 } from 'js-base64';
import { TranspondModel } from '../page';

const { VITE_GLOB_INFO_IMAGE_URL, VITE_GLOB_FILE_PREVIEW } = getAppEnvConfig();
const envConfig = getAppEnvConfig();
const VITE_GLOB_ROLES_XQ = (envConfig as any).VITE_GLOB_ROLES_XQ;
const VITE_GLOB_ROLES_JD = (envConfig as any).VITE_GLOB_ROLES_JD;
const VITE_GLOB_ROLES_SH = (envConfig as any).VITE_GLOB_ROLES_SH;
const { createConfirm, createMessage } = useMessage();
const userStore = useUserStore();
const roles = userStore.getUserInfo.roles;
const comment = ref('');
const emit = defineEmits(['success', 'register']);
const obj = ref({});
const type = ref('');
const title = ref('');
const workitems = ref();
const workItemId = ref();
// 是否显示转发按钮
const transpondvisible = ref(false);
// 是否允许添加意见信息
const commentvisible = ref(false);
// todo: 判断监督和审核项目的按钮
enum NodeType {
  Common = 'Common',  // 提交之后待转发
  Parallel = 'Parallel',      // 转发之后待审核
  Branch = 'Branch', // 汇总之后待处置
  Other = 'Other', // 其他、默认
}
const modelNodeType = ref(NodeType.Other);
const [registerTranspondModel, { openModal: openAregisterTranspondModel }] = useModal();
const iconLoading = ref(false);

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ confirmLoading: false });
  obj.value = data.record;
  console.log('data.record', data.record)
  workItemId.value = data.record.workitemId;
  type.value = data.type ? data.type : 'audit';
  title.value = data.type == 'detail' ? '详情' : '办理';
  getDetail();
  comment.value = '';
  if (roles.includes(VITE_GLOB_ROLES_JD)) {
    // 如果是监督权限操作，且是汇总判断节点，则不展示转发按钮，否则为转发
    if (data.record.nodeType == NodeType.Common) {
      // 监督科待办：县区提交上来的
      modelNodeType.value = NodeType.Common;
      transpondvisible.value = true;
    } else if (data.record.nodeType == NodeType.Branch) {
      // 监督科待办：全部审核完成的
      transpondvisible.value = false;
      modelNodeType.value = NodeType.Branch;
    }
    else {
      transpondvisible.value = false;
      modelNodeType.value = NodeType.Other;
    }
  }
  // 如果是审核员权限操作，则不展示转发按钮
  if (roles.includes(VITE_GLOB_ROLES_SH)) {
    transpondvisible.value = false;
    if (data.record.nodeType == NodeType.Parallel) {
      commentvisible.value = true;
      modelNodeType.value = NodeType.Parallel;
    } else {
      commentvisible.value = false;
      modelNodeType.value = NodeType.Other;
    }
  }
});
const detailData = ref({});
function handlerDealFileName(path) {
  const regex = /([^/\\]+)(?=\.[^/\\]*$|$)/;
  const matchStr = path.match(regex);
  if (matchStr?.length) {
    return matchStr[0];
  }
}
const getDetail = async () => {
  detail({ businessNo: obj.value.businessNo }).then((data) => {
    console.log(data);
    detailData.value = data;
    workitems.value = data.workitems;
    detailData.value.attachmentsArr = [];
    const attachments = data.attachments ? data.attachments.split(',') : [];
    attachments.forEach((element) => {
      detailData.value.attachmentsArr.push({
        name: handlerDealFileName(element),
        url: VITE_GLOB_INFO_IMAGE_URL + element,
      });
    });
  });
};
async function audit(val) {
  if (commentvisible.value && val == 'Reject' && !comment.value) {
    return createMessage.error('审核意见不能为空');
  }
  try {
    const query = {
      comment: comment.value,
      workitemId: obj.value.workitemId,
      auditResult: val,
    };
    iconLoading.value = true;
    handleWorkitem(query).then((data) => {
      if (data) {
       setTimeout(() => {
        setModalProps({ confirmLoading: true });
        // TODO custom api
        closeModal();
        emit('success');
        iconLoading.value = false;
        return createMessage.success('审核成功');
       }, 2000);
      } else {
        iconLoading.value = false;
        return createMessage.error('审核失败');
      }
    });
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const sikpBtn = (val) => {
  const previewUrl =
    String(VITE_GLOB_FILE_PREVIEW) +
    '/onlinePreview?url=' +
    encodeURIComponent(Base64.encode(val));
  window.open(previewUrl, '_blank');
};
const getcolor = (status: string) => {
  switch (status) {
    case 'Rejected':
      return 'red';
    case 'ToDo':
      return 'blue';
    default:
      return 'green';
  }
};
const transpond = () => {
  openAregisterTranspondModel(true, {
    record: obj.value,
  });
};
function handleSuccess() {
  closeModal();
  emit('success');
}
</script>
<style lang="less" scoped>
.container {
  display: flex;

  .model-left {
    width: 60%;
  }

  .model-right {
    width: 40%;
    margin: 10px;
    overflow-y: scroll;
    height: 50vh;
  }
}

::v-deep .ant-timeline {
  padding: 10px;
}
</style>
