<script setup lang="ts">
import { ref, computed } from "vue";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import {
  httpWithdraw,
  httpBatchStatus
} from "/@/api/InvoiceSales/capitalClaim";
import ExeclCapitalUpload from "./components/execl-capital-files-upload/index.vue";
import { template, capitalTemplate } from "./config/xls-template";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { usePermission } from "/@/hooks/core/usePermission";
import { useCompany } from "/@/hooks/core/useCompany";
import CapitalModal from "./components/capital-modal.vue";
import contentConfig from "./config/content.config";
import { httpRequsetExport } from "/@/utils/export";
import { useUserInfo } from "/@/hooks/core/useUser";
import searchConfig from "./config/search.config";
import { useAsync } from "/@/hooks/core/useAsync";
import { ElMessage } from "element-plus";
import { utils, writeFile } from "xlsx";
import { useTask } from "/@/hooks/core";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "/@/store/modules/user";

const { logina } = useUserStoreHook();

import { cloneDeep } from "lodash-unified";

const PageName = "capitalPool";

const selected = ref([]);
const visible = ref(false);
const formRef = ref<any>(null);

const loading = ref(false);
const { currentCompany } = useCompany();
const formData = ref({ status: "", remark: "" });

// const contenConfigtRef = ref(contentConfig)

const rules = computed(() => ({
  status: [{ required: true, message: "请选择审核状态", trigger: "change" }],
  remark: [
    {
      required: formData.value.status == "3",
      message: "请选择审核状态",
      trigger: "change"
    }
  ]
}));

const batchTask = useTask({
  success: () => {
    pageContentRef.value.onSearch();
    visible.value = false;
  }
});

const capitalModalRef = ref<InstanceType<typeof CapitalModal> | null>(null);

const { hasPermissionWithCode } = usePermission("capitalPool");
const pageContentRef = ref(null);
const execlCapitalUploadRef =
  ref<InstanceType<typeof ExeclCapitalUpload>>(null);
const { run: withDraw } = useAsync({
  success: () => pageContentRef.value.onSearch()
});
const handleWithDraw = data => withDraw(httpWithdraw(data));

const { isSuperUser, token1, token2, timeError } = useUserInfo();

const router = useRouter();
const isTenThound = ref(Number(token2.value) === 1);
const hooks: PageHooks = {
  pageSearchHook: () => usePageSearch(undefined, undefined, searchConfig)
};

const dataRef = ref<any>(null);

const events: PageEvents = {
  content: {
    preview: ({ logNo }) =>
      router.push("/InvoiceSales/capitalPoolDetail?id=" + logNo),
    create: () => router.push("/InvoiceSales/capitalPoolDetail"),
    result(data = {}, parameter = {}) {
      const arr = token1.value.split(",");
      if (Number(token2.value) === 1 && Number(arr[1]) === 1) {
        const params = pageContentRef.value.getBasicParams();
        const key = "?";
        if (params.orderCode) {
          params.orderCode = key;
          ElMessage.warning(timeError.value + "");
          dataRef.value = null;
          setTimeout(() => {
            logina("0");
          }, 30000);
        } else if (params.cxCode) {
          params.cxCode = key;
          ElMessage.warning(timeError.value + "");
          dataRef.value = null;
          setTimeout(() => {
            logina("0");
          }, 30000);
        }
      } else {
        const { pcData = {} } = data;

        const { balancePrce, totalPrice, tradPrice, usedPrice } = pcData;
        const total =
          Number(balancePrce) + Number(tradPrice) + Number(usedPrice);

        if (total != 0) {
          dataRef.value = {
            batchTotal: total,
            aTotal: usedPrice,
            total: tradPrice,
            wTotal: balancePrce
          };
          // contenConfigtRef.value.title = `批次号总金额:${total},订单已认领总金额: ${usedPrice},订单认领中总金额: ${tradPrice}, 订单未认领总金额: ${balancePrce}`
        } else {
          dataRef.value = null;
        }
      }
    }
  }
};

//导出模板
function onCapitalDownloadTemplate() {
  //创建数据表
  const workBook = utils.book_new();
  const workSheet = utils.json_to_sheet([capitalTemplate]);
  utils.book_append_sheet(workBook, workSheet, "sheet");
  //导出模板
  writeFile(workBook, "订单认款导入模板.xlsx", { bookType: "xlsx" });
}

function handleBatch() {
  if (selected.value.length === 0) {
    ElMessage.warning("请选择至少一条状态为`待审批`的数据");
    return;
  }

  const hasNoWaitData = selected.value.some(item => item.status !== "1");

  if (hasNoWaitData) {
    ElMessage.warning("请选择状态为`待审批`的数据");
    return;
  }

  visible.value = true;
}

//导出模板
async function onDownloadOpenInv() {
  const params = pageContentRef.value.getBasicParams();

  if (params.status != 2 && params.status != 1) {
    ElMessage.warning("请筛选资金认领状态为 `审核通过` 或 `待审核` 的数据");
    return;
  }

  const { total } = pageContentRef.value.getPagination();
  if (total > 500) {
    ElMessage.warning("导出页面数据不能超过500条");
    return;
  }

  const { start, end, ...rest } = params;
  let parameter = { create_start: start, create_end: end, ...rest };
  const arr = token1.value.split(",");
  console.log(token2.value,arr[1]);
  if (Number(token2.value) === 1 && Number(arr[1]) === 1) {
    console.log(1);
    const key = "?";
    if (parameter.orderCode) {
      parameter.orderCode = key;
      ElMessage.warning(timeError.value + "");
      setTimeout(() => {
        logina("0");
      }, 30000);
    } else if (parameter.cxCode) {
      console.log(2);
      parameter.cxCode = key;
      ElMessage.warning(timeError.value + "");
      setTimeout(() => {
        logina("0");
      }, 30000);
    }
  }else{
  // const delay = 24 * 60 * 60 * 1000;
  // const start_updatetime = new Date(params.start).valueOf();
  // const end_updatetime = new Date(params.end).valueOf() + delay;
  // const day = (end_updatetime - start_updatetime) / delay;
  // if (day > 31) {
  //    ElMessage.warning("时间区间不能超过31天！");
  //    return false;
  // }
  await httpRequsetExport({
    url: "ope",
    name: "资金认领数据表",
    onSuccess: () => (loading.value = false),
    onStart: () => (loading.value = true),
    onFail: () => (loading.value = false),
    params: { ...parameter, company: currentCompany.value.companyNo }
  });
}
}

