<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? `编辑${typeName}` : `创建${typeName}`"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    :confirm-loading="loading"
    @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="头像" name="avatar">
        <SelectFile
          :placeholder="`请选择图片`"
          :limit="1"
          :data="images"
          @done="chooseImage"
          @del="onDeleteItem"
        />
      </a-form-item>
      <a-form-item :label="`${typeName}名称`" name="websiteName">
        <div class="flex w-full justify-between gap-2">
          <a-input
            allow-clear
            :placeholder="`请输入${typeName}名称`"
            v-model:value="form.websiteName"
          />
          <a-tooltip :title="`关联租户套餐(${form.templateId})`">
            <SelectCmsWebsiteTemplate
              :placeholder="`关联产品模型`"
              class="form-item"
              v-model:value="form.templateId"
              @done="chooseTemplate"
            />
          </a-tooltip>
          <a-tooltip :title="`${form.developer}${form.companyId}`">
            <SelectSuperAdmin
              :placeholder="`绑定超级管理员`"
              class="form-item"
              v-model:value="form.companyId"
              @done="chooseCompanyId"
            />
          </a-tooltip>
        </div>
      </a-form-item>
      <a-form-item label="网站域名" name="domain" v-if="form.type == 10">
        <a-input
          v-model:value="form.domain"
          placeholder="yourname"
        >
          <template #addonBefore>
            <a-select v-model:value="form.prefix" style="width: 90px">
              <a-select-option value="https://">https://</a-select-option>
              <a-select-option value="http://">http://</a-select-option>
            </a-select>
          </template>
        </a-input>
      </a-form-item>
      <a-form-item label="后台管理" name="adminUrl">
        <div class="flex w-full justify-between gap-2">
          <a-input
            v-model:value="form.adminUrl"
            placeholder="后台管理地址"
            addon-before="https://"
          />
        </div>
      </a-form-item>
      <a-form-item label="AppId" name="websiteCode" v-if="form.type == 20">
        <div class="flex w-full justify-between gap-2">
          <a-input
            v-model:value="form.websiteCode"
            placeholder="AppId"
          />
        </div>
      </a-form-item>
      <a-form-item label="AppSecret" name="AppSecret" v-if="form.type == 20">
        <div class="flex w-full">
          <span>**********</span><a class="px-3">重置</a>
        </div>
      </a-form-item>
      <a-form-item :label="`${typeName}描述`" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          :placeholder="`请输入${typeName}描述`"
          v-model:value="form.comments"
        />
      </a-form-item>
      <a-form-item label="SEO关键词" name="keywords" v-if="form.type == 10">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入SEO关键词"
          v-model:value="form.keywords"
        />
      </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 label="软件版本" name="version">-->
      <!--        <a-radio-group-->
      <!--          v-model:value="form.version"-->
      <!--        >-->
      <!--          <a-radio :value="10">免费版</a-radio>-->
      <!--          <a-radio :value="20">授权版</a-radio>-->
      <!--        </a-radio-group>-->
      <!--      </a-form-item>-->
      <!--      <a-form-item label="tenantID">-->
      <!--        <a-input-->
      <!--          v-model:value="form.tenantId"-->
      <!--          placeholder="请输入tenantID"-->
      <!--        />-->
      <!--      </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="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} from 'ele-admin-pro';
import {CmsWebsite} from '@/api/cms/cmsWebsite/model';
import {useThemeStore} from '@/store/modules/theme';
import {storeToRefs} from 'pinia';
import {FormInstance} from 'ant-design-vue/es/form';
import {ItemType} from 'ele-admin-pro/es/ele-image-upload/types';
import {FileRecord} from '@/api/system/file/model';
import {updateCmsWebsiteAll} from "@/api/cms/cmsWebsiteAll";
import {User} from "@/api/system/user/model";

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

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

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

// 提交状态
const loading = ref(false);
const typeName = ref<string>('网站')
const showAppSecret = ref<boolean>(false)
// 是否显示最大化切换按钮
const maxable = ref(true);
// 表格选中数据
const formRef = ref<FormInstance | null>(null);
const images = ref<ItemType[]>([]);
const websiteQrcode = ref<ItemType[]>([]);
const oldDomain = ref();
const files = ref<ItemType[]>([]);
const adminUrl = ref('');

// 用户信息
const form = reactive<CmsWebsite>({
  websiteId: undefined,
  websiteLogo: undefined,
  websiteName: undefined,
  websiteCode: undefined,
  type: undefined,
  templateId: undefined,
  companyId: undefined,
  developer: undefined,
  files: undefined,
  keywords: '',
  prefix: 'https',
  domain: '',
  adminUrl: '',
  style: '',
  icpNo: undefined,
  email: undefined,
  version: undefined,
  websiteType: '',
  running: 1,
  expirationTime: undefined,
  sortNumber: undefined,
  comments: undefined,
  status: undefined,
  statusText: undefined,
  tenantId: undefined
});

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

// 表单验证规则
const rules = reactive({
  adminUrl: [
    {
      required: true,
      type: 'string',
      message: '请填写后台管理地址',
      trigger: 'blur'
    }
  ],
  keywords: [
    {
      required: true,
      type: 'string',
      message: '请填写SEO关键词',
      trigger: 'blur'
    }
  ],
  running: [
    {
      required: true,
      type: 'number',
      message: '请选择网站状态',
      trigger: 'change'
    }
  ],
  domain: [
    {
      required: true,
      type: 'string',
      message: '请填写网站域名',
      trigger: 'blur'
    }
  ],
  websiteCode: [
    {
      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 chooseFile = (data: FileRecord) => {
//   files.value.push({
//     uid: data.id,
//     url: data.url,
//     status: 'done'
//   });
// };

const chooseCompanyId = (item: User) => {
  form.companyId = item.userId;
  form.companyName = item.realName;
  form.developer = item.nickname;
}

const chooseTemplate = (item: CmsWebsite) => {
  form.templateId = item.templateId;
  form.adminUrl = item.adminUrl;
  form.websiteType = item.websiteName;
  form.prefix = item.prefix;
}

// const onDeleteFile = (index: number) => {
//   files.value.splice(index, 1);
// };

// 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,
        files: JSON.stringify(files.value),
      };
      updateCmsWebsiteAll(formData)
        .then((msg) => {
          loading.value = false;
          updateVisible(false);
          message.destroy();
          message.success(msg);
          // window.location.reload();
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          message.destroy();
          message.error(e.message);
        });
    })
    .catch(() => {
    });
};

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      images.value = [];
      files.value = [];
      websiteQrcode.value = [];
      if (props.data?.websiteId) {
        assignObject(form, props.data);
        if(props.data.type == 10){
          typeName.value = '网站'
        }
        if(props.data.type == 20){
          typeName.value = '小程序'
        }
        if (props.data.websiteLogo) {
          images.value.push({
            uid: uuid(),
            url: props.data.websiteLogo,
            status: 'done'
          });
        }
        if (props.data.files) {
          files.value = JSON.parse(props.data.files);
        }
        if (props.data.websiteCode) {
          oldDomain.value = props.data.websiteCode;
        }
        if (props.data.adminUrl) {
          const split = props.data.adminUrl.split('.');
          adminUrl.value = split[0];
        }
        isUpdate.value = true;
      } else {
        isUpdate.value = false;
      }
    } else {
      resetFields();
    }
  },
  {immediate: true}
);
</script>
