<script setup lang="ts">
import { ref, unref, watch, shallowRef } from "vue";
import { httpDetail, httpCommonDetail } from "/@/api/purchase/orderRecord";
import PurchaseDescriptions from "./cpns/purchase-descriptions.vue";
import RemoteSelect from "/@/components/RemoteSelect";
import PurchaseTable from "./cpns/purchase-table.vue";
import { useAsync } from "/@/hooks/core/useAsync";
import { ElForm } from "element-plus";
import { rules } from "./_options";
import { httpGetSupplier, httpGetBusiness } from "/@/api/user";

import { division } from "/@/utils/calc"

import { useCompany } from "/@/hooks/core/useCompany";
import { addition } from "/@/utils/calc";

const emit = defineEmits(["create", "choose", "getRecord", "openInv", "clear"]);

const purchaseTableRef = ref<InstanceType<typeof PurchaseTable> | null>(null);
const { currentCompany } = useCompany();

const orderArr = ref([]);
const totalCommonPrice = shallowRef("0.00");
const totalCommonCount = shallowRef(0);

const isComon = ref("0");

const props = defineProps<{
  id?: string;
  isPurch?: boolean;
  loading?: boolean;
  readonly?: boolean;
  isPurchPay?: boolean;
  showTicketColumn?: boolean;
  edit: boolean;
  cover?: boolean;
  platformType?: string
}>();

const formData = ref({
  companyNo: "",
  supplierNo: "",
  companyItem: {},
  cids: []
});

const formRef = ref<InstanceType<typeof ElForm>>(null);
const purchaseOrders = ref<Record<string, any>[]>([]);

const {
  run,
  data,
  loading: _loading
} = useAsync<Record<string, any>>({
  initalData: {},
  success: function (data) {

    if (props.cover) { 
      purchaseOrders.value = []; formData.value.cids = [];
    }

    emit("getRecord", data)

    // division()

    uniquePurchaseOrders(data[props.edit ? 'qrdlist' : 'cgdlist'].map((item,index) => ({
      ...item,
      goodPrice:Number(division(item.totalPrice,item.goodNum)).toFixed(8),
      cgdNo:data['cgdlist'][index].name,
      num: item.winv_num,
      inv_fee: item.winv_fee,
      isSelection: false,
      totalOpenAmount: '0.00'
    })));

    totalCommonPrice.value = "0.00"
    totalCommonCount.value = 0;
  }
});

//追加采购单并去重
function uniquePurchaseOrders(list?: any[]) {
  if (!list) return;

  for (let i = 0; i < list.length; i++) {
    const current = list[i];
    if (formData.value.cids.includes(current.id)) continue;
    purchaseOrders.value.push(current);
    formData.value.cids.push(current.id);
  }
}

function handleDeletePurchaseOrders(index: number) {
  purchaseOrders.value.splice(index, 1);
  formData.value.cids.splice(index, 1);
}

function handleGetItem(item) {
  formData.value.companyItem = item;
}

async function handleCreate() {
  try {
    await formRef.value.validate();
    emit("create", unref(formData));
  } catch (err) {
    console.log(err);
  }
}

const requestDetail = () => run(props.edit ? httpCommonDetail({ payNo: props.id }) : httpDetail({payNo:props.id}));

const getLabel = company => {
  const { code, name, type } = company;
  const isCompany = type === "3" || type === "业务公司";
  const suffix = isCompany ? "(已升级为业务公司)" : "";
  return code + " / " + name + suffix;
};

const getBusinessLabel = company => {
  const { companyNo, company_name } = company;
  return companyNo + " / " + company_name;
};

const handleEditPurchaseOrders = (item, index) => { 
  const { inv_fee, num, totalOpenAmount } = item;

  
  purchaseOrders.value[index].inv_fee = inv_fee;
  purchaseOrders.value[index].num = num;
  purchaseOrders.value[index].totalOpenAmount = totalOpenAmount;

  const total = purchaseOrders.value.reduce((prev, current) => { 
    return addition(prev,current.isSelection ? current.inv_fee : 0)
  },0)

  totalCommonCount.value = purchaseOrders.value.reduce((prev, current) => { 
    return addition(prev,current.isSelection ? 1 : 0)
  },0)

  totalCommonPrice.value = Number(total).toFixed(2)
}

function handleBatchSelection(ids,isSelection = true) { 
  purchaseOrders.value.forEach(item => item.isSelection = isSelection ? ids.includes(item.id) : !ids.includes(item.id))
  const total = purchaseOrders.value.reduce((prev, current) => addition(prev,current.isSelection ? current.inv_fee : 0), 0)
  totalCommonCount.value = purchaseOrders.value.reduce((prev, current) => addition(prev,current.isSelection ? 1 : 0), 0)
  totalCommonPrice.value = Number(total).toFixed(2)
}

