<!--
 * @Author: Mm
 * @Date: 2025-04-07 10:13:17
 * @LastEditors: Mm
 * @LastEditTime: 2025-06-05 17:14:36
 * 不写bug的程序员不是一个好程序员!
-->
<script setup lang="ts">
import type { Recordable } from '@vben/types';

import { computed, getCurrentInstance, nextTick, onMounted, ref } from 'vue';

import { Page, useVbenModal, type VbenFormProps } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';

import {
  Modal,
  Textarea,
  Space,
  Tag,
  message,
  Table,
  Button,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  type VxeGridProps,
} from '#/adapter/vxe-table';

import {
  dwclTasksList,
  taskRemove,
  doQianshou,
  xzdDetail,
  returnXzd,
  agreeXzd,
  finishTask,
} from '#/api/tasks/index';
import { commonDownloadExcel } from '#/utils/file/download';
import fpModal from './fp-modal.vue';
import fkModal from './fk-modal.vue';
import fpDeptModal from './fp-dept-modal.vue';
import fpUserModal from './fp-user-modal.vue';
import xzdDetailModal from './xzd-detail-modal.vue';
import { dwblColumns, queryDwspSchema } from './data';
import InitiateProcess from '../workspace/InitiateProcess.vue';
import vuexStore from '#/store/vuex.js';
import { useRouter } from 'vue-router';

const router = useRouter();
import { useUserStore } from '@vben/stores';

const userStore = useUserStore();

