<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import OrderImportModal from "./components/OrderImportModal/index.vue"
import NotOrderImportModal from "./components/NotOrderImportModal/index.vue"
import { useRenderIcon } from "/@/components/ReIcon/src/hooks"
import contentConfig from "./config/content.config";
import searchConfig from "./config/search.config";
import { utils, writeFile } from "xlsx";
import { ElButton, ElDialog, ElDropdown, ElMessage } from "element-plus";
import { useUserInfo } from "/@/hooks/core/useUser";

import { orderTemplate } from "./components/OrderImportModal/columns-config"
import { notOrderTemplate } from "./components/NotOrderImportModal/columns-config"
import { useTask } from "/@/hooks/core";
import { httpDelete } from "/@/api/invoiceInOut/inOutManager";
import BasicDescriptions from "/@/components/BasicDescriptions";
import { orderGoodColumns } from "./config/columns";

import { httpDetail } from "/@/api/invoiceInOut/inOutManager";
import { httpProductDetail } from "/@/api/invoiceInOut/inventoryCheck";
import ProductDetail from "/@/components/ProductDetail/index.vue"


const PageName = "inOutManager";
const router = useRouter();

const state = reactive({ orderImportVisible: false, notOrderImportVisible: false, detailVisible: false, productVisible: false })
const hooks: PageHooks = { pageSearchHook: () => usePageSearch(undefined, undefined, searchConfig) };
const productIndex = ref();
const detailTask = useTask();
const productDetailTask = useTask();

const pageContentRef = ref(null)

const selection = ref([])

const deleteTask = useTask({
  success() {
    ElMessage.success('取消成功')
    pageContentRef?.value.onSearch()
  }
})

const { isSuperUser } = useUserInfo()

const events: PageEvents = {
  content: {
    create: () => router.push('/invoiceInOut/clinetCDetail'),
    preview: ({ id }) =>  {
      state.detailVisible = true
      detailTask.run(httpDetail({ id }))
    }
  }
};

function handleDownloadTemplate(isOrder = false){
  const data = isOrder ? orderTemplate : notOrderTemplate
  const name = isOrder ? '出库模板-订单商品(C端订单).xlsx' : '出库模板-非订单商品(C端订单).xlsx'

  const workBook = utils.book_new()
  const workSheet = utils.json_to_sheet(data)
  utils.book_append_sheet(workBook, workSheet, 'sheet');
  writeFile(workBook, name, { bookType: 'xlsx' })
}

function handleRefresh() {
  if (selection.value.length === 0) {
    ElMessage.warning('请选择至少一条状态为 "待审核" 或 "异常" 的数据')
    return
  }

  const isStatusNotOk = selection.value.some(({ status }) => status != '1' && status != '4')

  if (isStatusNotOk) {
    ElMessage.warning('只能选择状态为 "待审核" 或 "异常" 的数据')
    return
  }

  deleteTask.run(httpDelete({ id: selection.value.map(({ id }) => id) }))
}

function handleShowDetail(id, index) {
  state.productVisible = true
  productIndex.value = index
  console.log(id, index)

  productDetailTask.run(httpProductDetail({ id }))
}
</script>

<template>
  <PageAuth :pageName="PageName">
    <PageContainer :hooks="hooks" :events="events" :searchConfig="searchConfig" :contentConfig="contentConfig"
      :get-content-ref="ref => pageContentRef = ref" @content-select-change="selects => selection = selects">
      <template #content_header>
        <ElButton style="margin-right: 10px" size="small" type="primary" @click="handleRefresh">批量取消
        </ElButton>

        <ElDropdown v-if="!isSuperUser" >
          <ElButton 
            size="small" 
            type="primary" 
            style="margin-right: 10px;margin-top:1px"
            :icon="useRenderIcon('arrow-up-line')">出库数据导入(C端订单)
          </ElButton>

          <template #dropdown>
            <ElDropdownItem @click="state.orderImportVisible = true">订单导入</ElDropdownItem>
            <ElDropdownItem @click="state.notOrderImportVisible = true">非订单导入</ElDropdownItem>
          </template>
        </ElDropdown>

        <ElDropdown>
          <ElButton size="small" style="margin-right: 10px;margin-top:1px" :icon="useRenderIcon('arrow-down-line')">
            出库模板下载(C端订单)
          </ElButton>

          <template #dropdown>
            <ElDropdownItem @click="handleDownloadTemplate(true)">订单导入</ElDropdownItem>
            <ElDropdownItem @click="handleDownloadTemplate(false)">非订单导入</ElDropdownItem>
          </template>
        </ElDropdown>


        <ElButton v-if="!isSuperUser" size="small" type="primary" @click="router.push('/invoiceInOut/clinetCDetail')">
          批量处理
        </ElButton>
      </template>
    </PageContainer>

    <OrderImportModal v-model:visible="state.orderImportVisible" @refresh="pageContentRef?.onSearch()" />

    <NotOrderImportModal v-model:visible="state.notOrderImportVisible" @refresh="pageContentRef?.onSearch()" />

    <ElDialog v-model="state.detailVisible" title="C端无发票订单出库详情" center>
      <div v-loading="detailTask.loading" style="overflow:hidden;margin-bottom: 30px;">
        <BasicDescriptions v-if="detailTask.data"
          :columns="orderGoodColumns(handleShowDetail, detailTask.data.ProductRela.length !== 0 )" :data="detailTask.data" />
      </div>
    </ElDialog>


    <ElDialog center title="商品详情" v-model="state.productVisible" style="overflow: hidden" :append-to-body="true">
      <div v-loading="productDetailTask.loading">
        <ProductDetail style="overflow: hidden" v-if="productDetailTask.data" :data="productDetailTask.data"
          :num="detailTask.data.ProductRela[productIndex].num"
          :time="detailTask.data.ProductRela[productIndex].create_time" 
          :name="detailTask.data.ProductRela[productIndex].apply_name"
          />
      </div>
    </ElDialog>
  </PageAuth>
</template>
