<!-- 编辑弹窗 -->
<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="`网站Logo`" name="websiteLogo">
        <SelectFile
          :placeholder="`请上传封面图`"
          :limit="1"
          :data="images"
          @done="chooseImage"
          @del="onDeleteItem"
        />
      </a-form-item>
      <a-form-item label="网站名称" name="websiteName">
        <a-input
          allow-clear
          placeholder="华为官网"
          v-model:value="form.websiteName"
        />
      </a-form-item>
      <a-form-item label="赠送域名" name="websiteCode">
        <a-input
          v-model:value="form.websiteCode"
          placeholder="huawei"
          addon-before="https://"
          addon-after=".wsdns.cn"
        />
      </a-form-item>
      <a-form-item label="自定义域名" name="domain">
        <a-input
          v-model:value="form.domain"
          placeholder="huawei.com"
          addon-before="https://"
        />
      </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-item label="SEO关键词" name="keywords">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入SEO关键词"
          v-model:value="form.keywords"
        />
      </a-form-item>
      <a-form-item label="全局样式" name="style">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="全局样式"
          v-model:value="form.style"
        />
      </a-form-item>
      <a-form-item label="状态" name="running">
        <a-radio-group
          v-model:value="form.running"
          :disabled="form.running == 4 || form.running == 5"
        >
          <a-radio :value="1">运行中</a-radio>
          <a-radio :value="2">维护中</a-radio>
          <a-radio :value="3">已关闭</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="form.running == 2" label="维护说明" name="statusText">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="状态说明"
          v-model:value="form.statusText"
        />
      </a-form-item>
      <a-divider  style="height: 30px" />
<!--      <a-form-item label="网站类型" name="websiteType">-->
<!--        <DictSelect-->
<!--          dict-code="SiteType"-->
<!--          :width="200"-->
<!--          :show-search="true"-->
<!--          placeholder="网站类型"-->
<!--          v-model:value="form.websiteType"-->
<!--          @done="chooseWebsiteType"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="独立部署地址" name="adminUrl">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入独立部署的后台管理地址"-->
<!--          v-model:value="form.adminUrl"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="服务器ID" name="assetsId">-->
<!--        <SelectAssets-->
<!--          :placeholder="`所属服务器`"-->
<!--          class="form-item"-->
<!--          v-model:value="form.assetsName"-->
<!--          @done="chooseAssets"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="模版" name="templateId">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="选择使用模版"-->
<!--          v-model:value="form.templateId"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="所属行业" name="industryChild">-->
<!--        <industry-select-->
<!--          v-model:value="form.industryChild"-->
<!--          valueField="label"-->
<!--          placeholder="请选择所属行业"-->
<!--          class="ele-fluid"-->
<!--          @change="onIndustry"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="企业ID" name="companyId">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入企业ID"-->
<!--          v-model:value="form.companyId"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="所在国家" name="country">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入所在国家"-->
<!--          v-model:value="form.country"-->
<!--        />-->
<!--      </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="province">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入所在省份"-->
<!--          v-model:value="form.province"-->
<!--        />-->
<!--      </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="ICP备案号" name="icpNo">
        <a-input
          allow-clear
          placeholder="请输入ICP备案号"
          v-model:value="form.icpNo"
        />
      </a-form-item>
      <a-form-item label="公安备案" name="policeNo">
        <a-input
          allow-clear
          placeholder="请输入公安备案"
          v-model:value="form.policeNo"
        />
      </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="remarks">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入管理员备注"
          v-model:value="form.remarks"
        />
      </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 } from 'ele-admin-pro';
  import { addOaAssetsSite, updateOaAssetsSite } from '@/api/oa/oaAssetsSite';
  import { OaAssetsSite } from '@/api/oa/oaAssetsSite/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 { CenterPoint } from 'ele-admin-pro/es/ele-map-picker/types';
  import {DictionaryData} from "@/api/system/dictionary-data/model";
  import {OaAssets} from "@/api/oa/oaAssets/model";

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: OaAssetsSite | 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 showMap = ref(false);

  // 用户信息
  const form = reactive<OaAssetsSite>({
    websiteId: undefined,
    websiteName: undefined,
    websiteCode: undefined,
    websiteIcon: undefined,
    websiteLogo: undefined,
    websiteDarkLogo: undefined,
    websiteType: undefined,
    keywords: undefined,
    prefix: undefined,
    domain: undefined,
    style: undefined,
    adminUrl: undefined,
    version: undefined,
    expirationTime: undefined,
    templateId: undefined,
    industryParent: undefined,
    industryChild: undefined,
    companyId: undefined,
    country: undefined,
    province: undefined,
    city: undefined,
    region: undefined,
    longitude: undefined,
    latitude: undefined,
    lngAndLat: '',
    address: undefined,
    phone: undefined,
    email: undefined,
    icpNo: undefined,
    policeNo: undefined,
    comments: undefined,
    remarks: undefined,
    recommend: undefined,
    status: undefined,
    statusText: undefined,
    statusClose: undefined,
    styles: undefined,
    running: undefined,
    assetsId: undefined,
    assetsName: undefined,
    userId: undefined,
    userIds: undefined,
    deleted: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined,
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules = reactive({
    oaAssetsSiteName: [
      {
        required: true,
        type: 'string',
        message: '请填写网站信息记录表名称',
        trigger: 'blur'
      }
    ]
  });

  const chooseImage = (data: FileRecord) => {
    images.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.websiteLogo = data.path;
  };

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


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

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

  // const chooseWebsiteType = (data: DictionaryData) => {
  //   form.websiteType = data.dictDataName;
  //   // form.websiteType = data.dictDataCode;
  // };
  //
  // const onIndustry = (item: any) => {
  //   form.industryParent = item[0]
  //   form.industryChild = item[1];
  // };
  //
  // const chooseAssets = (data: OaAssets) => {
  //   form.assetsId = data.assetsId;
  //   form.assetsName = data.name;
  // };

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

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateOaAssetsSite : addOaAssetsSite;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if(props.data.websiteLogo){
            images.value.push({
              uid: uuid(),
              url: props.data.websiteLogo,
              status: 'done'
            })
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>

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