<script setup lang="ts">
import { convertInvoiceTitle, convertInvoiceTitleData } from "./columns";
import { httpList as httpCompanylist } from "/@/api/parameter/finance";
import { reactive, ref, nextTick, onMounted, shallowRef } from "vue";
import { httpCreate} from "/@/api/InvoiceSales/invoiceApply";
import { useCompany } from "/@/hooks/core/useCompany";
import ChooseForm from "./chooseForm/choose-form.vue";
import { FormRules, ElForm, ElMessage } from "element-plus";
import InvoiceTitle from "./invoice-title.vue";
import { useResponseHandle } from "/@/hooks";
import { useRouter } from "vue-router";

import { ADD_EDIT_FORM_RULES } from "./../../config/configs";
import { xs_inv_type_list } from "/@/utils/status";

const { push } = useRouter();
const { companyList, currentCompany } = useCompany();
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const chooseFormRef = ref<InstanceType<typeof ChooseForm> | null>(null);

const responseHandle = useResponseHandle();
const loading = shallowRef(false);
const denomination = shallowRef(0);

const initform = {
  buyer:"",
  email: "", //邮箱
  remark: "", //发票备注
  invtype: "", //开票类型
  companyNo: "", //销售方公司抬头
  exam_remark: "", //申请备注
  companyType: "01",
  platform_type: "",
  orderArr: [] //开票销售订单明细 obj：sequenceNo//销售订单编码 inv_fee//销售订单开票金额,
};

const invoiceTypes = ref([]);
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({ ...ADD_EDIT_FORM_RULES });

function onInvTypeChange() {
  const { invtype } = ruleForm.value;
  rules.email[0].required = (
    invtype === "special_electronic" || 
    invtype === "electronic" ||
    invtype === "fully_digitalized_special_electronic" ||
    invtype === "fully_digitalized_normal_electronic");
}


//设置发票抬头详情
const sellerInvoiceTitle = ref<Record<string, string>>({});
const purchaserInvoiceTitle = ref<Record<string, string>>({});

function handleInvoiceTitle(
  _isSeller: boolean,
  invoiceTitle: Record<string, string>
) {
  if (!invoiceTitle) { return _isSeller ? (sellerInvoiceTitle.value = {}) : (purchaserInvoiceTitle.value = {})}

  if (_isSeller) {
    //支持的开票方式
    const { invoiceType, denomination: _denomination } = invoiceTitle;
    denomination.value = Number(_denomination) * 10000;
    const chunks = invoiceType.split(",");
    ruleForm.value.invtype = "";
    invoiceTypes.value = xs_inv_type_list.filter(({ value }) => chunks.includes(value));
  }

  _isSeller
    ? (sellerInvoiceTitle.value = convertInvoiceTitleData(convertInvoiceTitle(invoiceTitle)))
    : (purchaserInvoiceTitle.value = convertInvoiceTitleData(convertInvoiceTitle(invoiceTitle)));
}

const setSellerInvoiceTitle = handleInvoiceTitle.bind(null, true);
const setPurchaserInvoiceTitle = handleInvoiceTitle.bind(null, false);

async function handleCompanyChange(companyNo, isSeller = true) {
  ruleForm.value[isSeller ? 'companyNo' : 'buyer']  = companyNo;
  const { code, data, message } = await httpCompanylist({ companyNo });
  nextTick(() => { if (formRef.value) {  formRef.value.validateField("companyNo");}});
  responseHandle({
    code,
    message,
    handler: () => setSellerInvoiceTitle(data.list[0])
  });
}

async function handleSupplierChange({ companyNo, companyName }) {
  ruleForm.value.buyer = companyName;

  const { code, data, message } = await httpCompanylist({ noRela: true, size:1000 });

  responseHandle({
    code,
    message,
    handler: () => {
      const item = data.list.find(({ companyNo: _code }) => _code === companyNo);
      setPurchaserInvoiceTitle(item || {});
    }
  })
}

