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

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

import { computed, nextTick, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { doRedo, taskRemove, tasksList } from '#/api/tasks/index';
import vuexStore from '#/store/vuex.js';

import InitiateProcess from '../workspace/InitiateProcess.vue';
import { columns, querySchema } from './data';

const router = useRouter();

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  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,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const formValuess = tableApi.formApi.form.values;
        return await tasksList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValuess,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'instanceId',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'web-news-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

interface ProcessFormInstance {
  submit: () => void;
  validate: (callback: (validForm: any, validProcess: any) => void) => void;
}
const processForm = ref<null | ProcessFormInstance>(null);
const isMobile = computed(() => {
  return window.screen.width < 450;
});
const loginUser = computed(() => {
  return vuexStore.state.loginUser;
});

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);
const recentlyUsed = ref<any>([]);

function resetForm() {
  selectForm.value = {
    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,
  };
}

function submitForm() {
  if (!rwjb.value) {
    message.warning('请选择添加的任务类型');
    return;
  }
  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 rwjb = ref('');
function addTask() {
  openItemDl.value = true;
  rwjb.value = '';
  nextTick(() => {
    updateBtnWidth();
  });
}
function addTasks(val: number) {
  // 普通任务，指令任务，线索核查
  if (val == 1) {
    rwjb.value = '普通任务';
  } else if (val == 2) {
    rwjb.value = '指令任务';
  } else if (val == 3) {
    rwjb.value = '线索核查';
  } else if (val == 4) {
    rwjb.value = '敏感任务';
  } else if (val == 5) {
    rwjb.value = '情指任务';
  } else if (val == 6) {
    rwjb.value = '特殊任务';
  }
  resetForm();
  openItemDl.value = true;

  recentlyUsed.value.removeByKey('formId', selectForm.value.formId);
  recentlyUsed.value.unshift(selectForm.value);
  if (recentlyUsed.value.length >= 20) {
    recentlyUsed.value.splice(1, recentlyUsed.value.length - 1);
  }
  localStorage.setItem(
    `recentlyUsed:${(loginUser.value || {}).id}`,
    JSON.stringify(recentlyUsed.value),
  );
  if (isMobile.value) {
    router.push(`/mbinitiate?code=${selectForm.value.formId}`);
  }
}

onMounted(() => {
  tableApi.formApi.updateSchema([
    {
      fieldName: 'status',
      componentProps: {
        onChange(val: number | string) {
          tableApi.reload();
        },
      },
    },
  ]);

  recentlyUsed.value = JSON.parse(
    localStorage.getItem(`recentlyUsed:${(loginUser.value || {}).id}`) || '[]',
  );
});

// 详情
function handleDetail(row: Recordable<any>) {
  router.push(`/tasks/detail?instanceId=${row.instanceId}`);
}
// 编辑
function handleEdit(row: Recordable<any>) {
  // router.push('/tasks/edit?instanceId=' + row.instanceId);
  rwjb.value = row.missionLevel;
  selectForm.value = {
    ...row,
    formId: 'wf67fdbee6c717f47dcf804ac8',
    formName: '任务流程',
  };
  console.log(row, '---------row');
  openItemDl.value = true;
  if (isMobile.value) {
    router.push(`/mbinitiate?code=${row.formId}&instanceId=${row.instanceId}`);
  }
}
// 删除
function handleDelete(row: Recordable<any>) {
  Modal.confirm({
    title: '删除',
    content: '确定删除该条数据吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      await taskRemove(row.instanceId);
      tableApi.reload();
    },
  });
}

const btncon = ref<HTMLElement | null>(null);
function updateBtnWidth() {
  const container = btncon.value;
  if (!container) return;

  const items = container.querySelectorAll('.btn-item');
  const count = items.length;

  container.className += ` btn-list${count}`;
}

