<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑仓库' : '添加仓库'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="仓库名称" name="name">
        <a-input
          allow-clear
          placeholder="请输入仓库名称"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="仓库编号" name="code">
        <a-input
          allow-clear
          placeholder="请输入仓库编号"
          v-model:value="form.code"
        />
      </a-form-item>
      <a-form-item label="类型" name="type">
        <a-input
          allow-clear
          placeholder="请输入类型"
          v-model:value="form.type"
        />
      </a-form-item>
      <a-form-item label="省市区" name="region">
        <RegionsSelect
          v-model:value="regions"
          valueField="label"
          placeholder="请选择省/市/区"
        />
      </a-form-item>
      <a-form-item label="仓库地址" name="address">
        <a-input
          allow-clear
          placeholder="请输入仓库地址"
          v-model:value="form.address"
        />
      </a-form-item>
      <a-form-item label="真实姓名" name="realName">
        <a-input
          allow-clear
          placeholder="请输入真实姓名"
          v-model:value="form.realName"
        />
      </a-form-item>
      <a-form-item label="联系电话" name="phone">
        <a-input
          allow-clear
          placeholder="请输入联系电话"
          v-model:value="form.phone"
        />
      </a-form-item>
      <a-form-item label="经纬度" name="lngAndLat">
        <a-input
          allow-clear
          placeholder="请输入经纬度"
          v-model:value="form.lngAndLat"
        />
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入描述"
          v-model:value="form.comments"
        />
      </a-form-item>
      <a-form-item label="排序号" name="sortNumber">
        <a-input-number
          :min="0"
          :max="9999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { addShopWarehouse, updateShopWarehouse } from '@/api/shop/shopWarehouse';
  import { ShopWarehouse } from '@/api/shop/shopWarehouse/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { FileRecord } from '@/api/system/file/model';
  import RegionsSelect from "@/components/RegionsSelect/index.vue";

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ShopWarehouse | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);
  const regions = ref<string[]>();

  // 用户信息
  const form = reactive<ShopWarehouse>({
    id: undefined,
    name: undefined,
    code: undefined,
    type: undefined,
    address: undefined,
    realName: undefined,
    phone: undefined,
    lngAndLat: undefined,
    userId: undefined,
    isDelete: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined,
    province: undefined,
    city: undefined,
    region: undefined,
    status: 0,
    comments: '',
    sortNumber: 100
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    shopWarehouseName: [
      {
        required: true,
        type: 'string',
        message: '请填写仓库名称',
        trigger: 'blur'
      }
    ]
  });

  const chooseImage = (data: FileRecord) => {
    images.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.image = data.path;
  };

  const onDeleteItem = (index: number) => {
    images.value.splice(index, 1);
    form.image = '';
  };

  const { resetFields } = useForm(form, rules);

  // 级联选择回填到表单字段，保持提交参数仍然是 province/city/region
  watch(
    regions,
    (val) => {
      form.province = val?.[0];
      form.city = val?.[1];
      form.region = val?.[2];
    },
    { immediate: true }
  );

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateShopWarehouse : addShopWarehouse;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if(props.data.image){
            images.value.push({
              uid: uuid(),
              url: props.data.image,
              status: 'done'
            })
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
