<script setup lang="ts">
import { computed, reactive, ref, watchEffect } from "vue";
import BasicPurchas from "./../basic-purchase.vue";
import AddOrderModal from "./add-order-modal.vue";
import { useResponseHandle } from "/@/hooks";
import { useRouter } from "vue-router";
import { ElForm } from "element-plus";
import { httpAdd, httpUpadte } from "/@/api/purchase/orderRecord";
import RemoteSelect from "/@/components/RemoteSelect";
import { httpList as httpSupplierList } from "/@/api/parameter/supplierPay";
import { httpList as httpCompanylist } from "/@/api/parameter/finance";
import { rules } from "../../config/configs";

const props = defineProps<{
  payNo?: string;
  statementDetail?: Record<string, string>;
}>();

const { push } = useRouter();
const isUpdate = computed(() => !!props.payNo);
const responseHandle = useResponseHandle();
const addOrderModalRef = ref<InstanceType<typeof AddOrderModal>>(null);
const mapSequenceNo = ref<Record<string, string>>({});

//已经审核 禁用表单
const formDisabled = computed(
  () => Number(props.statementDetail && props.statementDetail.status) >= 0
);
//采购单列表
const purchaseOrderList = ref<Array<any>>([]);

const formRef = ref<InstanceType<typeof ElForm>>(null);
const formData = reactive<Record<string, any>>({
  cids: "",
  supplierNo: "",
  companyNo: ""
});

//显示添加采购单的dialog
function handleAddPurchaseOrder() {
  addOrderModalRef.value.onDisplay();
}

//保存采购单信息
function handleSavePurchaseOrder(list) {
  list.forEach(item => {
    //去重
    if (!mapSequenceNo.value[item.sequenceNo]) {
      mapSequenceNo.value[item.sequenceNo] = item.sequenceNo;
      purchaseOrderList.value.push(item);
    }
  });
  converPurchaseids();
}

//删除采购单信息
function handleDeletepurchaseOrder({ id }) {
  const delIndex = purchaseOrderList.value.findIndex(
    p => String(p.id) === String(id)
  );

  if (delIndex < 0) return;
  const [delItem] = purchaseOrderList.value.splice(delIndex, 1);
  delete mapSequenceNo.value[delItem.sequenceNo];
  converPurchaseids();
}

//创建订单对账
function handleCreateBill() {
  formRef.value.validate(async isVaild => {
    if (!isVaild) return;

    const api = isUpdate.value ? httpUpadte : httpAdd;
    const { cids } = formData;

    const { code, message } = await api({
      cids,
      ...(props.payNo ? { payNo: props.payNo } : {})
    });

    responseHandle({
      code,
      message,
      //跳转回对账页面
      handler: () => push("/purchase/orderRecord")
    });
  });
}

//转换采购单id格式 [1,2,3] => '1,2,3'
const converPurchaseids = () => {
  formData.cids = purchaseOrderList.value.map(p => p.id).join(",");
};

//当供货商和业务公司有一个为空时清空列表数据
watchEffect(() => {
  const { supplierNo, companyNo } = formData;
  if (!supplierNo || !companyNo) purchaseOrderList.value = [];
});
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    :disabled="formDisabled"
  >
    <!-- 创建 -->
    <div flex gap-10 v-if="!payNo">
      <el-form-item label="业务公司" prop="companyNo">
        <RemoteSelect
          v-model:value="formData.companyNo"
          :api="httpCompanylist"
          placeholder="请选择业务公司"
          request-prop="companyName"
          response-label-prop="company_name"
          response-val-prop="companyNo"
        />
      </el-form-item>

      <el-form-item label="供应商" prop="supplierNo">
        <RemoteSelect
          v-model:value="formData.supplierNo"
          :api="httpSupplierList"
          width="300px"
          placeholder="请选择供应商"
          response-label-prop="name"
          response-val-prop="code"
        />
      </el-form-item>
    </div>

    <el-form-item label="采购单信息" prop="cids">
      <BasicPurchas
        :purchase-order-list="purchaseOrderList"
        :supplier-no="formData.supplierNo"
        :company-no="formData.companyNo"
        @add-btn-click="handleAddPurchaseOrder"
        @del-btn-click="handleDeletepurchaseOrder"
        @crate-btn-click="handleCreateBill"
        @change-supplie-list="handleSavePurchaseOrder"
      />
    </el-form-item>
  </el-form>

  <AddOrderModal
    ref="addOrderModalRef"
    :supplier-no="formData.supplierNo"
    :company-no="formData.companyNo"
    @save-btn-click="handleSavePurchaseOrder"
  />
</template>

<style lang="scss" scoped>
:deep(.el-select) {
  width: 500px;
}
</style>
