<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :confirm-loading="loading"
    :title="isUpdate ? '编辑电子围栏' : '添加电子围栏'"
    :body-style="{ paddingBottom: '28px', maxHeight: '70vh', overflow: 'auto' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :disabled="loading"
      :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-row :gutter="16">
        <a-col :xs="24" :sm="24">
          <a-form-item label="围栏类型" name="type">
            <a-radio-group v-model:value="form.type">
              <a-radio :value="0">圆形</a-radio>
              <a-radio :value="1">方形/多边形</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="围栏范围" name="points" :extra="pointsHelp">
        <a-textarea
          :auto-size="{ minRows: 3, maxRows: 6 }"
          allow-clear
          :placeholder="pointsPlaceholder"
          v-model:value="form.points"
        />
        <p class="py-2">
          <a
            class="text-blue-500"
            href="https://lbs.qq.com/dev/console/cloud/placeCloud/datamanage?table_id=0q3W4MrK1-_6Xag7V1"
            target="_blank"
          >使用腾讯地图的工具绘制电子围栏</a
          >
        </p>
      </a-form-item>

      <a-form-item label="定位描述" name="location">
        <a-input
          allow-clear
          placeholder="如：xx商圈/xx门店附近（可选）"
          v-model:value="form.location"
        />
      </a-form-item>

      <a-form-item label="所属区域" name="district">
        <a-input
          allow-clear
          placeholder="如：广东省/广州市/天河区（可选）"
          v-model:value="form.district"
        />
      </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-item label="状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">启用</a-radio>
          <a-radio :value="1">禁用</a-radio>
        </a-radio-group>
      </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>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { computed, nextTick, reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addShopStoreFence, updateShopStoreFence } from '@/api/shop/shopStoreFence';
  import { ShopStoreFence } from '@/api/shop/shopStoreFence/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { FormInstance } from 'ant-design-vue/es/form';

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

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

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = true;
  // 表单实例
  const formRef = ref<FormInstance | null>(null);

  const getDefaultForm = (): ShopStoreFence => ({
    id: undefined,
    name: '',
    type: 0,
    location: '',
    longitude: '',
    latitude: '',
    district: '',
    points: '',
    sortNumber: 100,
    comments: '',
    status: 0,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined
  });

  const form = reactive<ShopStoreFence>(getDefaultForm());

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    // 保存中不允许关闭，避免重复提交/状态不一致
    if (!value && loading.value) {
      return;
    }
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请填写电子围栏名称',
        trigger: 'blur'
      }
    ],
    type: [
      {
        required: true,
        type: 'number',
        message: '请选择围栏类型',
        trigger: 'change'
      }
    ],
    longitude: [
      {
        required: true,
        type: 'string',
        message: '请填写经度',
        trigger: 'blur'
      }
    ],
    latitude: [
      {
        required: true,
        type: 'string',
        message: '请填写纬度',
        trigger: 'blur'
      }
    ],
    points: [
      {
        required: true,
        type: 'string',
        message: '请填写围栏范围',
        trigger: 'blur'
      }
    ]
  });

  const pointsPlaceholder = computed(() => {
    return form.type === 0
      ? '圆形示例：lng,lat,radius(米) 例如：113.123456,23.123456,500'
      : '多边形示例：lng,lat;lng,lat;lng,lat 例如：113.1,23.1;113.2,23.1;113.2,23.2;113.1,23.2';
  });

  const pointsHelp = computed(() => {
    return form.type === 0
      ? '按 “经度,纬度,半径(米)” 填写'
      : '按 “经度,纬度;经度,纬度;...” 填写，建议首尾闭合';
  });

  const resetForm = async () => {
    assignObject(form, getDefaultForm());
    await nextTick();
    formRef.value?.clearValidate?.();
  };

  const fillForm = async (data: ShopStoreFence) => {
    await resetForm();
    assignObject(form, data);
    await nextTick();
    formRef.value?.clearValidate?.();
  };

  /* 保存编辑 */
  const save = async () => {
    if (!formRef.value || loading.value) {
      return;
    }
    try {
      await formRef.value.validate();
      loading.value = true;
      const formData: ShopStoreFence = {
        ...form,
        name: form.name?.trim(),
        location: form.location?.trim(),
        longitude: form.longitude?.trim(),
        latitude: form.latitude?.trim(),
        district: form.district?.trim(),
        points: form.points?.trim(),
        comments: form.comments?.trim()
      };
      const saveOrUpdate = isUpdate.value ? updateShopStoreFence : addShopStoreFence;
      const msg = await saveOrUpdate(formData);
      loading.value = false;
      message.success(msg);
      updateVisible(false);
      emit('done');
    } catch (e: any) {
      loading.value = false;
      if (e?.message) {
        message.error(e.message);
      }
    }
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          void fillForm(props.data);
          isUpdate.value = true;
        } else {
          void resetForm();
          isUpdate.value = false;
        }
      } else {
        void resetForm();
      }
    },
    { immediate: true }
  );
</script>
