<!-- 编辑弹窗 -->
<template>
  <ele-modal
    width="60%"
    :visible="visible"
    :maskClosable="false"
    :title="isUpdate ? '编辑租户' : '添加租户'"
    :body-style="{ paddingBottom: '28px', backgroundColor: '#F0F2F5FF' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 20 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <a-card title="基本信息" :bordered="false">
        <a-row :gutter="16">
          <a-col
            v-bind="styleResponsive ? { md: 11, sm: 24, xs: 24 } : { span: 8 }"
          >
            <a-form-item label="租户名称" name="shortName">
              <a-input
                allow-clear
                placeholder="请输入租户名称"
                v-model:value="form.shortName"
              />
            </a-form-item>
            <a-form-item label="客户类型" name="companyType">
              <DictSelect
                dict-code="CompanyType"
                placeholder="请选择客户类型"
                v-model:value="form.companyType"
              />
            </a-form-item>
            <a-form-item label="企业名称" name="companyName">
              <a-input
                allow-clear
                placeholder="请输入企业完整名称"
                v-model:value="form.companyName"
              />
            </a-form-item>
            <a-form-item label="统一社会信用代码" name="companyCode">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请输入社会统一信用代码"
                v-model:value="form.companyCode"
              />
            </a-form-item>
            <a-form-item label="法定代表人" name="businessEntity">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请填写法定代表人"
                v-model:value="form.businessEntity"
              />
            </a-form-item>
            <a-form-item label="手机号码" name="phone">
              <a-input
                allow-clear
                :maxlength="11"
                :disabled="isUpdate"
                placeholder="请填写法定代表手机号"
                v-model:value="form.phone"
              />
            </a-form-item>
            <a-form-item label="登录密码" name="password" v-if="!isUpdate">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请填写登录密码"
                v-model:value="form.password"
              />
            </a-form-item>
            <a-form-item label="电子邮箱" name="email">
              <a-input
                allow-clear
                placeholder="请填写电子邮箱"
                v-model:value="form.email"
              />
            </a-form-item>
            <a-form-item label="座机电话" name="tel">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请填写座机电话"
                v-model:value="form.tel"
              />
            </a-form-item>
            <a-form-item label="官方网站" name="domain">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请填写官方网站域名"
                v-model:value="form.domain"
              />
            </a-form-item>
            <a-form-item label="LOGO" name="logo">
              <SelectFile
                :placeholder="`请选择图片`"
                :limit="1"
                :data="images"
                @done="chooseFile"
                @del="onDeleteItem"
              />
            </a-form-item>
          </a-col>
          <a-col
            v-bind="styleResponsive ? { md: 11, sm: 24, xs: 24 } : { span: 8 }"
          >
            <a-form-item label="所属行业" name="industry">
              <industry-select
                v-model:value="industry"
                valueField="label"
                placeholder="请选择所属行业"
                class="ele-fluid"
              />
            </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="region">
              <regions-select
                v-model:value="city"
                valueField="label"
                placeholder="请选择省市区"
                class="ele-fluid"
              />
            </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="comments">
              <a-textarea
                :rows="4"
                :maxlength="200"
                placeholder="请输入备注信息"
                v-model:value="form.comments"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </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"
    />
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, phoneReg } from 'ele-admin-pro';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { EnvironmentOutlined } from '@ant-design/icons-vue';
  import { FormInstance, type RuleObject } from 'ant-design-vue/es/form';
  import { Company } from '@/api/system/company/model';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import {
    updateCompany,
    addCompany,
    updateCompanyAll
  } from '@/api/system/company';
  import { CenterPoint } from 'ele-admin-pro/es/ele-map-picker/types';
  import { FileRecord } from '@/api/system/file/model';
  import { getMerchantId, getUserId } from '@/utils/common';
  import { emailReg } from 'ele-admin-pro/es';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);
  const { darkMode } = storeToRefs(themeStore);
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Company | null;
  }>();

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  const userId = getUserId();
  // 当期时间
  // 已上传数据
  const images = ref<ItemType[]>([]);
  // 类型 single|multiple
  // const type = ref<string>('single');
  // 日期范围选择
  const content = ref('');
  const requirement = ref('');
  // 是否显示地图选择弹窗
  const showMap = ref(false);
  // 省市区
  const city = ref<string[]>([]);
  const formRef = ref<FormInstance | null>(null);

  // 用户信息
  const form = reactive<Company>({
    companyId: undefined,
    companyName: '',
    companyCode: '',
    businessEntity: '',
    companyType: undefined,
    industryParent: '',
    industryChild: '',
    shortName: '',
    phone: '',
    email: '',
    companyLogo: undefined,
    domain: '',
    sortNumber: undefined,
    comments: '',
    tenantName: '',
    province: '',
    city: '',
    region: '',
    latitude: '',
    longitude: '',
    address: '',
    nickname: '',
    merchantId: 0,
    createTime: '',
    status: undefined
  });

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

  // 表单验证规则
  const rules = reactive({
    companyName: [
      {
        required: true,
        type: 'string',
        message: '请填写企业名称',
        trigger: 'blur'
      }
    ],
    companyType: [
      {
        required: true,
        type: 'string',
        message: '请选择企业类型',
        trigger: 'blur'
      }
    ],
    shortName: [
      {
        required: true,
        type: 'string',
        message: '请填写租户名称',
        trigger: 'blur'
      }
    ],
    phone: [
      {
        pattern: phoneReg,
        required: true,
        type: 'string',
        message: '手机号格式不正确',
        trigger: 'blur'
      }
    ],
    businessEntity: [
      {
        required: true,
        type: 'string',
        message: '请填写企业法定代表人',
        trigger: 'blur'
      }
    ],
    email: [
      {
        pattern: emailReg,
        required: true,
        type: 'string',
        message: '电子邮箱格式不正确',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        type: 'string',
        message: '请填写登录密码',
        trigger: 'blur'
      }
    ],
    region: [
      {
        required: true,
        type: 'string',
        message: '请选择所在区域',
        trigger: 'blur'
      }
    ],
    industry: [
      {
        required: true,
        type: 'string',
        message: '请选择所属行业',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (!industry.value[1]) {
            return Promise.reject('请选择所属行业');
          } else {
            return Promise.resolve();
          }
        }
      }
    ]
  });

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

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

  /* 地图选择后回调 */
  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 chooseFile = (data: FileRecord) => {
    images.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.companyLogo = data.path;
  };

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

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          content: content.value,
          merchantId: getMerchantId(),
          industryParent: industry.value[0],
          industryChild: industry.value[1]
        };
        console.log(formData);
        const saveOrUpdate = isUpdate.value ? updateCompanyAll : addCompany;
        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 industry = ref<string[]>([
    String(form.industryParent),
    String(form.industryChild)
  ]);

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        content.value = '';
        requirement.value = '';
        if (props.data) {
          assignObject(form, props.data);
          images.value = [];
          if (props.data.companyLogo) {
            images.value.push({
              uid: 0,
              url: props.data.companyLogo,
              status: 'done'
            });
          }
          industry.value[0] = String(props.data.industryParent);
          industry.value[1] = String(props.data.industryChild);
          // 所在地区
          if (props.data.province) {
            city.value.push(props.data.province);
          }
          if (props.data.city) {
            city.value.push(props.data.city);
          }
          if (props.data.region) {
            city.value.push(props.data.region);
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
