<template>
  <a-modal
    v-model:open="modalVisible"
    :title="modalTitle"
    centered
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    width="50%"
    :okButtonProps="okBtnStatus"
    :cancelButtonProps="cancelBtnStatus"
    :okText="okText"
    :cancelText="cancelText"
  >
    <template v-if="showCreateSite">
      <a-spin :spinning="spinning" :tip="tipTitle">
        <a-form ref="createSiteFormsRef" :model="createSiteForm" :rules="createSiteFormRules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-item>
            我们将为您新建站点，稍后请移至“站群管理”对网站内容进行编辑<br />
            在建站完成后，需要您将域名解析到指定的CNAME将网站发布上线<br />
            您可在“站群管理”中查看建站进度和CNAME
          </a-form-item>
          <a-form-item name="uid" label="用户名称">
            <a-select
              v-model:value="createSiteForm.uid"
              show-search
              :options="userList"
              :filter-option="filterOption"
              :field-names="{ label: 'realname', value: 'id' }"
              placeholder="请选择用户名称"
            />
          </a-form-item>
          <a-form-item name="name" label="站点名称">
            <a-input v-model:value="createSiteForm.name" placeholder="请输入站点名称" />
          </a-form-item>
          <a-form-item name="languageCode" label="站点语言">
            <j-search-select placeholder="请选择站点语言" v-model:value="createSiteForm.languageCode" dict="adweb_language" />
          </a-form-item>
          <a-form-item name="planId" label="营销方案">
            <a-row :gutter="8">
              <a-col :span="21">
                <j-search-select placeholder="请选择营销方案" v-model:value="createSiteForm.planId" dict="subscribe_plan,plan_name,id,status=1" />
              </a-col>
              <a-col :span="3">
                <router-link :to="{ path: '/deliver/serp/seoMarketPlan/list', query: { from: 'themeList' } }">
                  <a-button type="primary" block>新增</a-button>
                </router-link>
              </a-col>
            </a-row>
          </a-form-item>

          <a-form-item label="赠送天数" name="giveDay" v-show="createSiteForm.planId !== undefined">
            <a-input-number :min="0" :max="1000" style="width: 100%" placeholder="赠送天数" v-model:value="createSiteForm.giveDay" />
          </a-form-item>
          <a-form-item label="补偿天数" name="compensateDay" v-show="createSiteForm.planId !== undefined">
            <a-input-number :min="0" :max="1000" style="width: 100%" placeholder="补偿天数" v-model:value="createSiteForm.compensateDay" />
          </a-form-item>
        </a-form>
      </a-spin>
    </template>

    <template v-if="showResult">
      <a-result status="success" title="站点创建完成!" />
    </template>
  </a-modal>
