<template>
  <ElDialog v-model="showDialog" :close-on-click-modal="false" destroy-on-close width="fit-content" @close="dialogCloseHandler">
    <ElForm :model="formData" :rules="rules" ref="goodsForm" class="form-panel" label-width="auto">
      <ElFormItem label="产品类型" prop="goodsCategoryId">
        <!-- <ElInput v-model="formData.goodsCategoryId" :disabled="status === 'view'" placeholder="产品类型 Id" /> -->
        <el-select v-model="formData.goodsCategoryId" :disabled="status === 'view'" placeholder="产品类型" filterable remote reserve-keyword remote-show-suffix :remote-method="remoteMethod" :loading="loading" style="width: 240px">
          <el-option v-for="item in category" :key="item.id" :label="item.categoryName" :value="item.id" />
        </el-select>
      </ElFormItem>
      <ElFormItem label="商品编码" prop="sn">
        <ElInput v-model="formData.sn" :disabled="status === 'view'" placeholder="商品编码" />
      </ElFormItem>
      <ElFormItem label="产品名称" prop="goodsName">
        <ElInput v-model="formData.goodsName" :disabled="status === 'view'" placeholder="产品名称" />
      </ElFormItem>
      <ElFormItem label="规格" prop="specParams">
        <ElInput v-model="formData.specParams" :disabled="status === 'view'" placeholder="规格" />
      </ElFormItem>
      <ElFormItem label="图片" prop="picture">
        <Uploader v-model:file="formData.picture" :limit="1" :multiple="true" accept="image/*" class="avatar-uploader" list-type="picture-card">
          <span style="font-size: 50px; padding: 0 40px">+</span>
        </Uploader>
      </ElFormItem>
      <ElFormItem label="计量单位" prop="unit">
        <ADict v-model="formData.unit" :disabled="status === 'view'" dict-key="unit" placeholder="计量单位" style="width: 240px"/>
      </ElFormItem>
      <ElFormItem label="排序" prop="sort">
        <ElInput v-model="formData.sort" :disabled="status === 'view'" placeholder="请输入排序" />
      </ElFormItem>
      <ElFormItem label="备注" prop="memo">
        <ElInput v-model="formData.memo" :disabled="status === 'view'" placeholder="请输入备注" />
      </ElFormItem>
      <ElFormItem label="是否可用" prop="canuse">
        <el-switch v-model="formData.canuse" :disabled="status === 'view'" />
      </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 GoodsApi from '@/pages/gds/goods/goods-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 Uploader from '@/components/uploader/Uploader.vue'
import GoodsCategoryApi from '@/pages/gds/goods-category/goods-category-api.ts'
import DictApi from '@/pages/sys/dict/dict-api.ts'
import ADict from '@/components/a-dict/ADict.vue'

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

const goodsFormIns = useTemplateRef<FormInstance>("goodsForm");

const formData = Utils.resetAble(reactive<GoodsTypes.SearchGoodsResult>({ canuse: true }));
const rules = reactive<FormRules<GoodsTypes.SearchGoodsResult>>({
  id: [{ required: true, message: "请填写Id", trigger: "blur" }],
  goodsCategoryId: [{ required: true, message: "请填写产品类型", trigger: "blur" }],
  sn: [{ required: true, message: "请填写商品编码", trigger: "blur" }],
  goodsName: [{ required: true, message: "请填写产品名称", trigger: "blur" }],
  specParams: [{ required: true, message: "请填写规格", trigger: "blur" }],
  picture: [{ required: true, message: "请填写图片", trigger: "blur" }],
  unit: [{ required: true, message: "请填写计量单位", trigger: "blur" }],
  sort: [{ required: true, message: "请填写排序", trigger: "blur" }],
});

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

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

const category = ref<GoodsCategoryTypes.SearchGoodsCategoryResult[]>([]);
const loading = ref(false);
const remoteMethod = (query: string) => {
  console.log(query, "query");
  loading.value = true;
  GoodsCategoryApi.paging({ size: 50, categoryName: query || undefined }).then((res) => {
    category.value = res.data.records;
    loading.value = false;
    // category.value = list.value.filter((item) => {
    //   return item.label.toLowerCase().includes(query.toLowerCase())
    // })
  });
  // } else {
  //   category.value = [];
  // }
};
const unitList=ref<DictItemTypes.SearchDictItemResult[]>([])
const getOpt = () => {
  let searchForm = {
    dictKey: "unit",
  };
  DictApi.obtainDictData(searchForm).then((res) => {
    // console.log(res.data);
    unitList.value=res.data
  });
};

defineExpose({
  open(data: GoodsTypes.SearchGoodsResult = {}) {
    showDialog.value = true;
    if (!Strings.isBlank(data.id)) {
      status.value = "modify";
      GoodsApi.detail(data.id!).then((res) => {
        formData.$reset(res.data);
      });
    } else {
      status.value = "add";
      formData.$reset(data);
    }
    getOpt();
  },
});
</script>

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