<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { PageSearch, usePageSearch } from "/@/components/PageSearch";
import { PageContent } from "/@/components/PageContent";
import searchFormConfig from "./config/search.config";
import contentConfig from "./config/content.config";
import PagePower from "/@/components/PagePower/PagePower.vue";
import { usePermission } from "/@/hooks/core/usePermission";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import ExeclUploadModal from "./../_component/execl-files-upload/index.vue";
import ProcureImport from "./../_component/procure-import/index.vue";
import { template, procureTemplate } from "./../_config/xls-template";
import { utils, writeFile } from "xlsx";
import { ElMessage } from "element-plus";
import { useUserInfo } from "/@/hooks/core/useUser";

import { httpRequsetExport } from "/@/utils/export";

import dayjs from "dayjs"
import { useCompany } from "/@/hooks/core/useCompany";

const execlUploadModalRef = ref<InstanceType<typeof ExeclUploadModal>>(null);
const procureUploadModalRef = ref<InstanceType<typeof ProcureImport>>(null);

const { permissions, hasPermissionWithCode } = usePermission("consultingCost");
const selects = ref([]);

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

const { currentCompany } = useCompany()

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

const mapTag = {
  "1": "免税",
  "2": "不征税",
  "3": "零税率"
};

const mapDiscount = {
  "1": "是",
  "0": "否"
};

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.good_name;
      _template["买入方公司编码"] = item.supplierNo;
      _template["买入方公司名称"] = item.supplierName;
      _template["卖出方公司编码"] = item.cgd_supplierNo;
      _template["卖出方公司名称"] = item.cgd_supplierName;
      _template["开票商品名称"] = item.cgd_inv_good_name;
    } else {  // 财务
      _template["商品编码"] = item.spuCode;
      _template["商品名称"] = item.good_name;
      _template["买入方公司编码"] = item.supplierNo;
      _template["买入方公司名称"] = item.supplierName;
      _template["卖出方公司编码"] = item.cgd_supplierNo;
      _template["卖出方公司名称"] = item.cgd_supplierName;
      _template["采购类目编码"] = item.cgd_inv_cat_code;
      _template['采购类目名称'] = item.cgd_inv_cat_name;
      _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_cat_name;
      _template['财务开票商品名称'] = item.inv_good_name;
      _template['财务税率'] = item.inv_tax ? (((item.inv_tax.split("%"))[0]) / 100).toFixed(2) : ""

      _template['税率标识'] = item.inv_tag && item.inv_tag !== "0" ? mapTag[item.inv_tag] : "";
      _template["是否有优惠政策"] = Number(item.status) >= 2 ? mapDiscount[item.is_discount] : "";
      _template["增值税管理内容"] = item.addTax;
    }

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

const _loading = ref(false);
async function handleExportPage() {
  const params = pageContentRef.value.getBasicParams();
  if (!params.start || !params.end) {
    ElMessage.warning('请选择导出的时间区间')
    return
  }

  const start = dayjs(params.start);
  const end = dayjs(params.end);
  const diffDay = start.diff(end, 'days')
  const startDays = start.daysInMonth();
  const endDays = end.daysInMonth();

  if (Math.abs(diffDay) > (startDays + endDays)) {
    ElMessage.warning('导出的时间区间不能超过两个月')
    return
  }

  await httpRequsetExport({
    url: "/admin/good/export",
    name: "咨询成交类目",
    onStart: () => (_loading.value = true),
    onSuccess: () => (_loading.value = false),
    onFail: () => (_loading.value = false),
    params: { isZx: 1, ...params, companyNo: currentCompany.value.companyNo, isChild: 0 },
    admin: false
  });
}
</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" :icon="useRenderIcon('arrow-up-line') "
              v-if="hasPermissionWithCode('037') && !isSuperUser" @click="() => execlUploadModalRef.onDisplay()">
              批量导入财务设置类目结果</ElButton>

            <ElButton type="primary" @click="handleExportPage" size="small" v-if="hasPermissionWithCode('048')"
              :loading="_loading">导出
            </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>