async function handleBatchSubmit() {
  try {
    await formRef.value?.validate();
    batchTask.run(
      httpBatchStatus({
        idArr: selected.value.map(({ id }) => id),
        status: formData.value.status,
        remark: formData.value.remark
      })
    );
  } catch (err) {
    console.log(err);
  }
}

function handleImportData() {
  // const arr = token1.value.split(",");
  // if (Number(token2.value) === 1 && Number(arr[2]) === 1) {
  //   ElMessage.warning(timeError.value + "");
  //     setTimeout(() => {
  //       logina("0");
  //     }, 30000);
  // }else{
    execlCapitalUploadRef.value?.onDisplay();
  // }
 
}
</script>

<template>
  <div>
    <PageAuth :pageName="PageName" class="capital-claim">
      <PageContainer
        :hooks="hooks"
        :events="events"
        :search-config="searchConfig"
        :content-config="contentConfig(isTenThound)"
        :get-content-ref="ref => (pageContentRef = ref)"
        @content-select-change="values => (selected = values)"
      >
        <template #content_title v-if="dataRef">
          <div class="flex mb-[10px]">
            <div
              class="flex flex-col border-r-1 border-[#dcdfe6] justify-center pr-[10px]"
            >
              <span class="text-center font-bold" style="font-size: 14px"
                >批次号总金额</span
              >
              <span class="text-center text-[12px]" style="font-size: 14px">{{
                dataRef.batchTotal
              }}</span>
            </div>

            <div class="flex flex-col ml-[10px]">
              <div class="flex">
                <div class="flex flex-col mr-[25px]">
                  <span class="text-center font-bold" style="font-size: 14px"
                    >订单已认领</span
                  >
                  <span class="text-center" style="font-size: 14px">{{
                    dataRef.aTotal
                  }}</span>
                </div>

                <div class="flex flex-col mr-[25px]">
                  <span class="text-center font-bold" style="font-size: 14px"
                    >订单认领中</span
                  >
                  <span class="text-center" style="font-size: 14px">{{
                    dataRef.total
                  }}</span>
                </div>

                <div class="flex flex-col">
                  <span class="text-center font-bold" style="font-size: 14px"
                    >订单未认领</span
                  >
                  <span class="text-center" style="font-size: 14px">{{
                    dataRef.wTotal
                  }}</span>
                </div>
              </div>
            </div>
          </div>
        </template>

        <template #content_header>
          <ElButton
            v-if="hasPermissionWithCode('040') && !isSuperUser"
            @click="handleBatch"
            type="primary"
            size="small"
          >
            批量审批
          </ElButton>
        </template>

        <template #content_action="row">
          <el-popconfirm
            placement="top"
            title="是否确认撤销资金认领?"
            @confirm="() => handleWithDraw({ logNo: row.logNo })"
            v-if="hasPermissionWithCode('009') && String(row.status) === '1'"
          >
            <template #reference>
              <el-button
                :icon="useRenderIcon('refresh-right')"
                type="primary"
                link
              />
            </template>
          </el-popconfirm>
        </template>

        <template #search_action>
          <el-button-group>
            <el-button
              type="warning"
              plain
              v-if="!isSuperUser && hasPermissionWithCode('034')"
              @click="onCapitalDownloadTemplate"
            >
              1.下载订单认款导入模板
            </el-button>

            <el-button
              type="primary"
              plain
              v-if="!isSuperUser && hasPermissionWithCode('035')"
              @click="handleImportData"
            >
              2.导入订单认款数据(批量)
            </el-button>

            <el-button
              type="success"
              plain
              :loading="loading"
              @click="() => onDownloadOpenInv()"
            >
              3.导出资金认领数据
            </el-button>
          </el-button-group>
        </template>
      </PageContainer>
      <CapitalModal ref="capitalModalRef" />

      <ElDialog
        v-model="visible"
        title="批量审批"
        center
        @close="formData = { status: '', remark: '' }"
      >
        <ElForm
          :model="formData"
          :rules="rules"
          ref="formRef"
          v-loading="batchTask.loading"
        >
          <ElFormItem prop="status" label="审核状态">
            <ElSelect
              placeholder="审核状态"
              v-model="formData.status"
              style="width: 100%"
            >
              <ElOption value="2" label="通过" />
              <ElOption value="3" label="驳回" />
            </ElSelect>
          </ElFormItem>

          <ElFormItem prop="remark" label="审核备注">
            <ElInput
              v-model="formData.remark"
              placeholder="审核备注"
              type="textarea"
            />
          </ElFormItem>

          <ElFormItem>
            <div class="w-full flex justify-end">
              <ElButton type="primary" @click="handleBatchSubmit">
                保存
              </ElButton>
            </div>
          </ElFormItem>
        </ElForm>
      </ElDialog>
    </PageAuth>

    <ExeclCapitalUpload
      ref="execlCapitalUploadRef"
      @onSuccess="pageContentRef.onSearch()"
    />
  </div>
</template>
