<script setup lang="ts">
import { FormRules, ElForm, ElMessage } from "element-plus";
import { reactive, ref, watchEffect, watch } from "vue";
import { httpAdd } from "/@/api/InvoiceSales/invoiceApply";
import RemoteSelect from "/@/components/RemoteSelect";
import { httpInvoiceList } from "/@/api/InvoiceSales/invoiceApply";
import { httpList as httpCompanylist } from "/@/api/parameter/finance";
import OrderDialog from "./order-dialog.vue";
import EditOrder from "./edit-order.vue";
import { useResponseHandle } from "/@/hooks";
import { useRouter } from "vue-router";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { inv_type_list } from "./../../status";
import InvoiceTitle from "./invoice-title.vue";
import { convertInvoiceTitle, convertInvoiceTitleData } from "./columns";
import { ADD_EDIT_FORM_RULES, requriedEmail } from "./../../config/configs";

enum FROM_TYPE {
  order = "order",
  invoice = "invoice"
}

const TYPE = ref<FROM_TYPE>(FROM_TYPE.order);
const { push } = useRouter();

const modelRef = ref<InstanceType<typeof OrderDialog>>(null);
const editOrderRef = ref<InstanceType<typeof EditOrder>>(null);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const mapSequenceNoToInvfee = ref<Record<string, any>>({});
const responseHandle = useResponseHandle();
const loading = ref(false);
const orderList = ref([]);

const max = 150;

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

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

function handleShowEditModal(_, row: any) {
  editOrderRef.value.onDisplay({
    row
  });
}

function handleEdit({ row, inv_fee, num }) {
  mapSequenceNoToInvfee.value[row.sequenceNo] = {
    inv_fee,
    num
  };
}

const removeRemarkPo = (poCode: string, index: number) => {
  const isLast = index === orderList.value.length - 1;
  const isOnly = orderList.value.length === 1;

  if (isOnly)
    return (ruleForm.value.remark = ruleForm.value.remark
      .split(poCode)
      .join(""));

  ruleForm.value.remark = ruleForm.value.remark
    .split(isLast ? ";" + poCode : poCode + ";")
    .join("");
};

const handleDelete = (index: number) => {
  const { sequenceNo, poCode } = orderList.value[index];
  removeRemarkPo(poCode, index);
  delete mapSequenceNoToInvfee.value[sequenceNo];
  orderList.value.splice(index, 1);
};

function generatorOrderArr() {
  const keys = Object.keys(mapSequenceNoToInvfee.value);
  const orderArr = keys.map(sequenceNo => {
    const { inv_fee, num } = mapSequenceNoToInvfee.value[sequenceNo];

    return {
      sequenceNo,
      inv_fee,
      num
    };
  });

  return { orderArr };
}

function handleSave() {
  formRef.value.validate(async isValid => {
    if (!isValid) return;
    if (ruleForm.value.remark.length > 184) {
      return ElMessage.error("发票备注不能超过184个字符");
    }

    if (orderList.value.length > max) {
      return ElMessage.error(`订单数量不能超过${max}个`);
    }

    const { code, message } = await httpAdd({
      ...ruleForm.value,
      ...generatorOrderArr()
    });

    responseHandle({
      code,
      message,
      handler: () => push("/InvoiceSales/invoiceApply")
    });
  });
}

function menu_type_change() {
  const { invtype } = ruleForm.value;
  rules.email[0].required = invtype === "26" || invtype === "27";
}

function handleAddModalShow() {
  if (!ruleForm.value.companyNo) return ElMessage.warning("请选择销售公司抬头");

  modelRef.value.show(ruleForm.value.companyNo);
}

function handleAddOrder(list) {
  ruleForm.value.remark = "";

  list.forEach((item, index) => {
    const { sequenceNo, winv_fee, wsendNum, poCode } = item;

    if (!mapSequenceNoToInvfee.value[sequenceNo]) {
      mapSequenceNoToInvfee.value[sequenceNo] = {
        inv_fee: winv_fee,
        num: wsendNum
      };
      orderList.value.push(item);
      ruleForm.value.remark += index === 0 ? poCode : ";" + poCode;
    }
  });
}

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

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

    return (purchaserInvoiceTitle.value = {});
  }

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

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

watchEffect(() => {
  const { invtype } = ruleForm.value;
  if (["3", "4"].includes(invtype)) {
    rules.email[0].required = true;
    rules.email[0].validator = requriedEmail;
  } else {
    rules.email[0].required = false;
    rules.email[0].validator = () => true;
  }
});

