<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="750"
    :visible="visible"
    :confirm-loading="loading"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑仓库' : '添加仓库'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
      <a-form
        :label-col="{ md: { span: 6 }, sm: { span: 20 }, xs: { span: 24 } }"
        :wrapper-col="{ md: { span: 24 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="仓库名称" name="warehouseName">
              <a-input
                allow-clear
                :maxlength="30"
                placeholder="请输入仓库名称"
                v-model:value="form.warehouseName"
              />
            </a-form-item>
            <a-form-item label="负责人" name="warehouseKeeper">
              <a-input
                allow-clear
                :maxlength="30"
                placeholder="请输入负责人"
                v-model:value="form.warehouseKeeper"
              />
            </a-form-item>
            <a-form-item label="负责人电话" name="warehousePhone">
              <a-input
                allow-clear
                :maxlength="30"
                placeholder="请输入负责人联系电话"
                v-model:value="form.warehousePhone"
              />
            </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-col :md="12" :sm="24" :xs="24">
            <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="regionName">
              <a-input
                allow-clear
                :maxlength="30"
                placeholder="请输入区域名称"
                v-model:value="form.regionName"
              />
            </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="longitude">
              <a-input
                allow-clear
                :maxlength="30"
                disabled
                placeholder="请输入经度"
                v-model:value="form.longitude"
              />
            </a-form-item>
            <a-form-item label="纬度" name="latitude">
              <a-input
                allow-clear
                :maxlength="30"
                disabled
                placeholder="请输入纬度"
                v-model:value="form.latitude"
              />
            </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 { addWarehouse, updateWarehouse } from '@/api/tower/warehouse';
  import type { Warehouse } from '@/api/tower/warehouse/model';
  import { uploadFile } from '@/api/system/file';
  import type { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FILE_SERVER } from '@/config/setting';
  import { useUserStore } from '@/store/modules/user';
  import {
    EnvironmentOutlined
  } from '@ant-design/icons-vue';
  import { CenterPoint } from "ele-admin-pro/es/ele-map-picker/types";
  import { useThemeStore } from "@/store/modules/theme";
  import { storeToRefs } from "pinia";

  const userStore = useUserStore();
  // 当前用户信息
  const loginUser = computed(() => userStore.info ?? {});
  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  const themeStore = useThemeStore();
  const { darkMode } = storeToRefs(themeStore);

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

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);

  // 用户信息
  const form = reactive<Warehouse>({
    warehouseName: '',
    warehouseKeeper: undefined,
    warehousePhone: '',
    regionName: '',
    longitude: '',
    latitude: '',
    country: '',
    province: '',
    city: '',
    region: '',
    address: '',
    status: 0,
    userId: undefined,
    comments: '',
    sortNumber: 100,
    warehouseId: 0,
  });

  // 已上传数据, 可赋初始值用于回显
  const images = ref(<any>[]);
  // 省市区
  const city = ref<string[]>([]);
  // 是否显示地图选择弹窗
  const showMap = ref(false);

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

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

  // 选择地区
  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.regionName = `${location.city?.city}${location.city?.district}`;
    form.address = `${location.address}`;
    form.latitude = `${location.lat}`;
    form.longitude = `${location.lng}`;
    showMap.value = false;
  };

  // 表单验证规则
  const rules = reactive({
    warehouseName: [
      {
        required: true,
        type: 'string',
        message: '请输入仓库名称',
        trigger: 'blur'
      }
    ],
    warehouseCode: [
      {
        required: true,
        type: 'string',
        message: '请输入合法的IP地址',
        trigger: 'blur'
      }
    ],
    progress: [
      {
        required: true,
        type: 'string',
        message: '请选择跟进状态',
        trigger: 'blur'
      }
    ]
  });

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

  /* 保存编辑 */
  const save = () => {
    validate()
      .then(() => {
        loading.value = true;
        // 去除空格
        form.warehouseName = form.warehouseName?.replace(/\s*/g, '');
        // 判断权限
        // if (loginUser.value.roles?.[0].roleCode != 'admin'){
        //   form.status = '1';
        // }
        const data = {
          ...form
        };
        // 转字符串
        const saveOrUpdate = isUpdate.value ? updateWarehouse : addWarehouse;
        saveOrUpdate(data)
          .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.warehouseAvatar = result.path;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          // 头像赋值
          images.value = [];
          if(props.data.warehouseAvatar){
            images.value.push({ uid:1, url: FILE_SERVER + props.data.warehouseAvatar, status: '' });
          }
          assignObject(form, props.data);
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less"></style>