// 重办
function handleRedo(row: Recordable<any>) {
  cbForm.value = {
    redoReason: '',
    taskNo: row.instanceId,
  };
  open.value = true;
}
// 重办弹框显示
const open = ref(false);
const cbForm = ref<any>({
  redoReason: '',
  taskNo: '',
});
// 重办退回确认按钮
async function handleOk() {
  if (cbForm.value.redoReason) {
    await doRedo(cbForm.value);
    open.value = false;
    await tableApi.query();
  } else {
    message.warning('请填写重办原因');
  }
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="任务中心">
      <template #toolbar-tools>
        <Space>
          <a-button type="primary" @click="addTask"> 添加任务 </a-button>
          <!-- <a-button type="primary" @click="addTasks(2)">
            {{ $t('pages.common.add') }}指令任务
          </a-button>
          <a-button type="primary" @click="addTasks(3)">
            {{ $t('pages.common.add') }}线索核查
          </a-button> -->
        </Space>
      </template>
      <template #missionStatus="{ row }">
        <Tag color="#006be6" v-if="row.missionStatus === '审批进行中'">
          {{ row.missionStatus }}
        </Tag>
        <Tag color="#87d068" v-else>{{ row.missionStatus }}</Tag>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button @click.stop="handleDetail(row)"> 详情 </ghost-button>
          <ghost-button
            @click.stop="handleRedo(row)"
            v-if="row.bizStatus == 60"
          >
            重办
          </ghost-button>
          <ghost-button @click.stop="handleEdit(row)" v-if="row.editable">
            编辑
          </ghost-button>
          <ghost-button
            danger
            @click.stop="handleDelete(row)"
            v-if="row.editable"
          >
            {{ $t('pages.common.delete') }}
          </ghost-button>
        </Space>
      </template>
    </BasicTable>
    <!-- 添加任务 -->
    <w-dialog
      v-if="!isMobile"
      :ok-loading="submitLoading"
      title="发起任务"
      close-free
      width="900px"
      v-model="openItemDl"
      ok-text="提 交"
      @cancel="openItemDl = false"
      @ok="submitForm"
    >
      <div class="btn-bg" v-if="!rwjb" ref="btncon">
        <div
          class="btn-item"
          @click="addTasks(1)"
          v-access:code="['task:putong:add']"
        >
          <img src="../../assets/image/zhichu.png" dlt="" />
          <span>普通任务</span>
        </div>
        <div
          class="btn-item"
          @click="addTasks(2)"
          v-access:code="['task:jinji:add']"
        >
          <img src="../../assets/image/huojian.png" alt="" />
          <span>指令任务</span>
        </div>
        <div
          class="btn-item"
          @click="addTasks(3)"
          v-access:code="['task:zhiling:add']"
        >
          <img src="../../assets/image/shouru.png" alt="" />
          <span>线索核查</span>
        </div>
        <div
          class="btn-item"
          @click="addTasks(4)"
          v-access:code="['task:mingan:add']"
        >
          <img src="../../assets/image/wenjian.png" alt="" />
          <span>敏感任务</span>
        </div>
        <div
          class="btn-item"
          @click="addTasks(6)"
          v-access:code="['task:mingan:add']"
        >
          <img src="../../assets/image/quanxian.png" alt="" />
          <span>特殊任务</span>
        </div>
        <div
          class="btn-item"
          @click="addTasks(5)"
          v-access:code="['task:qingzhi:add']"
        >
          <img src="../../assets/image/diannao.png" alt="" />
          <span>情指任务</span>
        </div>
      </div>
      <InitiateProcess
        ref="processForm"
        @render-ok="submitLoading = false"
        :node-id="selectForm.nodeId"
        :instance-id="selectForm.instanceId"
        :code="selectForm.formId"
        :rwjb="rwjb"
        v-if="rwjb"
        @fail="submitLoading = false"
        @ok="((openItemDl = false), (submitLoading = false))"
      />
    </w-dialog>

    <!-- 重办原因 -->
    <Modal v-model:open="open" title="重办原因" @ok="handleOk" width="600px">
      <Textarea
        v-model:value="cbForm.redoReason"
        :rows="6"
        placeholder="请输入退回意见"
      />
    </Modal>
    <!-- 修改任务 -->
    <!-- <w-dialog
      v-if="!isMobile"
      :title="`发起 - ${selectInstance.processDefName}`"
      closeFree
      width="1000px"
      v-model="openItemDl"
      okText="提 交"
      @cancel="openItemDl = false"
      @ok="submitForm"
    >
      <initiate-process
        ref="processForm"
        :node-id="selectInstance.nodeId"
        :instance-id="selectInstance.instanceId"
        :code="selectInstance.formId"
        v-if="openItemDl"
        @ok="openItemDl = false"
      ></initiate-process>
    </w-dialog> -->
  </Page>
</template>
<style>
.hide-label > label {
  width: 0 !important;
}
</style>
<style scoped lang="scss">
.btn-bg {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  height: 400px;

  .btn-item {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 23%;
    // height: 100px;
    height: 60%;
    padding: 20px;
    margin-left: 20px;
    cursor: pointer;
    background: linear-gradient(#f8f8f8, #f0f0f0);
    border-radius: 10px;

    img {
      width: 120px;
      height: 120px;
      object-fit: cover;
    }

    span {
      margin-top: 30px;
      font-size: 20px;
      color: rgba($color: #000, $alpha: 80%);
      letter-spacing: 1px;
    }
  }

  .btn-item:hover {
    background: linear-gradient(#f0f0f0, #f8f8f8);
  }
}
</style>

<style scoped lang="scss" v-access:role="['superadmin']">
.btn-list4 {
  .btn-item {
    width: 20%;
    height: 60%;
  }
}

.btn-list5 {
  height: 360px;

  .btn-item {
    width: 17%;
  }
}

.btn-list6 {
  height: 560px;

  .btn-item {
    width: 23%;
    height: 45%;
  }
}
</style>
