<!--
 * @Author: hcc han_chen301@163.com
 * @Date: 2025-05-24 17:21:02
 * @LastEditors: Mm
 * @LastEditTime: 2025-06-19 15:31:47
 * @remarker: 
-->
<script lang="ts" setup>
import type {
  WorkbenchProjectItem,
  WorkbenchQuickNavItem,
  WorkbenchTodoItem,
} from '@vben/common-ui';

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

import {
  AnalysisChartCard,
  AnalyticsTaskStatistics,
  WorkbenchQuickNav,
} from '@vben/common-ui';
import {
  SvgDclIcon,
  SvgDshIcon,
  SvgWfqdIcon,
  SvgYclIcon,
  SvgYspIcon,
} from '@vben/icons';
import { openWindow } from '@vben/utils';

import { Card, CardContent, CardHeader, CardTitle } from '@vben-core/shadcn-ui';

import { message, Tag } from 'ant-design-vue';
import { Vue3SeamlessScroll } from 'vue3-seamless-scroll';

import { getAllMenusApi } from '#/api';
import { getHomeStatistics } from '#/api/statistics/statistics';
import vuexStore from '#/store/vuex.js';
// import { renderText } from '#/utils/render';
import { getDictOptions } from '#/utils/dict';

import InitiateProcess from '../../workspace/InitiateProcess.vue';
import AnalyticsTrends from './analytics-trends.vue';
import AnalyticsVisitsData from './analytics-visits-data.vue';
import AnalyticsVisitsSource from './analytics-visits-source.vue';

const dictInfo = getDictOptions('biz_task_log_type');

const router = useRouter();
interface ProcessFormInstance {
  submit: () => void;
  validate: (callback: (validForm: any, validProcess: any) => void) => void;
}
interface PropsItem {
  names?: string[];
  jqrwzs?: number[];
  ajrwzs?: number[];
  zxrwzs?: number[];
  qtrwzs?: number[];
  rwzs?: number[];
}
const homeStatistics = ref<any>({});
const everydayItems = ref<PropsItem>({});
const taskTypeData = ref<any>([]);
const taskLevelData = ref<any>([]);

const todoItems = ref<WorkbenchTodoItem[]>([]);

const quickNavItems = ref<WorkbenchQuickNavItem[]>([
  {
    color: '#1fdaca',
    icon: 'ion:paper-plane-outline',
    title: '新建任务',
    url: '/',
  },
]);

const initData = async () => {
  homeStatistics.value = await getHomeStatistics();
  const backMenuList = await getAllMenusApi();
  backMenuList.forEach((item: any) => {
    item.children.forEach((child: any) => {
      if (child.meta.title === '我发起的') {
        quickNavItems.value.push({
          color: '#bf0c2c',
          icon: markRaw(SvgWfqdIcon),
          title: '我发起的',
          url: `/${child.component}`,
        });
      }
      if (child.meta.title === '待我审批') {
        quickNavItems.value.push({
          color: '#bf0c2c',
          icon: markRaw(SvgDshIcon),
          title: '待我审批',
          url: `/${child.component}`,
        });
      }
      if (child.meta.title === '待我办理') {
        quickNavItems.value.push({
          color: '#bf0c2c',
          icon: markRaw(SvgDclIcon),
          title: '待我办理',
          url: `/${child.component}`,
        });
      }
      if (child.meta.title === '已审批的') {
        quickNavItems.value.push({
          color: '#bf0c2c',
          icon: markRaw(SvgYspIcon),
          title: '已审批的',
          url: `/${child.component}`,
        });
      }
      if (child.meta.title === '已处理的') {
        quickNavItems.value.push({
          color: '#bf0c2c',
          icon: markRaw(SvgYclIcon),
          title: '已处理的',
          url: `/${child.component}`,
        });
      }
    });
  });
  everydayItems.value = {
    names: homeStatistics.value.mrrwqs.map((item: any) => item.drq),
    jqrwzs: homeStatistics.value.mrrwqs.map((item: any) => item.jqrws),
    ajrwzs: homeStatistics.value.mrrwqs.map((item: any) => item.ajrws),
    zxrwzs: homeStatistics.value.mrrwqs.map((item: any) => item.zxrws),
    qtrwzs: homeStatistics.value.mrrwqs.map((item: any) => item.qtrws),
    rwzs: homeStatistics.value.mrrwqs.map((item: any) => item.rwzs),
  };
  taskTypeData.value = [
    { name: '案件任务', value: homeStatistics.value.ajrws },
    { name: '警情任务', value: homeStatistics.value.jqrws },
    { name: '专项任务', value: homeStatistics.value.zxrws },
    { name: '其他任务', value: homeStatistics.value.qtrws },
  ];
  taskLevelData.value = [
    { name: '普通任务', value: homeStatistics.value.ptrws },
    { name: '指令任务', value: homeStatistics.value.jjrws },
    { name: '专项任务', value: homeStatistics.value.zxrws },
    { name: '线索核查', value: homeStatistics.value.zlrws },
    { name: '敏感任务', value: homeStatistics.value.mgrws },
    { name: '情指任务', value: homeStatistics.value.qzrws },
  ];
  const dictValue = ref<string>('');

  homeStatistics.value?.rwdt.forEach((item: any) => {
    dictInfo.forEach((dict: any) => {
      if (dict.value === item.type) {
        dictValue.value = dict.label;
      }
    });
    todoItems.value.push({
      completed: false,
      content: item.dept_name + item.user_name + item.remark,
      date: item.optime,
      type: dictValue.value,
      title: item.task_title,
      task_no: item.task_no,
    });
  });
};

