<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { PageSearch, usePageSearch } from "/@/components/PageSearch";
import ExeclUploadModal from "./../_component/execl-files-upload/index.vue";
import ProcureImport from "./../_component/procure-import/index.vue";

import PagePower from "/@/components/PagePower/PagePower.vue";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { usePermission } from "/@/hooks/core/usePermission";
import { PageContent } from "/@/components/PageContent";
import searchFormConfig from "./config/search.config";
import contentConfig from "./config/content.config";
import { template, procureTemplate } from "./../_config/xls-template";
import { useUserInfo } from "/@/hooks/core/useUser";
import { ElMessage } from "element-plus";
import { utils, writeFile } from "xlsx";


const execlUploadModalRef = ref<InstanceType<typeof ExeclUploadModal>>(null);
const procureUploadModalRef = ref<InstanceType<typeof ProcureImport>>(null);
const { permissions, hasPermissionWithCode } = usePermission("supplyCommodityCost");
const selects = ref([]);

const { pageContentRef, handleResetClick, handleSearchClick } = usePageSearch(
  undefined,
  undefined,
  searchFormConfig
);
const { push } = useRouter();
const { isSuperUser } = useUserInfo();

function toDetail(spuCode) {
  push({
    path: "/supplyInvoiceSaleSettings/supplyCommodityCostDetail",
    query: {
      id: spuCode
    }
  });
}

function onDownloadTemplate(isProcure = false) {
  if (selects.value.length === 0) {
    ElMessage.warning("请选择至少一个商品");
    return;
  }

  const judieTemplate = isProcure ? procureTemplate : template
  const judieFilename = isProcure ? "采购批量设置类目模板" : "财务批量设置类目模板"

  const data: any[] = [];
  selects.value.forEach((item) => {
    const _template = { ...judieTemplate };

    if (isProcure) { // 采购
      _template["商品编码"] = item.spuCode;
      _template["开票商品名称"] = item.cgd_inv_good_name;
    } else {  // 财务
      _template["商品编码"] = item.spuCode;
      _template["采购类目编码"] = item.cgd_inv_cat_code;
      _template["采购开票商品名称"] = item.cgd_inv_good_name;
      _template['采购税率'] = item.cgd_inv_tax ? (((item.cgd_inv_tax.split("%"))[0]) / 100).toFixed(2) : "";

      _template['财务类目编码'] = item.inv_cat_code;
      _template['财务开票商品名称'] = item.inv_good_name;
      _template['财务税率'] = item.inv_tax ? (((item.inv_tax.split("%"))[0]) / 100).toFixed(2) : ""
    }

    data.push(_template);
  });

  //创建数据表
  const workBook = utils.book_new();
  const workSheet = utils.json_to_sheet(data);
  utils.book_append_sheet(workBook, workSheet, "sheet");

  //导出模板
  writeFile(workBook, `${judieFilename}.xlsx`, {
    bookType: "xlsx"
  });
}
</script>

<template>
  <div class="main role">
    <PagePower :is-show="hasPermissionWithCode('001')">
      <div w-full>
        <PageSearch
          :form-config="searchFormConfig"
          @search-btn-click="handleSearchClick"
          @reset-btn-click="handleResetClick"
        />

        <PageContent
          ref="pageContentRef"
          :powers="permissions"
          :content-config="contentConfig"
          @preview-btn-click="({ spuCode }) => toDetail(spuCode)"
          @selection-change="nodes => (selects = nodes)"
        >
          <template #header>
            <ElButton
              size="small"
              v-if="hasPermissionWithCode('041')"
              :icon="useRenderIcon('arrow-down-line')"
              @click="() => onDownloadTemplate(true)"
              >下载采购批量设置类目模板</ElButton
            >

            <ElButton
              size="small"
              type="primary"
              v-if="hasPermissionWithCode('042') && !isSuperUser"
              :icon="useRenderIcon('arrow-up-line')"
              @click="() => procureUploadModalRef.onDisplay()"
              >批量导入采购设置类目结果</ElButton
            >

            <ElButton
              size="small"
              v-if="hasPermissionWithCode('036')"
              :icon="useRenderIcon('arrow-down-line')"
              @click="() => onDownloadTemplate()"
              >下载财务批量设置类目模板</ElButton
            >

            <ElButton
              size="small"
              type="primary"
              v-if="hasPermissionWithCode('037') && !isSuperUser"
              :icon="useRenderIcon('arrow-up-line')"
              @click="() => execlUploadModalRef.onDisplay()"
              >批量导入财务设置类目结果</ElButton
            >
          </template>
        </PageContent>

        <ExeclUploadModal
          ref="execlUploadModalRef"
          @on-success="() => pageContentRef.onSearch()"
        />

        <ProcureImport
          ref="procureUploadModalRef"
          @on-success="() => pageContentRef.onSearch()"
        />
      </div>
    </PagePower>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
</style>