watch(
  () => ruleForm.value.companyNo,
  () => {
    ruleForm.value.remark = "";
    orderList.value = [];
    mapSequenceNoToInvfee.value = {};
  }
);
</script>

<template>
  <div class="addEditForm">
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      status-icon
      size="small"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="销售方公司抬头"
            prop="companyNo"
            label-width="135px"
          >
            <RemoteSelect
              v-model:value="ruleForm.companyNo"
              :api="httpCompanylist"
              style="width: 100%"
              placeholder="销售方公司抬头"
              response-label-prop="company_name"
              response-val-prop="companyNo"
              @item-change="setSellerInvoiceTitle"
            />
          </el-form-item>
          <InvoiceTitle :detail="sellerInvoiceTitle" />
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="购买方公司抬头"
            prop="buy_id"
            label-width="135px"
          >
            <RemoteSelect
              is-root
              v-model:value="ruleForm.buy_id"
              :api="httpInvoiceList"
              style="width: 100%"
              placeholder="购买方公司抬头"
              request-prop="name"
              response-label-prop="invoice_title"
              response-val-prop="id"
              @item-change="setPurchaserInvoiceTitle"
            />
          </el-form-item>
          <InvoiceTitle :detail="purchaserInvoiceTitle" />
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="100px" label="发票类型" prop="invtype">
            <el-select
              v-model="ruleForm.invtype"
              style="width: 100%"
              @change="menu_type_change"
              placeholder="发票类型"
            >
              <el-option
                v-for="(si, sii) in inv_type_list"
                :key="'type' + si.value + sii"
                :label="si.label"
                :value="si.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label-width="100px" label="电子邮箱" prop="email">
            <el-input v-model="ruleForm.email" placeholder="电子邮箱"
          /></el-form-item>
        </el-col>

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

        <el-col :span="8">
          <el-form-item label="申请备注" prop="exam_remark" label-width="135px">
            <el-input
              w-full
              v-model="ruleForm.exam_remark"
              :rows="3"
              type="textarea"
              maxlength="2000"
              placeholder="申请备注"
            /> </el-form-item
        ></el-col>
        <el-col :span="24" v-show="TYPE === 'order'">
          <el-form-item label="订单列表">
            <div flex justify-between w-full mb-2>
              <el-tag :type="orderList.length > max ? 'danger' : 'info'"
                >{{ orderList.length }} / {{ max }}</el-tag
              >
              <el-button type="primary" @click="handleAddModalShow"
                >添加销售订单</el-button
              >
            </div>
            <el-table :data="orderList" stripe border max-height="300">
              <el-table-column
                prop="sequenceNo"
                label="销售订单编号"
                width="200"
              />
              <el-table-column
                prop="poCode"
                label="po编号"
                show-overflow-tooltip
                width="200"
              />
              <el-table-column
                prop="customerNo"
                label="购买方公司编号"
                width="200"
              />
              <el-table-column
                prop="customerName"
                label="购买方公司名称"
                show-overflow-tooltip
                width="200"
              />

              <el-table-column prop="winv_fee" label="未开票" width="120" />
              <el-table-column prop="wsendNum" label="未发数量" width="120" />

              <el-table-column label="开票金额" width="110">
                <template #="{ row }">{{
                  mapSequenceNoToInvfee[row.sequenceNo].inv_fee
                }}</template>
              </el-table-column>

              <el-table-column label="开票数量" width="110">
                <template #="{ row }">{{
                  mapSequenceNoToInvfee[row.sequenceNo].num
                }}</template>
              </el-table-column>

              <el-table-column label="业务员" prop="ownerName" width="80" />

              <el-table-column fixed="right" width="70">
                <template #header>
                  <span>操作</span>
                </template>
                <template #default="scope">
                  <el-button
                    size="small"
                    type="primary"
                    link
                    :icon="useRenderIcon('edits')"
                    @click="handleShowEditModal(scope.$index, scope.row)"
                  />
                  <el-button
                    size="small"
                    type="danger"
                    link
                    :icon="useRenderIcon('delete')"
                    @click="handleDelete(scope.$index)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="flex justify-end mt-2">
        <el-button :loading="loading" type="primary" @click="handleSave"
          >保存</el-button
        >
      </div>
    </el-form>

    <OrderDialog ref="modelRef" @save-btn-click="handleAddOrder" />

    <EditOrder ref="editOrderRef" @save-btn-click="handleEdit" />
  </div>
</template>
