<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="880"
    :visible="visible"
    :confirm-loading="loading"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑企业' : '添加企业'"
    :body-style="{ paddingBottom: '8px' }"
    @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: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="企业简称" name="shortName">
              <a-input
                allow-clear
                :maxlength="30"
                placeholder="请输入企业简称"
                v-model:value="form.shortName"
              />
            </a-form-item>
            <a-form-item label="企业类型" name="companyTypeMultiple">
              <DictSelectMultiple
                dict-code="CompanyType"
                placeholder="请选择企业类型"
                v-model:value="form.companyTypeMultiple"
              />
            </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="20"
                placeholder="请填写联系人手机号码"
                v-model:value="form.phone"
              />
            </a-form-item>
            <a-form-item label="企业logo" name="companyLogo">
              <ele-image-upload
                v-model:value="images"
                :item-style="{ width: '90px', height: '90px' }"
                :limit="1"
                @upload="onUpload"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="企业全称" name="companyName">
              <a-input
                allow-clear
                :maxlength="30"
                placeholder="请输入企业全称"
                v-model:value="form.companyName"
              />
            </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="所属区域"
                  @search="onSearch"
                />
                <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="sortNumber">
              <a-input
                allow-clear
                :maxlength="20"
                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-col>
        </a-row>
        <!-- 地图位置选择弹窗 -->
        <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, computed} from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addCompany, updateCompany } from '@/api/system/company';
  import type { Company } from '@/api/system/company/model';
  import { createCode } from '@/utils/common';
  import { uploadFile } from '@/api/system/file';
  import type { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FILE_SERVER, FILE_THUMBNAIL } from "@/config/setting";
  import { useUserStore } from '@/store/modules/user';
  import {
    EnvironmentOutlined
  } from '@ant-design/icons-vue';
  import { useThemeStore } from "@/store/modules/theme";
  import { storeToRefs } from "pinia";
  import { CenterPoint } from "ele-admin-pro/es/ele-map-picker/types";
  import { FormInstance } from "ant-design-vue/es/form";

  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 city = ref<string[]>([]);
  // 是否显示地图选择弹窗
  const showMap = ref(false);
  const themeStore = useThemeStore();
  const { darkMode } = storeToRefs(themeStore);
  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  const formRef = ref<FormInstance | null>(null);

  // 用户信息
  const form = reactive<Company>({
    companyId: undefined,
    companyName: '',
    shortName: '',
    companyLogo: undefined,
    companyType: undefined,
    companyTypeMultiple: undefined,
    companyCode: undefined,
    province: '',
    city: '',
    region: '',
    address: '',
    businessEntity: '',
    phone: '',
    comments: '',
    status: undefined,
    sortNumber: 100,
    userId: undefined,
  });

  // 已上传数据, 可赋初始值用于回显
  const images = ref(<any>[]);

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

  // 表单验证规则
  const rules = reactive({
    shortName: [
      {
        required: true,
        type: 'string',
        message: '请输入企业简称',
        trigger: 'blur'
      }
    ],
    companyName: [
      {
        required: true,
        type: 'string',
        message: '请选择企业全称',
        trigger: 'blur'
      }
    ],

  });

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

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

  /* 地图选择后回调 */
  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 save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          // 去除空格
          shortName: form.shortName?.replace(/\s*/g, ''),
          companyName: form.companyName?.replace(/\s*/g, ''),
          companyTypeMultiple: JSON.stringify(form.companyTypeMultiple)
        };
        const saveOrUpdate = isUpdate.value
          ? updateCompany
          : 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 onUpload = (d: ItemType) => {
    uploadFile(<File>d.file)
      .then((result) => {
        form.companyLogo = result.path;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          assignObject(form, props.data);
          // 头像赋值
          images.value = [];
          if(props.data.companyLogo){
            images.value.push({ uid:1, url: FILE_THUMBNAIL + props.data.companyLogo, status: '' });
          }
          if(props.data.companyTypeMultiple){
            form.companyTypeMultiple = JSON.parse(props.data.companyTypeMultiple);
          }
          // 所在地区
          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>
<style lang="less"></style>
