<script setup lang="tsx">
import { h, ref } from 'vue';
import { NButton, NIcon, useMessage } from 'naive-ui';
import { AddCircleOutline as CashIcon } from '@vicons/ionicons5';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { fetchAddManageTaskInv, fetchGetFinishInvManageTask } from '@/service/api/taskmg';
import inIcon from '@/assets/imgs/盘库.png';
import { useRouterPush } from '@/hooks/common/router';
import FormulateSearch from './modules/formulate-search.vue'; // 表格数据初始化import

const { routerPushByKey } = useRouterPush();

const message = useMessage();
// 控制是否显示子组件
const showTaskDetail = ref(false);
const currentTaskData = ref<Api.InventoryTask.Inventory>({} as Api.InventoryTask.Inventory);
// 显示组件
const showTaskDetail_Click = (task: Api.InventoryTask.Inventory) => {
  showTaskDetail.value = true;
  currentTaskData.value = task;
};
// 供子组件调用的回调，用于隐藏子组件
const onTaskDetailSubmitted = () => {
  showTaskDetail.value = false;
};
const handleTaskIDClick = (task: Api.InventoryTask.Inventory) => {
  showTaskDetail_Click(task);
};

const appStore = useAppStore();
const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetFinishInvManageTask,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    TaskStatus: null, // 任务状态
    CreateUser: null, // 创建任务的用户名
    CreateTimeStart: null, // 创建时间
    CreateTimeEnd: null // 创建时间
  },
  columns: () => [
    {
      key: 'index',
      title: '序号',
      align: 'center',
      width: 48
    },
    {
      key: 'TaskID',
      title: '任务ID',
      align: 'center',
      width: 150,
      render: row => {
        if (row.TaskID === null) {
          return '未知';
        }
        return (
          <a
            style={{
              color: '#359469',
              cursor: 'pointer' // 鼠标悬浮时变为指针样式
            }}
            onClick={() => handleTaskIDClick(row)} // 点击时触发事件
          >
            {row.TaskID}
          </a>
        );
      }
    },
    {
      key: 'TaskStatus',
      title: '任务状态',
      align: 'center',
      width: 60,
      render: row => {
        if (row.TaskStatus === null) {
          return '未知';
        }
        switch (row.TaskStatus) {
          case 0:
            return '待执行';
          case 1:
            return '执行中';
          case 2:
            return '已完成';
          case 3:
            return '异常';
          default:
            return '未知';
        }
      }
    },
    {
      key: 'CreateUser',
      title: '创建用户',
      align: 'center',
      width: 120
    },
    {
      key: 'CreateTime',
      title: '创建时间',
      align: 'center',
      width: 120
    }
  ]
});
const { checkedRowKeys } = useTableOperate(data, getData);

const renderIcon = () => {
  return h(NIcon, null, {
    default: () => h(CashIcon)
  });
};

// 控制是否显示子组件
const showModalRef = ref(false);
function CreateInv() {
  showModalRef.value = true;
}
// 取消
async function onNegativeClick() {
  showModalRef.value = false;
}
// 确定创建
async function onPositiveClick() {
  showModalRef.value = false;
  const response = await fetchAddManageTaskInv();
  if (response.data?.Status === 1) {
    message.info(response.data?.msg, { duration: 5000 });
    routerPushByKey('inventory_invtodowork');
  }
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard v-if="!showTaskDetail">
      <NPageHeader subtitle="制定盘点任务计划">
        <template #title>
          <a>盘点任务</a>
        </template>
        <template #avatar>
          <NAvatar class="avatars" :src="inIcon" />
        </template>
        <template #extra>
          <NSpace>
            <NButton strong :render-icon="renderIcon" @click="CreateInv">创建盘点任务</NButton>
            <NModal
              v-model:show="showModalRef"
              preset="dialog"
              title="任务确认"
              content=" 是否确定创建盘点任务？"
              positive-text="确定创建"
              negative-text="取消"
              @positive-click="onPositiveClick"
              @negative-click="onNegativeClick"
            ></NModal>
          </NSpace>
        </template>
      </NPageHeader>
    </NCard>
    <FormulateSearch
      v-if="!showTaskDetail"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <NCard
      v-if="!showTaskDetail"
      title="历史完成盘点"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
    >
      <template #header-extra>
        <TableHeaderOperationinplan
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1500"
        :loading="loading"
        remote
        :row-key="row => row.OrderLineNumber"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
    </NCard>
    <TaskInvDetail
      v-if="showTaskDetail"
      :task-data="currentTaskData"
      @submitted="onTaskDetailSubmitted"
    ></TaskInvDetail>
  </div>
</template>

<style scoped>
.amin {
  height: 100%;
}
.amin_div {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-bottom: 2vh;
}
.avatars {
  background-color: transparent;
}
</style>