// 这是一个示例方法，实际项目中需要根据实际情况进行调整
function navTo(nav: WorkbenchProjectItem | WorkbenchQuickNavItem) {
  if (nav.url?.startsWith('http')) {
    openWindow(nav.url);
    return;
  }
  if (nav.title === '新建任务') {
    addTask();
    return;
  }
  if (nav.url?.startsWith('/')) {
    router.push(nav.url).catch((error) => {
      console.error('Navigation failed:', error);
    });
  } else {
    console.warn(`Unknown URL for navigation item: ${nav.title} -> ${nav.url}`);
  }
}

// 新建任务弹窗相关
const loginUser = computed(() => {
  return vuexStore.state.loginUser;
});
const openItemDl = ref(false);
const processForm = ref<null | ProcessFormInstance>(null);
const isMobile = computed(() => {
  return window.screen.width < 450;
});
const btncon = ref<HTMLElement | null>(null);
const rwjb = ref('');
const submitLoading = ref(false);

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 addTask() {
  openItemDl.value = true;
  rwjb.value = '';
  nextTick(() => {
    updateBtnWidth();
  });
}
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));
      } else {
        message.warning('请完善表单/流程选项😥');
      }
    }
  });
}
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 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,
  };
}
const addTasks = (val: number) => {
  // 普通任务，紧急任务，线索核查
  switch (val) {
    case 1: {
      rwjb.value = '普通任务';

      break;
    }
    case 2: {
      rwjb.value = '指令任务';

      break;
    }
    case 3: {
      rwjb.value = '线索核查';

      break;
    }
    case 4: {
      rwjb.value = '敏感任务';

      break;
    }
    case 5: {
      rwjb.value = '情指任务';

      break;
    }
    case 6: {
      rwjb.value = '特殊任务';

      break;
    }
    // No default
  }

  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}`);
  }
};

const componentKey = ref(0);
onMounted(async () => {
  // 获取首页统计数据
  initData();
  await nextTick(); // 等待DOM更新
  componentKey.value += 1; // 强制更新Vue3SeamlessScroll组件
});
</script>

<template>
  <div class="p-3">
    <div class="w-full md:flex">
      <!-- <AnalysisOverview class="md:w-3/4" :items="overviewItems" /> -->
      <AnalyticsTaskStatistics
        class="mr-2 md:w-3/4"
        :overview-items="homeStatistics"
      />
      <WorkbenchQuickNav
        :items="quickNavItems"
        class="mt-3 md:w-1/4 lg:mt-0"
        title="快捷导航"
        @click="navTo"
        :add-task="addTask"
      />
    </div>
    <div class="mt-3 flex flex-col lg:flex-row">
      <div class="mr-2 w-full lg:w-3/4">
        <!-- <AnalysisChartsTabs :tabs="chartTabs" class="">
          <template #trends>
            <AnalyticsTrends
              :everyday-task="everydayItems"
            />
          </template>
          <template #visits>
            <AnalyticsVisits />
          </template>
        </AnalysisChartsTabs> -->
        <AnalysisChartCard class="md:mt-0" title="每日任务趋势">
          <AnalyticsTrends :everyday-task="everydayItems" />
        </AnalysisChartCard>
        <div class="mt-3 w-full md:flex">
          <AnalysisChartCard
            class="md:mr-2 md:mt-0 md:w-1/2"
            title="任务类型统计"
          >
            <AnalyticsVisitsData :task-type-data="taskTypeData" />
          </AnalysisChartCard>
          <AnalysisChartCard class="md:mt-0 md:w-1/2" title="任务级别统计">
            <AnalyticsVisitsSource :task-level-data="taskLevelData" />
          </AnalysisChartCard>
        </div>
      </div>
      <div class="w-full lg:w-1/4">
        <Card style="height: 800px">
          <CardHeader class="py-4">
            <CardTitle class="text-lg">任务动态</CardTitle>
          </CardHeader>
          <CardContent class="flex flex-wrap p-5 pt-0">
            <ul
              class="divide-border w-full divide-y"
              role="list"
              style="height: 700px; overflow: hidden"
            >
              <Vue3SeamlessScroll
                :list="todoItems"
                :step="1"
                :hover="true"
                class="scroll-container"
                :key="componentKey"
                :limit-scroll-num="8"
                :single-height="90"
                :copy-num="5"
                v-if="todoItems.length > 0"
              >
                <li
                  v-for="item in todoItems"
                  :key="item.date"
                  :class="{
                    'select-none line-through opacity-60': item.completed,
                  }"
                  class="flex cursor-pointer justify-between gap-x-6 py-5"
                  style="border-bottom: 1px solid hsl(var(--border))"
                  @click="
                    () => {
                      router.push(`/tasks/detail?instanceId=${item.task_no}`);
                    }
                  "
                >
                  <Tag color="error" style="position: absolute; right: 0">
                    {{ item.type }}
                  </Tag>
                  <div class="flex min-w-0 items-center gap-x-4">
                    <div class="min-w-0 flex-auto">
                      <p
                        class="text-foreground text-sm font-semibold leading-6"
                      >
                        {{ item.title }}
                      </p>
                      <p
                        class="text-foreground/80 *:text-primary mt-1 truncate text-xs leading-5"
                      >
                        {{ item.content }}
                      </p>
                    </div>
                  </div>
                  <div
                    class="hidden h-full shrink-0 sm:flex sm:flex-col sm:items-end"
                  >
                    <span class="text-foreground/80 mt-6 text-xs leading-6">
                      {{ item.date }}
                    </span>
                  </div>
                </li>
              </Vue3SeamlessScroll>
            </ul>
          </CardContent>
        </Card>
      </div>
    </div>
    <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>
  </div>
</template>
<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>
.scroll-container {
  width: 100%;
  overflow: hidden;
}

.item {
  padding: 12px;
  margin: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
</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>