watch(
  () => props.id,
  value => value && requestDetail(),
  { immediate: true }
);


watch(() =>  isComon.value,() => {
  purchaseOrders.value  = [];
  formData.value.cids = [];
})

watch(
  () => currentCompany.value,
  ({ companyNo }) => {
    formData.value[props.isPurch ? "companyNo" : "supplierNo"] = companyNo;
  },
  { immediate: true }
);

watch(() => props.platformType, () => { 
  data.value = {};
  purchaseOrders.value = [];
  formData.value.cids = [];
  emit("clear")
})

defineExpose({
  detail: data,
  refresh: () => requestDetail(),
  getOpenInvInfo: () => ({
    orderArr: purchaseOrders.value.filter(({ isSelection }) => isSelection).map(({ num, inv_fee ,sequenceNo}) => ({ num, inv_fee, sequenceNo })),
    totalCommonPrice: totalCommonPrice.value,
    totalCommonCount:totalCommonCount.value,
    data: data.value
  })
});
</script>

<template>
  <div class="w-full" v-loading="_loading || loading">
    <div class="w-full flex justify-end" v-if="isPurchPay">
      <ElButton text type="primary" @click="() => emit('choose')">
        选择</ElButton
      >
    </div>

    <PurchaseDescriptions
      v-if="readonly"
      :showTicketColumn="showTicketColumn"
      :isPurchPay="isPurchPay"
      :data="data"
    />

    <ElForm
      v-if="!isPurchPay"
      class="w-full"
      ref="formRef"
      :model="formData"
      :rules="rules"
      v-loading="loading"
    >
      <div flex gap-10 v-if="!readonly">
        <ElFormItem label="买方公司" prop="companyNo">
          <RemoteSelect
            v-if="!isPurch"
            v-model:value="formData.companyNo"
            style="width: 386px"
            :api="httpGetBusiness"
            placeholder="请选择买方公司"
            request-prop="company_name"
            response-label-prop="company_name"
            response-val-prop="companyNo"
            :disabled-value="currentCompany.companyNo"
            :getLabel="getBusinessLabel"
            @item-change="handleGetItem"
          />
          <ElInput
            v-else
            style="width: 300px"
            :value="currentCompany.companyName"
            disabled
          />
        </ElFormItem>

        <ElFormItem label="卖方公司" prop="supplierNo">
          <ElInput
            v-if="!isPurch"
            style="width: 300px"
            :value="currentCompany.companyName"
            disabled
          />

          <RemoteSelect
            v-else
            v-model:value="formData.supplierNo"
            style="width: 386px"
            :api="httpGetSupplier"
            placeholder="请选择卖方公司"
            request-prop="name"
            response-label-prop="name"
            response-val-prop="code"
            :disabled-value="currentCompany.companyNo"
            :getLabel="getLabel"
          />
        </ElFormItem>

        

        <ElFormItem label="业务类型" :required="true">
          <ElSelect v-model="isComon">
            <ElOption label="采购订单" value="0" />
            <ElOption label="源头订单" value="2" />
          </ElSelect>
        </ElFormItem>
      </div>

      <ElFormItem
        :label="readonly ? '' : '采购单信息'"
        :prop="readonly ? '' : 'cids'"
      >
        <PurchaseTable
          class="w-full mt-1"
          ref="purchaseTableRef"
          v-bind="formData"
          :readonly="readonly"
          :edit="edit"
          :totalCommonPrice="totalCommonPrice"
          :totalCommonCount="totalCommonCount"
          :purchaseOrders="purchaseOrders"
          :isComon="isComon"
          @delete="handleDeletePurchaseOrders"
          @push="uniquePurchaseOrders"
          @edit="handleEditPurchaseOrders"
          @selectionChange="arr => orderArr = arr"
          @batchSelection="handleBatchSelection"
          @batchCancelSelection="handleBatchSelection($event,false)"
        />
      </ElFormItem>

      <ElFormItem>
        <div class="flex w-full justify-end" v-if="!readonly">
          <ElButton type="primary" @click="handleCreate" :loading="loading"
            >保存</ElButton
          >
        </div>
      </ElFormItem>
    </ElForm>

    <PurchaseTable
      v-if="isPurchPay"
      ref="purchaseTableRef"
      class="w-full mt-1"
      v-bind="formData"
      :edit="edit"
      :totalCommonPrice="totalCommonPrice"
      :totalCommonCount="totalCommonCount"
      :readonly="readonly"
      :isPurchPay="isPurchPay"
      :isComon="isComon"
      :purchaseOrders="purchaseOrders"
      @delete="handleDeletePurchaseOrders"
      @push="uniquePurchaseOrders"
      @edit="handleEditPurchaseOrders"
      @selectionChange="arr => orderArr = arr"
      @batchSelection="handleBatchSelection"
      @batchCancelSelection="handleBatchSelection($event,false)"
    />
  </div>
</template>
