<template>
  <a-modal
    v-model:visible="visible"
    :title="props.editId ? '编辑' : '新增'"
    @ok="handleOk"
    @cancel="handleCancel"
    class="myModal"
  >
    <a-form
      :model="formData"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 14 }"
      autocomplete="off"
      ref="formRef"
      :rules="rulesRef"
    >
      <a-form-item label="经销商" name="distributorId">
        <a-select
          v-model:value="formData.distributorId"
          style="width: 100%"
          placeholder="请选择"
          :fieldNames="{ label: 'name', value: 'id' }"
          :options="distributorOptions"
        ></a-select>
      </a-form-item>
      <a-form-item label="商品" name="goods">
        <a-select
          v-model:value="formData.goods"
          show-search
          label-in-value
          placeholder="请搜索商品"
          style="width: 100%"
          :filter-option="false"
          :not-found-content="fetching ? undefined : null"
          :options="goodsOptions"
          @search="fetchGoods"
        >
          <template v-if="fetching" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="折扣时间期限" name="time">
        <a-range-picker
          v-model:value="formData.time"
          :show-time="{ format: 'HH:mm:ss' }"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          :placeholder="['开始时间', '结束时间']"
        />
      </a-form-item>
      <a-form-item label="折扣设置" name="discountRate">
        <a-input-number v-model:value="formData.discountRate" :max="10" :min="0" />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="formData.status">
          <a-radio value="YES">启用</a-radio>
          <a-radio value="NO">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineExpose, ref, reactive, defineEmits, watch, defineProps } from 'vue';
  import { rulesRef } from './schema';
  import { message } from 'ant-design-vue';
  import * as GoodsPriceApi from '/@/api/product/goodsPriceApi';
  import * as DistributorApi from '/@/api/system/distributorApi';
  import * as GoodsApi from '/@/api/product/goodsApi';
  import { debounce, cloneDeep } from 'lodash-es';
  import { Data } from './type';

  const props = defineProps(['editId']);
  const emits = defineEmits(['handleSuccess', 'update:editId']);
  const formRef = ref<any>();
  const visible = ref<boolean>(false);

  const formData = reactive<Data>({
    distributorId: undefined,
    goodsId: undefined,
    goods: undefined,
    time: <string[]>[],
    discountStartTime: '',
    discountEndTime: '',
    discountRate: 10,
    status: 'NO',
    id: undefined,
  });
  const distributorOptions = ref<any>([]);
  const goodsOptions = ref();

  const getDistributor = () => {
    DistributorApi.all().then((res) => {
      distributorOptions.value = res;
    });
  };

  let lastFetchId = 0;
  const fetching = ref(false);

  const fetchGoods = debounce((value) => {
    lastFetchId += 1;
    const fetchId = lastFetchId;
    goodsOptions.value = [];
    fetching.value = true;
    GoodsApi.search({ pageNum: 1, pageSize: 20, name: `%${value}%` }).then((body) => {
      if (fetchId !== lastFetchId) {
        return;
      }
      const data = body.records.map((item) => ({
        label: item.name,
        value: item.id,
      }));

      goodsOptions.value = data;
      fetching.value = false;
    });
  }, 300);

  const handleOk = () => {
    formRef.value.validate().then(() => {
      const data = cloneDeep(formData);
      data.discountStartTime = data.time[0];
      data.discountEndTime = data.time[1];

      if (data.goods) {
        data.goodsId = data.goods.value;
      }

      let api;
      if (props.editId) {
        data.id = props.editId;
        api = GoodsPriceApi.update;
      } else {
        api = GoodsPriceApi.add;
      }
      api(data).then((res) => {
        message.success('操作成功');
        emits('handleSuccess');
        handleCancel();
      });
    });
  };
  const handleCancel = () => {
    formRef.value.resetFields();
    emits('update:editId', undefined);
    visible.value = false;
  };

  const getEditInfo = () => {
    GoodsPriceApi.getById(props.editId).then((res) => {
      for (const key in formData) {
        formData[key] = res[key];
      }
      formData.time = [res.discountStartTime, res.discountEndTime];
      formData.goods = { value: res.goodsId };
      fetchGoods(res.goodsDto.name);
    });
  };

  watch(
    () => visible.value,
    (n) => {
      if (n) {
        getDistributor();
      }
    },
  );

  watch(
    () => props.editId,
    (newValue) => {
      if (newValue) {
        getEditInfo();
      }
    },
  );

  defineExpose({ visible });
</script>

<style lang="less" scoped></style>
