<template>
  <ElDialog v-model="showDialog" :destroy-on-close="true" :close-on-click-modal="false" width="fit-content" @close="dialogCloseHandler">
    <ElForm :model="formData" :rules="rules" ref="purchaseOrderForm" class="form-panel" label-width="auto">
      <!-- <ElFormItem label-width="90" label="Id" prop="id">
        <ElInput v-model="formData.id" :disabled="status === 'view'" placeholder="Id" />
      </ElFormItem> -->
      <!-- <ElFormItem label-width="90" label="编号" prop="sn">
        <ElInput v-model="formData.sn" :disabled="status === 'view'" placeholder="编号" />
      </ElFormItem> -->

      <!-- ，JinXingZhong--进行中、YiDaoHuo--已到货、YiRuKu--已入库、YiQuXiao--已取消 -->
      <!-- <ElFormItem label-width="90" label="状态" prop="purchaseOrderStatus">
        <ElInput v-model="formData.purchaseOrderStatus" :disabled="status === 'view'" placeholder="状态" />
      </ElFormItem> -->
      <ElFormItem label-width="90" label="供货客户" prop="customerId">
        <!-- <ElSelect v-model="formData.goodsCategoryId" :disabled="status === 'view'" placeholder="产品类型" filterable remote reserve-keyword remote-show-suffix :remote-method="remoteMethod" :loading="loading" style="width: 240px">
          <ElOption v-for="item in category" :key="item.id" :label="item.categoryName" :value="item.id" />
        </ElSelect> -->
        <ASelect labelKey="customerName" :tableColumn="customerColumn" v-model="formData.customerId" :api="CustomerApi.paging" :disabled="status === 'view'" placeholder="供货客户" />
      </ElFormItem>
      <ElFormItem label-width="90" label="采购日期" prop="purchaseDate">
        <el-date-picker v-model="formData.purchaseDate" :disabled="status === 'view'" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date" placeholder="请选择采购日期" />
      </ElFormItem>
      <ElFormItem label-width="90" label="到货日期" prop="arrivalDate">
        <el-date-picker v-model="formData.arrivalDate" :disabled="status === 'view'" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date" placeholder="请选择采购日期" />

        <!-- <ElInput v-model="formData.arrivalDate" :disabled="status === 'view'" placeholder="到货日期" /> -->
      </ElFormItem>
      <!-- <ElFormItem label-width="90" label="产品分类" prop="goodsCategoryId">
        <ElInput v-model="formData.goodsCategoryId" :disabled="status === 'view'" placeholder="产品分类" />
      </ElFormItem>
      <ElFormItem label-width="90" label="分类名称" prop="goodsCategoryName">
        <ElInput v-model="formData.goodsCategoryName" :disabled="status === 'view'" placeholder="分类名称" />
      </ElFormItem> -->

      <ElFormItem label-width="90" label="产品" prop="goodsId">
        <ASelect labelKey="goodsName" v-model="formData.goodsId" :tableColumn="goodColumn" @change="goodsChange" :api="GoodsApi.paging" :disabled="status === 'view'" placeholder="选择产品" />
      </ElFormItem>

      <!-- <ElFormItem label-width="90" label="商品编码" prop="goodSn">
        <ElInput v-model="formData.goodSn" :disabled="status === 'view'" placeholder="商品编码" />
      </ElFormItem> -->
      <ElFormItem label-width="90" label="数量" prop="quantity">
        <ElInput v-model="formData.quantity" :disabled="status === 'view'" placeholder="数量" />
      </ElFormItem>
      <ElFormItem label-width="90" label="计量单位" prop="unit">
        <ElInput v-model="formData.unit" readonly placeholder="计量单位" />
      </ElFormItem>
      <ElFormItem label-width="90" label="总金额" prop="totalMoney">
        <ElInput v-model="formData.totalMoney" :disabled="status === 'view'" placeholder="总金额；单位：元" />
      </ElFormItem>
      <ElFormItem label-width="90" label="备注" prop="memo">
        <ElInput v-model="formData.memo" :disabled="status === 'view'" placeholder="备注" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="showDialog = false">{{ status === "view" ? "关闭" : "取消" }}</ElButton>
      <ElButton v-if="status !== 'view'" :loading="submiting" type="primary" @click="submitHandler">提交</ElButton>
    </template>
  </ElDialog>
</template>

<script lang="ts" setup>
import PurchaseOrderApi from "@/pages/wh/purchase-order/purchase-order-api.ts";
import Strings from "@/common/utils/strings.ts";
import FormUtil from "@/common/utils/formUtil.ts";
import Utils from "@/common/utils";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
// import GoodsCategoryApi from '@/pages/gds/goods-category/goods-category-api.ts'
import CustomerApi from "@/pages/cst/customer/customer-api.ts";
import GoodsApi from "@/pages/gds/goods/goods-api.ts";
import ASelect from "@/components/a-select/ASelect.vue";