</template>
<script setup lang="ts">
  import JSearchSelect from '@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { onBeforeMount, reactive, ref } from 'vue';
  import { getAction, postActionForm } from '@/api/manage/manage';
  import { useMessage } from '@/hooks/web/useMessage';

  const createSiteFormRules = reactive({
    uid: [{ required: true, message: '请选择用户名称', trigger: 'blur' }],
    name: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
    languageCode: [{ required: true, message: '站点语言不能为空', trigger: 'change' }],
    planId: [{ required: true, message: '请选择营销方案', trigger: 'blur' }],
  });
  const modalTitle = ref('');
  const showResult = ref(false);
  const confirmLoading = ref(false);
  const labelCol = reactive({ span: 3 });
  const wrapperCol = reactive({ span: 21 });

  const okText = ref('');
  const cancelText = ref('');
  const spinning = ref(false);
  const showCreateSite = ref(false);
  let createSiteForm = reactive({
    uid: undefined,
    templateId: undefined,
    source: '',
    name: '',
    languageCode: 'en',
    parentCode: '',
    planId: undefined,
    giveDay: 0,
    compensateDay: 0,
  });
  const tipTitle = ref('');

  let okBtnStatus = reactive({});
  const createSiteFormsRef = ref();

  const modalVisible = ref(false);

  const siteCreating = ref(false);
  const isWpSiteCreate = ref(false);

  const url = reactive({
    createSiteUrl: 'siteManage/createSite',
    addSiteLanguageUrl: 'siteManage/addSiteLanguage',
    getTemplateTagsUrl: '/adweb/adwebThemeC/getTemplateTags',
    wpSiteCreateUrl: 'wpWebSite/addWebsite',
    getAdwebVipUrl: 'adweb/adwebSiteManage/getAdwebVip',
  });
  const newCreateSiteInfo = ref('');
  let userList = reactive([{ id: '', realname: '' }]);
  let cancelBtnStatus = reactive({});

  const ins = ref(0);
  // 用户搜索
  const filterOption = (input: string, option: any) => {
    if (option.realname == null) {
      return false;
    }
    return option.realname.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  const { createMessage } = useMessage();

  function cleanAllFormData() {
    confirmLoading.value = false;

    spinning.value = false;
    tipTitle.value = '';
    modalVisible.value = false;
    modalTitle.value = '';
    showCreateSite.value = false;

    createSiteFormsRef.value.resetFields();
    createSiteForm = {
      uid: undefined,
      languageCode: 'en',
      source: '',
      name: '',
      parentCode: '',
      planId: undefined,
      giveDay: 0,
      compensateDay: 0,
    };
    showResult.value = false;
    ins.value = 0;
  }

  onBeforeMount(() => {
    getUserList();
  });

  //创建站点
  function initCreateSiteModel(item) {
    isWpSiteCreate.value = true;
    createSiteForm.templateId = item.id;
    modalVisible.value = true;
    modalTitle.value = '创建站点';
    showCreateSite.value = true;
    okText.value = '确定';
    cancelText.value = '取消';
  }

  async function handleOk() {
    if (showCreateSite.value && isWpSiteCreate.value) {
      await createSiteFormsRef.value.validateFields();
      wpSiteCreate();
    }

    if (showResult.value && isWpSiteCreate) {
      toMyWPSite();
    }
  }

  function handleCancel() {
    cleanAllFormData();
  }

  //wp站点创建成功预览
  function toMyWPSite() {
    return window.open('http://' + newCreateSiteInfo.value, '_blank');
  }

  //wp站点创建
  function wpSiteCreate() {
    if (siteCreating.value) {
      createMessage.warning('站点创建中，请勿重复点击！');
      return;
    }

    siteCreating.value = true;
    confirmLoading.value = false;
    spinning.value = true;
    tipTitle.value = '正在创建站点';
    okBtnStatus = { props: { disabled: true } };
    cancelBtnStatus = { props: { disabled: true } };

    postActionForm(url.wpSiteCreateUrl, createSiteForm, 1000 * 60 * 5)
      .then(function (res) {
        if (res.code === 200 && res.result === 'ignore') {
          createMessage.error('您距离上个站点创建不足两分钟，请两分钟后再次尝试！');
          return;
        }
        if (res.code === 200) {
          showCreateSite.value = false;
          showResult.value = true;
          modalTitle.value = '系统提示';
          okText.value = '预览站点';
          cancelText.value = '关闭';
          showCreateSite.value = false;
          okBtnStatus = {};
          cancelBtnStatus = {};
          newCreateSiteInfo.value = res.data;
        } else {
          cancelBtnStatus = {};
          createMessage.error('网站创建失败，请重试！');
        }
      })
      .catch(function () {
        modalVisible.value = true;
        createMessage.error('网络超时，请重试!');
      })
      .finally(() => {
        siteCreating.value = false;
        spinning.value = false;
        tipTitle.value = '';
      });
  }

  async function getUserList() {
    getAction(url.getAdwebVipUrl, null).then(function (res) {
      if (res.code == 200) {
        userList = res.result;
      }
    });
  }

  defineExpose({ initCreateSiteModel });
</script>
