<!-- 编辑弹窗 -->
<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="avatar">
        <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="domain">
        <a-input
          v-model:value="form.domain"
          placeholder="websoft.top"
          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="全局样式(Tailwind CSS风格)"
          v-model:value="form.style"
        />
      </a-form-item>
      <!--      <a-form-item label="访问域名" name="domain">-->
      <!--        <a-input-->
      <!--          v-model:value="form.domain"-->
      <!--          placeholder="websoft.top"-->
      <!--          addon-before="https://"-->
      <!--          addon-after="websoft.top"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <!--      <a-form-item label="后台管理" name="adminUrl">-->
      <!--        <a-input v-model:value="form.adminUrl" placeholder="admin.domain.com">-->
      <!--          <template #addonBefore>-->
      <!--            <a-select v-model:value="form.prefix" style="width: 90px">-->
      <!--              <a-select-option value="http://">http://</a-select-option>-->
      <!--              <a-select-option value="https://">https://</a-select-option>-->
      <!--            </a-select>-->
      <!--          </template>-->
      <!--        </a-input>-->
      <!--      </a-form-item>-->
      <!--      <a-form-item label="ICP备案号" name="icpNo">-->
      <!--        <a-input-->
      <!--          allow-clear-->
      <!--          placeholder="请输入网站备案"-->
      <!--          v-model:value="form.icpNo"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <!--      <a-form-item label="网站类型" name="websiteType">-->
      <!--        <a-select-->
      <!--          :options="websiteType"-->
      <!--          :value="form.websiteType"-->
      <!--          placeholder="请选择主体类型"-->
      <!--          @change="onWebsiteType"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <!--      <a-form-item label="当前版本" name="version">-->
      <!--        <a-tag color="red" v-if="form.version === 10">免费版</a-tag>-->
      <!--        <a-tag color="green" v-if="form.version === 20">专业版</a-tag>-->
      <!--        <a-tag color="cyan" v-if="form.version === 30">永久授权</a-tag>-->
      <!--      </a-form-item>-->
      <a-form-item label="状态" name="status">
        <a-radio-group
          v-model:value="form.status"
          :disabled="form.status && form.status > 3"
        >
          <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.status == 2" label="维护说明" name="statusText">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="状态说明"
          v-model:value="form.statusText"
        />
      </a-form-item>
      <!--      <a-divider style="margin-bottom: 24px" />-->
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid, SelectProps } from 'ele-admin-pro';
  import { addWebsite, updateWebsite } from '@/api/system/website';
  import { Website } from '@/api/system/website/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';

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

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

  // 用户信息
  const form = reactive<Website>({
    websiteId: undefined,
    websiteLogo: undefined,
    websiteName: undefined,
    websiteCode: undefined,
    keywords: '',
    prefix: '',
    domain: '',
    adminUrl: '',
    style: '',
    icpNo: undefined,
    email: undefined,
    version: undefined,
    websiteType: '',
    expirationTime: undefined,
    sortNumber: undefined,
    comments: undefined,
    status: undefined,
    statusText: undefined
  });

  const websiteType = ref<SelectProps['options']>([
    {
      value: '企业官网',
      label: '企业官网'
    },
    {
      value: '门户网站',
      label: '门户网站'
    },
    {
      value: '电子商城',
      label: '电子商城'
    }
  ]);

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

  // 表单验证规则
  const rules = reactive({
    comments: [
      {
        required: true,
        type: 'string',
        message: '请填写网站描述',
        trigger: 'blur'
      }
    ],
    keywords: [
      {
        required: true,
        type: 'string',
        message: '请填写SEO关键词',
        trigger: 'blur'
      }
    ],
    domain: [
      {
        required: true,
        type: 'string',
        message: '请填写网站域名',
        trigger: 'blur'
      }
    ],
    adminUrl: [
      {
        required: true,
        type: 'string',
        message: '请填写网站后台管理地址',
        trigger: 'blur'
      }
    ],
    icpNo: [
      {
        required: true,
        type: 'string',
        message: '请填写ICP备案号',
        trigger: 'blur'
      }
    ],
    appSecret: [
      {
        required: true,
        type: 'string',
        message: '请填写网站秘钥',
        trigger: 'blur'
      }
    ],
    websiteName: [
      {
        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.downloadUrl;
  };

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

  const onWebsiteType = (text: string) => {
    form.websiteType = text;
  };

  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 ? updateWebsite : addWebsite;
        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 = [];
        websiteQrcode.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>