const emits = defineEmits(["editSucc"]);
const showDialog = ref(false);
const submiting = ref(false);
const status = ref<"add" | "view" | "modify">("add");

const purchaseOrderFormIns = useTemplateRef<FormInstance>("purchaseOrderForm");

const formData = Utils.resetAble(reactive<PurchaseOrderTypes.SearchPurchaseOrderResult>({}));
const rules = reactive<FormRules<PurchaseOrderTypes.SearchPurchaseOrderResult>>({
  sn: [{ required: true, message: "请填写编号", trigger: "blur" }],
  purchaseOrderStatus: [{ required: true, message: "请填写状态", trigger: "blur" }],
  customerId: [{ required: true, message: "请填写供货客户", trigger: "blur" }],
  purchaseDate: [{ required: true, message: "请填写采购日期", trigger: "blur" }],
  arrivalDate: [{ required: true, message: "请填写到货日期", trigger: "blur" }],
  goodsCategoryId: [{ required: true, message: "请填写产品分类", trigger: "blur" }],
  goodsCategoryName: [{ required: true, message: "请填写分类名称", trigger: "blur" }],
  goodsId: [{ required: true, message: "请填写产品", trigger: "blur" }],
  goodsName: [{ required: true, message: "请填写产品名称", trigger: "blur" }],
  goodSn: [{ required: true, message: "请填写商品编码", trigger: "blur" }],
  quantity: [{ required: true, message: "请填写数量", trigger: "blur" }],
  unit: [{ required: true, message: "请填写计量单位", trigger: "blur" }],
  totalMoney: [{ required: true, message: "请填写总金额；单位：元", trigger: "blur" }],
  memo: [{ required: true, message: "请填写备注", trigger: "blur" }],
  creatorId: [{ required: true, message: "请填写创建人", trigger: "blur" }],
  modifierId: [{ required: true, message: "请填写修改人", trigger: "blur" }],
  createTime: [{ required: true, message: "请填写创建时间", trigger: "blur" }],
  modifyTime: [{ required: true, message: "请填写修改时间", trigger: "blur" }],
});

const goodColumn = [
  {
    label: "名称",
    prop: "goodsName",
  },
  {
    label: "规格",
    prop: "specParams",
  },
  {
    label: "计量单位",
    prop: "unitTxt",
  },
];

const customerColumn = [
  {
    label: "公司",
    prop: "orgName",
  },
  {
    label: "地区",
    prop: "areaName",
  },
  {
    label: "负责人",
    prop: "customerName",
  },
];

const goodsChange = (val: any) => {
  // console.log(item, 'itemmm')
  formData.goodsCategoryName = val.goodsCategoryName;
  formData.goodsName = val.goodsName;
  formData.goodSn = val.sn;
  formData.unit = val.unit;
  formData.goodsCategoryId = val.goodsCategoryId;
};

// const iconTableDataSource = ref<any>(
//   icons.glyphs.filter((_, i) => {
//     return i >= 0 && i < 5;
//   })
// );

// const remoteMethod = (query: string) => {
//   console.log(query, "query");
//   loading.value = true;
//   CustomerApi.paging({ size: 50, categoryName: query || undefined }).then((res) => {
//     category.value = res.data.records;
//     loading.value = false;
//   });
// };

function dialogCloseHandler() {
  formData.$reset();
}

function submitHandler() {
  if (status.value === "view") return;
  submiting.value = true;
  if (formData.id != null) {
    FormUtil.submit(purchaseOrderFormIns, () => PurchaseOrderApi.modify(formData))
      .then(() => {
        ElMessage.success("修改成功");
        emits("editSucc");
        showDialog.value = false;
      })
      .finally(() => {
        submiting.value = false;
      });
  } else {
    FormUtil.submit(purchaseOrderFormIns, () => PurchaseOrderApi.add(formData))
      .then(() => {
        ElMessage.success("添加成功");
        emits("editSucc");
        showDialog.value = false;
      })
      .finally(() => {
        submiting.value = false;
      });
  }
}

defineExpose({
  open(data: PurchaseOrderTypes.SearchPurchaseOrderResult = {}) {
    if (!Strings.isBlank(data.id)) {
      status.value = "modify";
      PurchaseOrderApi.detail(data.id!).then((res) => {
        formData.$reset(res.data);
      });
    } else {
      status.value = "add";
      formData.$reset(data);
    }
    showDialog.value = true;

    console.log(formData.goodsId, "formData");
  },
});
</script>

<style lang="stylus" scoped>
.form-panel {
  padding 20px
}
</style>