async function handleOpenInv() {
  try {
    const { data, orderArr, totalCommonPrice, totalCommonCount } = chooseFormRef.value?.getOpenInvInfo() || ({} as any);
    const { winv_fee, payNo } = data;

    console.log(orderArr);

    await formRef.value.validate();

    if (!payNo) { 
      ElMessage.warning('请选择对账单');
      return
    }

    if (orderArr.length === 0) {
      ElMessage.warning('请至少选中一个订单')
      return
    }

    if (Number(totalCommonPrice) > Number(winv_fee)) { 
      ElMessage.warning('开票总金额不能大于未开票金额');
      return;
    }


    if (ruleForm.value.invtype === "fully_digitalized_special_electronic" || ruleForm.value.invtype === "fully_digitalized_normal_electronic") {
      if (Number(totalCommonPrice) > (1000 * 10000)) {
        return ElMessage.error("订单总金额不能超过1000万");
      }
    } else {
      if (Number(totalCommonPrice) > Number((sellerInvoiceTitle.value.denomination.split('万元'))[0] * 10000)) {
        ElMessage.warning('开票总金额不能超过销售方公司开票最大面额');
        return
       }
    }


    if (totalCommonCount > 150) { 
      ElMessage.warning('选择的通用订单不能超过150个')
      return
    }

    const { invtype, email, remark, exam_remark } = ruleForm.value
    loading.value = true;
    const { code, message } = await httpCreate({ email, payNo, remark, invtype, orderArr, exam_remark });
    loading.value = false;
    responseHandle({
       code,
       message,
       handler: () => push("/InvoiceSales/invoiceApply")
    });
  } catch (err) {
    const { warn } = console;
    warn(err);
  }
}

onMounted(() => handleCompanyChange(currentCompany.value.companyNo));
</script>

<template>
  <div class="addEditForm">
    <el-form
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      ref="formRef"
      status-icon
      size="small"
    >
      <el-row gutter="10">
        <el-col :span="12">
          <el-form-item
            label="销售方公司抬头"
            prop="companyNo"
          >
            <el-select
              disabled
              style="width: 100%"
              placeholder="销售方公司抬头"
              v-model="ruleForm.companyNo"
            >
              <el-option
                v-for="c in companyList"
                :key="c.companyCode"
                :value="c.companyCode"
                :label="c.companyName"
              />
            </el-select>
          </el-form-item>

          <InvoiceTitle :detail="sellerInvoiceTitle" />
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="购买方公司抬头"
            prop="companyNo"
          >
            <el-select
              style="width: 100%"
              placeholder="购买方公司抬头"
              disabled
              v-model="ruleForm.buyer"
            >
              <el-option
                v-for="c in companyList"
                :key="c.companyCode"
                :value="c.companyCode"
                :label="c.companyName"
              />
            </el-select>
          </el-form-item>

          <InvoiceTitle v-if="ruleForm.buyer" :detail="purchaserInvoiceTitle" />
        </el-col>

        <el-col :span="6">
          <el-form-item label="发票类型" prop="invtype">
            <el-select
              v-model="ruleForm.invtype"
              style="width: 100%"
              @change="onInvTypeChange"
              no-data-text="请选择其他销售方公司"
              placeholder="发票类型"
            >
              <el-option
                v-for="si in invoiceTypes"
                :key="si.value"
                :label="si.label"
                :value="si.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="ruleForm.email" placeholder="电子邮箱" />
          </el-form-item>
        </el-col> 

        <el-col :span="18">
          <el-form-item label="申请备注" prop="exam_remark">
            <el-input
              w-full
              v-model="ruleForm.exam_remark"
              :rows="5"
              type="textarea"
              maxlength="2000"
              placeholder="申请备注"
              show-word-limit
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="发票备注" prop="remark">
            <div w-full>
              <el-input
                w-full
                v-model="ruleForm.remark"
                :rows="3"
                type="textarea"
                maxlength="2000"
                show-word-limit
                placeholder="发票备注"
              />
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="订单对账">
            <ChooseForm 
              ref="chooseFormRef"
              @get-buyer="buyer =>  handleSupplierChange(buyer)" 
              :platformType="ruleForm.platform_type" 
             />
          </el-form-item>
        </el-col>

        <div class="flex justify-end w-full">
          <ElButton type="primary" size="" @click="handleOpenInv">保存</ElButton>
        </div>
      </el-row>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-descriptions) {
  padding: 0px !important;
  padding-left: 30px !important;
  padding-bottom: 10px !important;
}
</style>
