<script setup lang="ts">
import { ref, unref, watch, h } from "vue";
// import { httpDetail } 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 { useCompany } from "/@/hooks/core/useCompany";

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

const { currentCompany } = useCompany();

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

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

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

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

//追加采购单并去重
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;
}

function handleCreate() {
  props.isPurch;
  formRef.value.validate(isValid => isValid && emit("create", unref(formData)));
}

const requesetDetail = () => {};

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

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

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

defineExpose({
  detail: data,
  refresh: () => requesetDetail()
});
</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"
      :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>
      </div>

      <ElFormItem
        :label="readonly ? '' : '采购单信息'"
        :prop="readonly ? '' : 'cids'"
      >
        <PurchaseTable
          class="w-full mt-1"
          v-bind="formData"
          :readonly="readonly"
          :purchaseOrders="purchaseOrders"
          @delete="handleDeletePurchaseOrders"
          @push="uniquePurchaseOrders"
        />
      </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"
      class="w-full mt-1"
      v-bind="formData"
      :readonly="readonly"
      :isPurchPay="isPurchPay"
      :purchaseOrders="purchaseOrders"
      @delete="handleDeletePurchaseOrders"
      @push="uniquePurchaseOrders"
    />
  </div>
</template>
