<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="75%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '修改会员' : '添加会员'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <div style="background-color: #f3f3f3; padding: 8px">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-card title="基本信息" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <div class="upload-image">
                <ele-image-upload
                  v-model:value="avatar"
                  :limit="1"
                  :drag="true"
                  :item-style="{ width: '90px', height: '90px' }"
                  :upload-handler="uploadHandler"
                  @upload="onUpload"
                />
              </div>
              <a-form-item label="会员ID" name="userId">
                <span>{{ form.userId }}</span>
              </a-form-item>
              <a-form-item label="手机号码" name="phone">
                <a-input
                  allow-clear
                  placeholder="请输入手机号码"
                  :disabled="isUpdate"
                  v-model:value="form.phone"
                />
              </a-form-item>
              <a-form-item label="会员等级" name="gradeName">
                <SelectGrade
                  :placeholder="`请选择会员等级`"
                  v-model:value="form.gradeName"
                  :disabled="isUpdate"
                  @done="chooseGradeId"
                />
              </a-form-item>
              <a-form-item label="所属部门" name="organizationName">
                <SelectOrganization
                  :placeholder="`请选择部门`"
                  v-model:value="form.organizationName"
                  @done="chooseOrganization"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="账号" name="username">
                <a-input
                  allow-clear
                  placeholder="请输入会员账号"
                  :disabled="isUpdate"
                  v-model:value="form.username"
                />
              </a-form-item>
              <a-form-item label="昵称" name="nickname">
                <a-input
                  allow-clear
                  placeholder="请输入昵称"
                  v-model:value="form.nickname"
                />
              </a-form-item>
              <a-form-item label="角色" name="roles">
                <role-select v-model:value="form.roles" />
              </a-form-item>
              <a-form-item label="姓名" name="realName">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请输入真实姓名"
                  v-model:value="form.realName"
                />
              </a-form-item>
              <a-form-item label="性别" name="sex">
                <sex-select v-model:value="form.sex" />
              </a-form-item>
              <a-form-item label="备注">
                <a-textarea
                  :rows="4"
                  :maxlength="200"
                  placeholder="请输入备注"
                  v-model:value="form.comments"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="电子邮箱" name="email">
                <a-input
                  allow-clear
                  placeholder="请输入电子邮箱"
                  v-model:value="form.email"
                />
              </a-form-item>
              <a-form-item label="出生日期">
                <a-date-picker
                  class="ele-fluid"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择出生日期"
                  v-model:value="form.birthday"
                />
              </a-form-item>
              <a-form-item label="年龄" name="age">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请输入年龄"
                  v-model:value="form.age"
                />
              </a-form-item>
              <a-form-item label="所在地区" name="region">
                <a-input-group compact>
                  <a-input
                    disabled
                    style="width: calc(100% - 32px)"
                    v-model:value="form.region"
                    placeholder="所属区域"
                  />
                  <a-tooltip title="选择位置">
                    <a-button @click="openMapPicker">
                      <template #icon><EnvironmentOutlined /></template>
                    </a-button>
                  </a-tooltip>
                </a-input-group>
              </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="province">
                <a-input
                  allow-clear
                  placeholder="请输入所在省份"
                  v-model:value="form.province"
                />
              </a-form-item>
              <a-form-item label="所在城市" name="city">
                <a-input
                  allow-clear
                  placeholder="请输入所在城市"
                  v-model:value="form.city"
                />
              </a-form-item>
              <a-form-item label="经度" name="longitude">
                <a-input
                  allow-clear
                  placeholder="请输入经度"
                  v-model:value="form.longitude"
                />
              </a-form-item>
              <a-form-item label="纬度" name="latitude">
                <a-input
                  allow-clear
                  placeholder="请输入纬度"
                  v-model:value="form.latitude"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-divider style="height: 8px" />
        <a-card title="详细资料" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="兴趣爱好">
                <DictSelectMultiple
                  dict-code="interest"
                  v-model:value="userProfile.interest"
                  placeholder="选择兴趣爱好"
                />
              </a-form-item>
              <a-form-item label="个人简介">
                <a-textarea
                  :rows="4"
                  :maxlength="200"
                  placeholder="请输入个人简介"
                  v-model:value="form.introduction"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="身高" name="height">
                <DictSelect
                  dict-code="height"
                  v-model:value="userProfile.height"
                  placeholder="请选择身高"
                />
              </a-form-item>
              <a-form-item label="年收入" name="yearlyPay">
                <DictSelect
                  dict-code="yearlyPay"
                  v-model:value="userProfile.yearlyPay"
                  placeholder="请选择年收入"
                />
              </a-form-item>
              <a-form-item label="职业" name="position">
                <DictSelect
                  dict-code="vocation"
                  v-model:value="userProfile.position"
                  placeholder="请选择职业"
                />
              </a-form-item>
              <a-form-item label="有无小孩" name="hasChildren">
                <DictSelect
                  dict-code="hasChildren"
                  v-model:value="userProfile.hasChildren"
                  placeholder="请选择有无小孩"
                />
              </a-form-item>
              <a-form-item label="是否有车" name="hasCar">
                <DictSelect
                  dict-code="hasCar"
                  v-model:value="userProfile.hasCar"
                  placeholder="请选择是否有车"
                />
              </a-form-item>
              <a-form-item label="是否有房" name="hasHouse">
                <DictSelect
                  dict-code="hasHouse"
                  v-model:value="userProfile.hasHouse"
                  placeholder="请选择是否有房"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="体重" name="weight">
                <DictSelect
                  dict-code="weight"
                  v-model:value="userProfile.weight"
                  placeholder="请选择体重"
                />
              </a-form-item>
              <a-form-item label="学历" name="education">
                <DictSelect
                  dict-code="education"
                  v-model:value="userProfile.education"
                  placeholder="请选择学历"
                />
              </a-form-item>
              <a-form-item label="婚姻状况" name="maritalStatus">
                <DictSelect
                  dict-code="maritalStatus"
                  v-model:value="userProfile.maritalStatus"
                  placeholder="请选择婚姻状况"
                />
              </a-form-item>
              <a-form-item label="是否要小孩" name="haveChild">
                <DictSelect
                  dict-code="haveChild"
                  v-model:value="userProfile.haveChild"
                  placeholder="请选择是否要小孩"
                />
              </a-form-item>
              <a-form-item label="何时想结婚" name="whenMarried">
                <DictSelect
                  dict-code="whenMarried"
                  v-model:value="userProfile.whenMarried"
                  placeholder="请选择何时想结婚"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-divider style="height: 8px" />
        <a-card title="择偶条件" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="择偶区域">
                <regions-select
                  v-model:value="cityMate"
                  valueField="label"
                  placeholder="请选择省市区"
                  class="ele-fluid"
                  @change="onChangeRegionMate"
                />
              </a-form-item>
              <a-form-item label="年龄" name="ageMate">
                <DictSelect
                  dict-code="ageMate"
                  v-model:value="userProfile.ageMate"
                  placeholder="请选择年龄"
                />
              </a-form-item>
              <a-form-item label="体型" name="shapeMate">
                <DictSelect
                  dict-code="shapeMate"
                  v-model:value="userProfile.shapeMate"
                  placeholder="请选择体型"
                />
              </a-form-item>
              <a-form-item label="是否吸烟" name="isSmokingMate">
                <DictSelect
                  dict-code="isSmokingMate"
                  v-model:value="userProfile.isSmokingMate"
                  placeholder="请选择体型"
                />
              </a-form-item>
              <a-form-item label="是否喝酒" name="isDrinkMate">
                <DictSelect
                  dict-code="isDrinkMate"
                  v-model:value="userProfile.isDrinkMate"
                  placeholder="请选择是否喝酒"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="身高" name="heightMate">
                <DictSelect
                  dict-code="heightMate"
                  v-model:value="userProfile.heightMate"
                  placeholder="请选择身高"
                />
              </a-form-item>
              <a-form-item label="年收入" name="yearlyPayMate">
                <DictSelect
                  dict-code="yearlyPayMate"
                  v-model:value="userProfile.yearlyPayMate"
                  placeholder="请选择年收入"
                />
              </a-form-item>
              <a-form-item label="职业" name="vocationMate">
                <DictSelect
                  dict-code="vocation"
                  v-model:value="userProfile.vocationMate"
                  placeholder="请选择职业"
                />
              </a-form-item>
              <a-form-item label="有无小孩" name="hasChildrenMate">
                <DictSelect
                  dict-code="hasChildrenMate"
                  v-model:value="userProfile.hasChildrenMate"
                  placeholder="请选择有无小孩"
                />
              </a-form-item>
              <a-form-item label="是否有车" name="hasCarMate">
                <DictSelect
                  dict-code="hasCarMate"
                  v-model:value="userProfile.hasCarMate"
                  placeholder="请选择是否有车"
                />
              </a-form-item>
              <a-form-item label="是否有房" name="hasHouseMate">
                <DictSelect
                  dict-code="hasHouseMate"
                  v-model:value="userProfile.hasHouseMate"
                  placeholder="请选择是否有房"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="体重" name="weightMate">
                <DictSelect
                  dict-code="weightMate"
                  v-model:value="userProfile.weightMate"
                  placeholder="请选择体重"
                />
              </a-form-item>
              <a-form-item label="学历" name="educationMate">
                <DictSelect
                  dict-code="educationMate"
                  v-model:value="userProfile.educationMate"
                  placeholder="请选择学历"
                />
              </a-form-item>
              <a-form-item label="婚姻状况" name="maritalStatusMate">
                <DictSelect
                  dict-code="maritalStatusMate"
                  v-model:value="userProfile.maritalStatusMate"
                  placeholder="请选择婚姻状况"
                />
              </a-form-item>
              <a-form-item label="是否要小孩" name="haveChildMate">
                <DictSelect
                  dict-code="haveChildMate"
                  v-model:value="userProfile.haveChildMate"
                  placeholder="请选择是否要小孩"
                />
              </a-form-item>
              <a-form-item label="何时想结婚" name="whenMarriedMate">
                <DictSelect
                  dict-code="whenMarriedMate"
                  v-model:value="userProfile.whenMarriedMate"
                  placeholder="请选择何时想结婚"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-divider style="height: 8px" />
        <a-card title="会员相册" :bordered="false">
          <!--          <template #extra><a-button type="link" @click="handleEditStatus">上传</a-button></template>-->
          <div class="content">
            <ele-image-upload
              v-model:value="images"
              :limit="6"
              :drag="true"
              :item-style="{ width: '150px', height: '267px' }"
              :upload-handler="uploadHandlerImages"
              @upload="onUploadImages"
            />
            <small class="ele-text-placeholder">
              请上传应用截图(最多6张)，建议宽度300*533像素，小于2M/张
            </small>
          </div>
        </a-card>
      </a-form>
      <!-- 地图位置选择弹窗 -->
      <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"
      />
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import RoleSelect from './role-select.vue';
  import SexSelect from './sex-select.vue';
  import { EnvironmentOutlined } from '@ant-design/icons-vue';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { User } from '@/api/system/user/model';
  import { uploadFile } from '@/api/system/file';
  import { FILE_SERVER } from '@/config/setting';
  import { CenterPoint } from 'ele-admin-pro/es/ele-map-picker/types';
  import useFormData from '@/utils/use-form-data';
  import { addUser, updateUser } from '@/api/system/user';
  import { Organization } from '@/api/system/organization/model';
  import { assignObject } from 'ele-admin-pro';
  import { UserProfile } from '@/api/love/user-profile/model';
  import { Grade } from '@/api/user/grade/model';

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

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

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 用户头像
  const avatar = ref<ItemType[]>([]);
  // 已上传数据
  const images = ref<ItemType[]>([]);
  // 是否显示地图选择弹窗
  const showMap = ref(false);
  const keywords = ref<string>();
  // 省市区
  const city = ref<string[]>([]);
  // 省市区
  const cityMate = ref<string[]>([]);
  const { darkMode } = storeToRefs(themeStore);
  const formRef = ref<FormInstance | null>(null);
  // 详细资料
  const userProfile = ref<UserProfile>({
    userId: props.data?.userId,
    interest: undefined
  });

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<User>({
    userId: undefined,
    type: undefined,
    username: '',
    nickname: '',
    realName: '',
    province: '',
    city: '',
    region: '',
    address: '',
    longitude: '',
    latitude: '',
    alias: '',
    companyName: '',
    organizationName: '',
    sex: undefined,
    roles: [],
    email: '',
    phone: '',
    password: '',
    introduction: '',
    organizationId: undefined,
    birthday: '',
    idCard: '',
    comments: '',
    gradeName: ''
  });

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

  // 表单验证规则
  const rules = reactive({
    username: [
      {
        required: true,
        type: 'string',
        message: '请输入会员账号',
        trigger: 'blur'
      }
    ],
    phone: [
      {
        required: true,
        type: 'string',
        message: '请输入合法手机号码',
        trigger: 'blur'
      }
    ],
    nickname: [
      {
        required: true,
        type: 'string',
        message: '请输入昵称',
        trigger: 'blur'
      }
    ],
    roles: [
      {
        required: true,
        message: '请选择角色',
        type: 'array',
        trigger: 'blur'
      }
    ]
    // securityStatus: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请选择安全状态',
    //     trigger: 'blur'
    //   }
    // ],
    // companyName: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请选择租赁单位',
    //     trigger: 'blur'
    //   }
    // ],
    // customerName: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请选择承租单位',
    //     trigger: 'blur'
    //   }
    // ],
    // projectRegion: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请输入会员地址',
    //     trigger: 'blur'
    //   }
    // ]
  });

  const chooseOrganization = (e: Organization) => {
    form.organizationName = e.organizationName;
    form.organizationId = e.organizationId;
  };

  const chooseGradeId = (data: Grade) => {
    form.gradeName = data.name;
    form.gradeId = data.gradeId;
  };

  /* 地图选择后回调 */
  const onDone = (location: CenterPoint) => {
    console.log(location);
    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.latitude = `${location.lat}`;
    form.longitude = `${location.lng}`;
    showMap.value = false;
  };

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

  const onChangeRegionMate = (e) => {
    userProfile.value.province = `${e[0]}`;
    userProfile.value.city = `${e[1]}`;
    userProfile.value.region = `${e[2]}`;
    userProfile.value.area = `${e[0]} ${e[1]} ${e[2]}`;
    userProfile.value.provinceMate = e[0];
    userProfile.value.cityMate = e[1];
    userProfile.value.regionMate = e[2];
    userProfile.value.areaMate = `${e[0]} ${e[1]} ${e[2]}`;
  };

  /* 上传事件 */
  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) => {
        form.avatar = data.thumbnail;
        avatar.value.push({
          uid: data.id,
          url: FILE_SERVER + data.path,
          status: 'done'
        });
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  /* 上传事件 */
  const uploadHandlerImages = (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;
    }
    onUploadImages(item);
  };

  // 上传文件
  const onUploadImages = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: FILE_SERVER + data.path,
          status: 'done',
          type: 'image'
        });
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const onSearch = (text) => {
    keywords.value = text;
    reload();
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        userProfile.value.interest = JSON.stringify(userProfile.value.interest);
        userProfile.value.images = JSON.stringify(images.value);
        const formData = {
          ...form,
          userProfile: userProfile.value
        };
        const saveOrUpdate = isUpdate.value ? updateUser : addUser;
        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 reload = () => {
    loading.value = true;
  };
  reload();

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields({
            ...props.data
          });
          images.value = [];
          avatar.value = [];
          if (props.data.avatar) {
            avatar.value.push({
              uid: String(props.data.userId),
              url: props.data.avatar,
              status: 'done'
            });
          }
          city.value = [
            `${props.data.province}`,
            `${props.data.city}`,
            `${props.data.region}`
          ];
          cityMate.value = [
            `${props.data.userProfile?.provinceMate}`,
            `${props.data.userProfile?.cityMate}`,
            `${props.data.userProfile?.regionMate}`
          ];
          if (props.data.userProfile) {
            const data = props.data.userProfile;
            userProfile.value = data;
            if (typeof data.interest === 'string') {
              userProfile.value.interest = JSON.parse(data.interest);
            }
            if (data.images) {
              const arr = JSON.parse(data.images);
              arr.map((d) => {
                images.value.push({
                  uid: d.uid,
                  url: d.url,
                  status: 'done'
                });
              });
            }
            if (props.data.birthday) {
              form.age =
                new Date().getFullYear() -
                Number(props.data.birthday.slice(0, 4));
            }
          }
          reload();
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }

  .ml-10 {
    margin-left: 5px;
  }

  .upload-text {
    margin-right: 70px;
  }

  .upload-image {
    margin-bottom: 30px;
    display: flex;
    justify-content: center;
    text-align: center;
  }
</style>
