<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="750"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑商户' : '添加商户'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
      layout="vertical"
    >
      <a-form-item label="商户编号" name="merchantCode">
        <a-input
          allow-clear
          placeholder="请输入商户编号"
          :disabled="isUpdate"
          v-model:value="form.merchantCode"
        />
      </a-form-item>
      <a-form-item label="商户名称" name="merchantName">
        <a-input
          allow-clear
          placeholder="请输入商户名称"
          v-model:value="form.merchantName"
        />
      </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="LOGO" name="images" extra="建议尺寸: 120*120">
        <ele-image-upload
          v-model:value="images"
          :limit="1"
          :drag="true"
          :item-style="{ width: '80px', height: '80px' }"
          :upload-handler="uploadHandler"
          @upload="onUpload"
        />
      </a-form-item>
      <a-form-item label="背景图" name="background" extra="建议尺寸: 750*200">
        <ele-image-upload
          v-model:value="background"
          :limit="1"
          :drag="true"
          :item-style="{ width: '360px', height: '100px' }"
          :upload-handler="uploadHandler"
          @upload="onUploadBackground"
        />
      </a-form-item>
      <a-form-item
        label="负责人"
        name="merchantOwner"
        extra="请绑定负责人，注意：超管和游客账号不要绑定"
      >
        <OwnerChoose :value="form.merchantOwner" @select="onSelect" />
      </a-form-item>
      <a-form-item label="营业时间" name="merchantHours">
        <a-input
          allow-clear
          placeholder="请输入营业时间"
          v-model:value="form.merchantHours"
        />
      </a-form-item>
      <a-form-item label="门店电话" name="merchantPhone">
        <a-input
          allow-clear
          placeholder="请输入门店电话"
          v-model:value="form.merchantPhone"
        />
      </a-form-item>
      <a-form-item label="商户坐标" name="lngAndLat">
        <div class="flex-sb">
          <a-input
            allow-clear
            placeholder="请输入商户坐标"
            v-model:value="form.lngAndLat"
          />
          <a-button
            class="ele-btn-icon"
            style="margin-left: 10px"
            @click="openMapPicker"
          >
            打开地图位置选择器
          </a-button>
        </div>
      </a-form-item>
      <a-form-item label="所在地区" name="region">
        <div class="flex-sb">
          <regions-select
            v-model:value="city"
            valueField="label"
            placeholder="请选择省市区"
            class="ele-fluid"
            @change="onChangeRegion"
          />
        </div>
      </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="content">
        <!-- 编辑器 -->
        <byte-md-editor
          v-model:value="content"
          :locale="zh_Hans"
          :plugins="plugins"
          height="350px"
        />
      </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="sortNumber">
        <a-input-number
          :min="0"
          :max="99999"
          class="ele-fluid"
          placeholder="请输入排序号（数字越小越靠前）"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
      <!-- 地图位置选择弹窗 -->
      <ele-map-picker
        :need-city="true"
        :dark-mode="darkMode"
        v-model:visible="showMap"
        :center="[108.374959, 22.767024]"
        :search-type="1"
        :zoom="12"
        @done="onDone"
      />
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { Merchant } from '@/api/merchant/model';
  import { addMerchant, updateMerchant } from '@/api/merchant';
  import { FormInstance, Rule, RuleObject } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { uploadFile } from '@/api/system/file';
  import OwnerChoose from '@/components/UserChoose/index.vue';
  import { FILE_SERVER, FILE_THUMBNAIL } from "@/config/setting";
  import useFormData from '@/utils/use-form-data';
  import RegionsSelect from '@/components/RegionsSelect/index.vue';
  import { createMerchantCode } from '@/utils/common';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import type { CenterPoint } from 'ele-admin-pro/es/ele-map-picker/types';
  import ByteMdEditor from '@/components/ByteMdEditor/index.vue';
  import highlight from '@bytemd/plugin-highlight';
  // 中文语言文件
  import zh_Hans from 'bytemd/locales/zh_Hans.json';
  // // 链接、删除线、复选框、表格等的插件
  import gfm from '@bytemd/plugin-gfm';
  // // 插件的中文语言文件
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  // // 预览界面的样式，这里用的 github 的 markdown 主题
  import 'github-markdown-css/github-markdown-light.css';

  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Merchant | null;
  }>();

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

  const themeStore = useThemeStore();
  const { darkMode } = storeToRefs(themeStore);

  // 提交状态
  const loading = ref(false);
  // 已上传数据
  const images = ref<ItemType[]>([]);
  const background = ref<ItemType[]>([]);
  const formRef = ref<FormInstance | null>(null);
  // 编辑器内容，双向绑定
  const content = ref<any>('');
  // 省市区
  const city = ref<string[]>([]);
  // 是否显示地图选择弹窗
  const showMap = ref(false);

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

  // 选择地区
  const onChangeRegion = (value) => {
    form.province = value[0];
    form.city = value[1];
    form.region = value[2];
  };

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Merchant>({
    merchantName: '',
    merchantCode: `${createMerchantCode()}`,
    image: '',
    createTime: '',
    comments: '',
    sortNumber: 100,
    status: 0,
    linkman: '',
    address: '',
    lngAndLat: '',
    phone: '',
    merchantId: 0,
    userId: undefined,
    merchantOwner: 0,
    merchantPhone: undefined,
    content: '',
    merchantHours: '8:30 - 22:30',
    province: '',
    city: '',
    region: '',
    customerId: 0
  });

  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return;
    }
    onUpload(item);
  };

  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: FILE_THUMBNAIL + data.path,
          status: 'done'
        });
        form.logo = data.path;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  // 上传文件
  const onUploadBackground = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        background.value.push({
          uid: data.id,
          url: FILE_THUMBNAIL + data.path,
          status: 'done'
        });
        form.logo = data.path;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    merchantName: [
      {
        required: true,
        message: '请输入商户名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    merchantCode: [
      {
        required: true,
        type: 'string',
        message: '请填写商户编号',
        trigger: 'blur'
      }
    ],
    // comments: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请填写商户简介',
    //     trigger: 'blur'
    //   }
    // ],
    status: [
      {
        required: true,
        type: 'number',
        message: '请选择商户状态',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        type: 'number',
        message: '请输入排序号',
        trigger: 'blur'
      }
    ],
    merchantOwner: [
      {
        required: true,
        type: 'number',
        message: '请绑定商户负责人',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          console.log(value);
          if (form.merchantOwner == 0) {
            return Promise.reject('请绑定商户负责人');
          }
          return Promise.resolve();
        }
      }
    ],
    merchantPhone: [
      {
        required: true,
        type: 'string',
        message: '请填写门店联系电话',
        trigger: 'blur'
      }
    ],
    merchantHours: [
      {
        required: true,
        type: 'string',
        message: '请填写商户营业时间',
        trigger: 'blur'
      }
    ],
    address: [
      {
        required: true,
        type: 'string',
        message: '请填写商户所在街道地址',
        trigger: 'blur'
      }
    ],
    lngAndLat: [
      {
        required: true,
        type: 'string',
        message: '请设置商户的定位信息',
        trigger: 'blur'
      }
    ],
    content: [
      {
        required: true,
        type: 'string',
        message: '请填写商户详情',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (content.value.length == 0) {
            return Promise.reject('请填写商户详情');
          }
          return Promise.resolve();
        }
      }
    ],
    region: [
      {
        required: true,
        type: 'string',
        message: '请选择商户所在区域',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (city.value.length == 0) {
            return Promise.reject('请选择商户所在区域');
          }
          return Promise.resolve();
        }
      }
    ]
    // ,
    // images: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请选择商户图片',
    //     trigger: 'blur',
    //     validator: async (_rule: RuleObject, value: string) => {
    //       if (images.value.length == 0) {
    //         return Promise.reject('请上传商户图片');
    //       }
    //       return Promise.resolve();
    //     }
    //   }
    // ]
  });

  // 插件
  const plugins = ref([
    gfm({
      locale: zh_HansGfm
    }),
    highlight()
  ]);

  /* 打开位置选择 */
  const openMapPicker = () => {
    showMap.value = true;
  };

  /* 地图选择后回调 */
  const onDone = (location: CenterPoint) => {
    city.value = [
      `${location.city?.province}`,
      `${location.city?.city}`,
      `${location.city?.district}`
    ];
    form.province = `${location.city?.province}`;
    form.city = `${location.city?.city}`;
    form.region = `${location.city?.district}`;
    form.address = `${location.address}`;
    form.lngAndLat = `${location.lng},${location.lat}`;
    showMap.value = false;
  };

  const onSelect = (item) => {
    form.merchantOwner = item.userId;
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const merchantForm = {
          ...form,
          content: content.value
        };
        const saveOrUpdate = isUpdate.value ? updateMerchant : addMerchant;
        saveOrUpdate(merchantForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            form.city = '[]';
            resetFields();
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          assignFields({
            ...props.data
          });
          images.value = [];
          images.value.push({
            uid: 1,
            url: props.data.logo,
            status: 'done'
          });
          content.value = props.data.content;
          city.value = [
            `${props.data.province}`,
            `${props.data.city}`,
            `${props.data.region}`
          ];
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
          content.value = '';
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
  .flex-sb {
    display: flex;
    justify-content: space-between;
  }
</style>