const userId = computed(() => {
  return userStore.userInfo?.userId;
});
const userRoles = computed(() => {
  return userStore.userInfo?.roles;
});
import { getDictOptions } from '#/utils/dict';
import { DictTag } from '#/components/dict';
const dictInfo = getDictOptions('biz_task_work_status');

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryDwspSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
  // columns: columns(),
  columns: dwblColumns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const formValuess = tableApi.formApi.form.values;
        return await dwclTasksList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValuess,
        });
      },
    },
  },

  expandConfig: {
    // showIcon:false,
    trigger: 'row',
    accordion: true,
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'dwbl-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
interface ProcessFormInstance {
  submit: () => void;
  validate: (callback: (validForm: any, validProcess: any) => void) => void;
}
const processForm = ref<ProcessFormInstance | null>(null);
const isMobile = computed(() => {
  return window.screen.width < 450;
});

const columns: any = [
  {
    title: '协作单位',
    dataIndex: 'deptName',
    key: 'deptName',
    width: 320,
    align: 'center',
  },
  {
    title: '协作人员',
    dataIndex: 'sponsorName',
    key: 'sponsorName',
    width: 150,
    align: 'center',
  },
  {
    title: '当前状态',
    dataIndex: 'status',
    width: 150,
    key: 'status',
    align: 'center',
  },
  {
    title: '协作内容',
    dataIndex: 'workContent',
    key: 'workContent',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 130,
    align: 'center',
  },
];

const submitLoading = ref(false);
const selectForm = ref<any>({
  formId: 'wf67fdbee6c717f47dcf804ac8',
  version: 7,
  processDefId: 'wf2c802379908f4ad2b04b2cbba5c295ac',
  formName: '任务流程',
  logo: {
    icon: 'bi:people-fill',
    background: '#1e90ff',
  },
  groupId: 104,
  isStop: false,
  remark: '备注说明',
  updated: '2025-04-21 16:43:26',
  nodeId: undefined,
  instanceId: undefined,
});
const openItemDl = ref(false);

function submitForm() {
  processForm.value?.validate(async (validForm: any, validProcess: any) => {
    if (!isMobile.value) {
      if (validForm && validProcess) {
        processForm.value?.submit();
        // // 延迟一下，确保提交完成后入库再刷新
        await new Promise((resolve) => setTimeout(resolve, 500));
        tableApi.reload();
      } else {
        message.warning('请完善表单/流程选项😥');
      }
    }
  });
}

// 分配弹框
const [FpModal, fpModalApi] = useVbenModal({
  connectedComponent: fpModal,
});
// 分配单位弹框
const [FpDeptModal, fpDeptModalApi] = useVbenModal({
  connectedComponent: fpDeptModal,
});
// 分配民警弹框
const [FpUserModal, fpUserModalApi] = useVbenModal({
  connectedComponent: fpUserModal,
});

// 反馈弹窗
const [FkModal, fkModalApi] = useVbenModal({
  connectedComponent: fkModal,
});

// 协作单详情弹窗
const [XzdDetailModal, xzdDetailModalApi] = useVbenModal({
  connectedComponent: xzdDetailModal,
});
//详情
function handleDetail(row: Recordable<any>) {
  router.push(
    '/tasks/detail?instanceId=' +
      row.taskNo +
      '&nodeId=' +
      row.nodeId +
      '&isdb=' +
      true,
  );
}
// 分配协助
async function handleApproval(row: Recordable<any>) {
  fpModalApi.setData({ instanceId: row.taskNo });
  fpModalApi.open();
}
// 分配单位
async function handleAllotDept(row: Recordable<any>) {
  fpDeptModalApi.setData({ instanceId: row.taskNo });
  fpDeptModalApi.open();
}
// 分配民警
async function handleAllotUser(row: Recordable<any>) {
  fpUserModalApi.setData({
    instanceId: row.taskNo,
    deptId: row.bizTaskWorkList[0].deptId,
    workId: row.bizTaskWorkList[0].id,
  });
  fpUserModalApi.open();
}

const rwjb = ref('');
// 编辑
function handleEdit(row: Recordable<any>) {
  rwjb.value = row.level;
  selectForm.value = {
    ...row,
    formId: 'wf67fdbee6c717f47dcf804ac8',
    formName: '任务流程',
    instanceId: row.taskNo,
  };
  openItemDl.value = true;
  if (isMobile.value) {
    router.push(`/mbinitiate?code=${row.formId}&instanceId=${row.instanceId}`);
  }
}
// 签收
async function handleQianShou(row: any) {
  Modal.confirm({
    title: '提示',
    content: '确认要签收当前任务吗？',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    async onOk() {
      await doQianshou({ taskNo: row.taskNo });
      await tableApi.query();
    },
    onCancel() {},
  });
}
// 反馈
async function handleFankui(row: Recordable<any>) {
  fkModalApi.setData({
    instanceId: row.taskNo,
    workId: row.bizTaskWorkList[0].id,
  });
  fkModalApi.open();
}

// 协作单详情
async function handleXzdDetail(row: Recordable<any>) {
  xzdDetailModalApi.setData({
    id: row.id,
  });
  xzdDetailModalApi.open();
}
// 协作单弹框显示
const open = ref(false);
const xzdForm = ref<any>({
  spContent: '',
  id: '',
  taskNo: '',
});
// 协作单退回确认按钮
async function handleOk() {
  if (xzdForm.value.spContent) {
    await returnXzd(xzdForm.value);
    open.value = false;
    await tableApi.query();
  } else {
    message.warning('请填写退回意见');
  }
}
// 协作单退回
async function handleXzdReturn(row: Recordable<any>) {
  xzdForm.value = {
    spContent: '',
    id: row.id,
    taskNo: row.taskNo,
  };
  open.value = true;
}
// 协作单签收
async function handleXzdAgree(row: any) {
  Modal.confirm({
    title: '提示',
    content: '确认要签收当前协作单的反馈吗？',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    async onOk() {
      await agreeXzd({ id: row.id, taskNo: row.taskNo });
      await tableApi.query();
    },
    onCancel() {},
  });
}

// 任务办结
async function handleFinish(row: any) {
  Modal.confirm({
    title: '提示',
    content: '确认要办结当前的任务吗？',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    async onOk() {
      await finishTask({ taskNo: row.taskNo });
      await tableApi.query();
    },
    onCancel() {},
  });
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="待我办理任务">
      <template #toolbar-tools>
        <Space>
          <a-button>
            {{ $t('pages.common.export') }}
          </a-button>
        </Space>
      </template>
      <!-- <template #missionStatus="{ row }">
        <span  v-if="row.startUser.name == userName">
          <Tag color="red">审批被驳回,请修改后提交</Tag>
        </span>
        <span v-else>
          <Tag color="#006be6" v-if="row.missionStatus === '审批进行中'">{{
            row.missionStatus
          }}</Tag>
          <Tag color="#87d068" v-else>{{ row.missionStatus }}</Tag>
        </span>
      </template> -->
      <template #expand_content="{ row }">
        <div
          style="width: 100%; padding: 10px 15px"
          v-if="row.bizTaskWorkList && row.bizTaskWorkList.length > 0"
        >
          <Table
            size="small"
            :dataSource="row.bizTaskWorkList"
            :columns="columns"
            :pagination="false"
            bordered
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <Tag
                  :title="record.spContent"
                  color="red"
                  v-if="record.status == 5"
                  >被中心驳回</Tag
                >
                <DictTag
                  v-else
                  :dicts="dictInfo"
                  :value="record.status"
                ></DictTag>
              </template>

              <template v-else-if="column.key === 'action'">
                <span>
                  <Button
                    type="link"
                    style="padding: 0 5px"
                    @click.stop="handleXzdDetail(record)"
                    >详情</Button
                  >

                  <Button
                    type="link"
                    style="padding: 0 5px"
                    @click.stop="handleQianShou(row)"
                    v-if="record.status == 1&&record.sponsorId==userId"
                  >
                    签收
                  </Button>
                  <Button
                    type="link"
                    style="padding: 0 5px"
                    @click.stop="handleFankui(row)"
                    v-if="(record.status == 2||record.status == 3||record.status==5)&&record.sponsorId==userId"
                  >
                    反馈
                  </Button>
                  <Button
                    type="link"
                    style="padding: 0 5px"
                    @click.stop="handleXzdAgree(record)"
                    v-if="
                      (userRoles?.includes('hezhanleader') || userRoles?.includes('qinzhizhongxin')) && record.status == 3
                    "
                    >签收</Button
                  >
                  <Button
                    type="link"
                    style="padding: 0 5px"
                    v-if="
                      (userRoles?.includes('hezhanleader') || userRoles?.includes('qinzhizhongxin')) && record.status == 3
                    "
                    @click.stop="handleXzdReturn(record)"
                    >退回</Button
                  >
                </span>
              </template>
            </template>
          </Table>
        </div>
        <span v-else></span>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button @click.stop="handleDetail(row)"> 详情 </ghost-button>
          <ghost-button
            v-if="row.status == 11 && row.applyUserId == userId"
            @click.stop="handleEdit(row)"
          >
            编辑
          </ghost-button>
          <ghost-button
            @click.stop="handleApproval(row)"
            v-if="row.status == 30 && (row.level == '普通任务' || row.level == '敏感任务')"
          >
            分配协助
          </ghost-button>
          <ghost-button
            @click.stop="handleAllotDept(row)"
            v-if="row.status == 30 && (row.level == '指令任务' || row.level == '线索核查' || row.level == '特殊任务' || row.level == '情指任务')"
          >
            分配单位
          </ghost-button>
          <ghost-button
            v-if="row.status == 31 && userRoles?.includes('leader')"
            @click.stop="handleAllotUser(row)"
          >
            分配民警
          </ghost-button>
          <ghost-button @click.stop="handleFinish(row)" v-if="row.status == 51">
            办结
          </ghost-button>
        </Space>
      </template>
    </BasicTable>
    <!-- 分配协作单弹框 -->
    <FpModal @reload="tableApi.query()" />
    <!-- 分配单位弹框 -->
    <FpDeptModal @reload="tableApi.query()" />
    <!-- 反馈弹窗 -->
    <FkModal @reload="tableApi.query()" />

    <!-- 分配民警弹框 -->
    <FpUserModal @reload="tableApi.query()" />

    <!-- 协作单详情弹框 -->
    <XzdDetailModal @reload="tableApi.query()" />
    <!-- 协作单退回弹框 -->
    <Modal v-model:open="open" title="协作单退回" @ok="handleOk" width="600px">
      <Textarea
        v-model:value="xzdForm.spContent"
        :rows="6"
        placeholder="请输入退回意见"
      />
    </Modal>
    <!-- 编辑任务 -->
    <w-dialog
      v-if="!isMobile"
      :ok-loading="submitLoading"
      :title="`发起 - ${selectForm.formName}`"
      closeFree
      width="900px"
      v-model="openItemDl"
      okText="提 交"
      @cancel="openItemDl = false"
      @ok="submitForm"
    >
      <initiate-process
        ref="processForm"
        :isCxtj="true"
        @render-ok="submitLoading = false"
        :node-id="selectForm.nodeId"
        :task-id="selectForm.taskId"
        :instance-id="selectForm.instanceId"
        :code="selectForm.formId"
        v-if="openItemDl"
        @fail="submitLoading = false"
        @ok="((openItemDl = false), (submitLoading = false))"
      />
    </w-dialog>
  </Page>
</template>
