<!-- 编辑弹窗 -->
<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="image">
        <SelectFile
          :placeholder="`请选择图片`"
          :limit="1"
          :data="images"
          @done="chooseImage"
          @del="onDeleteItem"
        />
      </a-form-item>
      <a-form-item label="商户名称" name="merchantName">
        <a-input
          allow-clear
          :maxlength="100"
          placeholder="xxx店"
          v-model:value="form.merchantName"
        />
      </a-form-item>
      <a-form-item
        label="商户手机号"
        name="phone"
        extra="手机号码将用做于商户端的登录账号请填写真实手机号码"
      >
        <a-input
          allow-clear
          :maxlength="11"
          placeholder="请输入商户手机号"
          v-model:value="form.phone"
        />
      </a-form-item>
      <a-form-item label="商户姓名" name="realName">
        <a-input
          allow-clear
          :maxlength="100"
          placeholder="请输入商户姓名"
          v-model:value="form.realName"
        />
      </a-form-item>
      <a-form-item label="店铺类型" name="shopType">
        <SelectMerchantType
          :placeholder="`请选择店铺类型`"
          v-model:value="form.shopType"
          @done="chooseShopType"
        />
      </a-form-item>
      <a-form-item label="经营类型" name="merchantCategoryId">
        <a-cascader v-model:value="merchantCategoryId" :options="merchantCategoryList"
                    :field-names="{ label: 'title', value: 'categoryId' }"
                    @change="selectMerchantCategory"
                    placeholder="请选择经营类型"/>
      </a-form-item>
      <a-form-item label="商户分类" name="category">
        <industry-select
          v-model:value="form.category"
          valueField="label"
          placeholder="请选择所属行业"
          class="ele-fluid"
          @change="onIndustry"
        />
      </a-form-item>
      <a-form-item label="商户坐标" name="lngAndLat">
        <div class="flex-sb">
          <a-input
            allow-clear
            placeholder="请选择所在位置"
            v-model:value="form.lngAndLat"
            disabled
          />
          <a-button
            class="ele-btn-icon"
            style="margin-left: 10px"
            @click="openMapPicker"
          >
            打开地图位置选择器
          </a-button>
        </div>
      </a-form-item>
      <a-form-item label="商户地址" name="address">
        <a-input
          allow-clear
          :maxlength="100"
          placeholder="请输入商户地址"
          v-model:value="form.address"
        />
      </a-form-item>
      <a-form-item label="手续费(%)" name="commission">
        <a-input-number
          :step="1"
          :max="100"
          :min="0.0"
          :precision="2"
          class="ele-fluid"
          placeholder="请输入手续费"
          v-model:value="form.commission"
        />
      </a-form-item>
      <a-form-item label="关键字" name="keywords">
        <a-select
          v-model:value="form.keywords"
          mode="tags"
          placeholder="输入关键词后回车"
        />
      </a-form-item>
      <a-form-item label="资质图片" name="files">
        <SelectFile
          :placeholder="`请选择图片`"
          :limit="9"
          :data="files"
          @done="chooseFiles"
          @del="onDeleteFiles"
        />
      </a-form-item>
      <a-form-item label="是否自营" name="ownStore">
        <a-switch
          checked-children="是"
          un-checked-children="否"
          :checked="form.ownStore === 1"
          @update:checked="updateOwnStore"
        />
      </a-form-item>
      <a-form-item label="是否推荐" name="recommend">
        <a-switch
          checked-children="是"
          un-checked-children="否"
          :checked="form.recommend === 1"
          @update:checked="updateRecommend"
        />
      </a-form-item>
      <a-form-item label="是否需要审核" name="goodsReview">
        <a-switch
          checked-children="是"
          un-checked-children="否"
          :checked="form.goodsReview === 1"
          @update:checked="updateGoodsReview"
        />
      </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="9999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.sortNumber"
        />
      </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>
  <!-- 地图位置选择弹窗 -->
  <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"
  />
</template>

<script lang="ts" setup>
import {ref, reactive, watch} from 'vue';
import {Form, message} from 'ant-design-vue';
import {assignObject, uuid, phoneReg} from 'ele-admin-pro';
import {addMerchant, updateMerchant} from '@/api/shop/merchant';
import {Merchant} from '@/api/shop/merchant/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 {MerchantType} from '@/api/shop/merchantType/model';
import {CenterPoint} from 'ele-admin-pro/es/ele-map-picker/types';
import {listRoles} from '@/api/system/role';
import {getTenantId} from '@/utils/domain';
import {MerchantCategory} from "@/api/shop/merchantCategory/model";
import {listMerchantCategory} from "@/api/shop/merchantCategory";

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

const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: Merchant | 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 files = ref<ItemType[]>([]);
// 是否显示地图选择弹窗
const showMap = ref(false);

// 用户信息
const form = reactive<Merchant>({
  merchantId: undefined,
  merchantName: undefined,
  image: undefined,
  phone: undefined,
  realName: undefined,
  shopType: undefined,
  category: undefined,
  merchantCategoryId: undefined,
  merchantCategoryTitle: undefined,
  province: '',
  city: '',
  region: '',
  address: '',
  lngAndLat: '',
  lng: '',
  lat: '',
  commission: 0,
  keywords: undefined,
  files: undefined,
  ownStore: undefined,
  recommend: undefined,
  goodsReview: 1,
  comments: '',
  adminUrl: '',
  status: 0,
  sortNumber: 100,
  roleId: undefined,
  roleName: '',
  tenantId: undefined
});

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

// 表单验证规则
const rules = reactive({
  merchantName: [
    {
      required: true,
      type: 'string',
      message: '请填写商户名称',
      trigger: 'blur'
    }
  ],
  category: [
    {
      required: true,
      type: 'string',
      message: '请填写商户分类',
      trigger: 'blur'
    }
  ],
  lngAndLat: [
    {
      required: true,
      type: 'string',
      message: '请填写商户坐标',
      trigger: 'blur'
    }
  ],
  realName: [
    {
      required: true,
      type: 'string',
      message: '请填写商户姓名',
      trigger: 'blur'
    }
  ],
  shopType: [
    {
      required: true,
      type: 'string',
      message: '请选择店铺类型',
      trigger: 'blur'
    }
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      pattern: phoneReg,
      message: '手机号格式不正确',
      type: 'string'
    }
  ],
  merchantCategoryId: [
    {
      required: true,
      type: 'number',
      message: '请选择经营类型',
      trigger: 'blur'
    }
  ]
});

const chooseShopType = (data: MerchantType) => {
  form.shopType = data.name;
};

const merchantCategoryId = ref<number[]>([])
const selectMerchantCategory = (value: number[]) => {
  if (value.length < 2) return message.error('请选择二级分类')
  form.merchantCategoryId = value[1];
  const data = merchantCategoryList.value.find(item => item.categoryId === value[1])
  if (data) {
    form.merchantCategoryTitle = data.title;
  }
  console.log(value)
};

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 chooseFiles = (data: FileRecord) => {
  files.value.push({
    uid: data.id,
    url: data.path,
    status: 'done'
  });
};

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

/* 地图选择后回调 */
const onDone = (location: CenterPoint) => {
  // city.value = [
  //   `${location.city?.province}`,
  //   `${location.city?.city}`,
  //   `${location.city?.district}`
  // ];
  if (location) {
    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}`;
    form.lng = location.lng?.toString();
    form.lat = location.lat?.toString();
  }
  showMap.value = false;
};

const onDeleteFiles = (index: number) => {
  files.value.splice(index, 1);
};

const updateOwnStore = (value: boolean) => {
  form.ownStore = value ? 1 : 0;
};

const updateRecommend = (value: boolean) => {
  form.recommend = value ? 1 : 0;
};

const updateGoodsReview = (value: boolean) => {
  form.goodsReview = value ? 1 : 0;
};

const onIndustry = (item: any) => {
  form.category = item[0] + '/' + item[1];
};

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

/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }

  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      const formData = {
        ...form,
        keywords: JSON.stringify(form.keywords),
        files: JSON.stringify(files.value)
      };
      const saveOrUpdate = isUpdate.value ? updateMerchant : addMerchant;
      saveOrUpdate(formData)
        .then((msg) => {
          loading.value = false;
          message.success(msg);
          updateVisible(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          message.error(e.message);
        });
    })
    .catch(() => {
    });
};

const merchantCategoryList = ref<MerchantCategory[]>([]);
const getMerchantCategoryList = async () => {
  merchantCategoryList.value = await listMerchantCategory({
    parentId: 0
  });
}

watch(
  () => props.visible,
  async (visible) => {
    if (visible) {
      await getMerchantCategoryList()
      images.value = [];
      files.value = [];
      merchantCategoryId.value = [];
      if (props.data) {
        isUpdate.value = true;
        assignObject(form, props.data);
        if (props.data.image) {
          images.value.push({
            uid: uuid(),
            url: props.data.image,
            status: 'done'
          });
        }
        if (props.data.files) {
          const arr = JSON.parse(props.data.files);
          arr.map((item) => {
            files.value.push({
              uid: uuid(),
              url: item.url,
              status: 'done'
            });
          });
        }
        if (props.data.keywords) {
          form.keywords = JSON.parse(props.data.keywords);
        }
        if (props.data && props.data.merchantCategoryId) {
          merchantCategoryList.value.forEach(item => {
            const cate = item.children?.find(i => i.categoryId === props?.data?.merchantCategoryId)
            if (cate) merchantCategoryId.value.push(item?.categoryId, cate.categoryId)
          });
        }
      } else {
        isUpdate.value = false;
      }
      // 获取商户管理员的roleId
      listRoles({roleCode: 'merchant'}).then((res) => {
        form.roleId = res[0].roleId;
        form.roleName = res[0].roleName;
      });
    } else {
      resetFields();
    }
  },
  {immediate: true}
);
</script>

<style lang="less" scoped>
.flex-sb {
  display: flex;
  justify-content: space-between;
}
</style>
