<template>
  <a-drawer title="站点发布" width="720" v-model:open="modalVisible" :body-style="{ paddingBottom: '80px' }" @close="handleCancel">
    <!--      wp站点发布-->
    <a-spin :spinning="spinning" :tip="tipTitle">
      <a-form
        ref="ruleForm"
        :model="wpPublishForm"
        :rules="wpPublishFormRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        style="text-align: center !important"
      >
        <a-form-item ref="server" label="生产服务器" name="serverIp">
          <a-select
            placeholder="请选择生产服务器"
            style="text-align: left"
            showSearch
            allowClear
            :filter-option="filterOption"
            v-model:value="wpPublishForm.ip"
            :options="serverList"
            @change="changeServer"
            :field-names="{ label: 'serverName', value: 'serverIp' }"
          />
        </a-form-item>
        <a-form-item ref="domain" label="域名" name="domain">
          <a-input-search
            v-model:value="wpPublishForm.domain"
            placeholder="请输入域名"
            enter-button="检测"
            :loading="loadingBtn"
            size="default"
            @search="checkWpDomain"
          />
        </a-form-item>
        <p>域名请勿带http://或https://</p>
        <p>请确保您填写的域名指向我们给定CNAME</p>
        <p>如有问题请联系域名供应商</p>
        <p>此过程大约需要2分钟，稍后您可以到我的网站查看结果</p>
        <p>如未显示请刷新页面后重试</p>
      </a-form>
    </a-spin>

    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-button type="primary" @click="handleOk" :loading="loadingDrawerBtn"> 提交 </a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
  import { getAction, postAction, postActionForm } from '@/api/manage/manage';
  import { reactive, ref } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';

  const modalVisible = ref(false);
  const labelCol = reactive({ span: 3 });
  const wrapperCol = reactive({ span: 21 });
  const spinning = ref(false);
  const loadingBtn = ref(false);
  const loadingDrawerBtn = ref(false);
  const tipTitle = ref('');

  const wpPublishFormRules = reactive({
    domain: [{ required: true, message: '请输入正确网站域名格式', trigger: 'blur' }],
    serverIp: [{ required: true, message: '请选择生产服务器', trigger: 'submit' }],
  });
  const { createMessage } = useMessage();
  const url = {
    serverListUrl: '/adweb/adwebServer/list',
    checkDomainUrl: '/wpWebSite/check/domain',
    wpSiteReleaseUrl: '/wpWebSite/releaseWebsite',
  };

  const emit = defineEmits(['ok', 'close', 'reload']);

  //服务器搜索
  const filterOption = (input: string, option: any) => {
    return option.serverName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  let wpPublishForm = reactive({ cname: '', ip: '', domain: '', siteCode: '' });
  let serverList = reactive([{ id: '', serverName: '', serverIp: '', cname: '' }]);
  let selectServer = reactive({ id: '', serverName: '', serverIp: '', cname: '' });

  function init(record) {
    modalVisible.value = true;
    spinning.value = true;

    console.log(record, 'record');
    wpPublishForm.siteCode = record.code;

    getAction(url.serverListUrl, null)
      .then(function (res) {
        spinning.value = false;
        if (res.code === 200) {
          serverList = res.result.records;
        }
      })
      .catch(function (err) {
        console.log(err);
      });
  }

  function changeServer(value) {
    if (value !== undefined) {
      // 更改选中的站点对象
      for (let i in serverList) {
        if (serverList[i].serverIp === value) {
          selectServer = serverList[i];
        }
      }
    } else {
      selectServer = reactive({ serverName: '', serverIp: '', cname: '' });
    }
  }

  // 检测域名
  function checkWpDomain() {
    loadingBtn.value = true;
    if (wpPublishForm.domain == null || wpPublishForm.domain === '') {
      createMessage.error('域名不能为空！');
      loadingBtn.value = false;
      return;
    }

    if (selectServer.serverIp == null || selectServer.serverIp === '') {
      createMessage.error('请选择生产服务器之后再次检测！');
      loadingBtn.value = false;
      return;
    }

    let params = {
      domain: wpPublishForm.domain,
      cname: selectServer.cname,
      ip: selectServer.serverIp,
    };
    let checkDomainUrl = `${url.checkDomainUrl}`;
    postActionForm(checkDomainUrl, params, 120000)
      .then(function (res) {
        loadingBtn.value = false;
        if (res.code === 200) {
          createMessage.success('检测成功,域名可用！');
        } else if (res.code === 101) {
          createMessage.error('域名请勿以http://或https://开头');
        } else if (res.code === 103) {
          createMessage.error('请确认您的域名已指向CNAME或IP');
        } else if (res.code === 100) {
          createMessage.warning('请勿提交我们的CNAME或IP');
        } else if (res.code === 102) {
          createMessage.warning('您填写的域名已发布或被他人使用，请勿重复提交！');
        }
      })
      .catch(function (err) {
        console.log(err);
      });
  }

  async function handleOk() {
    loadingBtn.value = true;
    if (wpPublishForm.domain == null || wpPublishForm.domain === '') {
      createMessage.error('域名不能为空！');
      loadingBtn.value = false;
      return;
    }

    if (selectServer.serverIp == null || selectServer.serverIp === '') {
      createMessage.error('请选择生产服务器之后再次检测！');
      loadingBtn.value = false;
      return;
    }

    let params = {
      domain: wpPublishForm.domain,
      cname: selectServer.cname,
      ip: selectServer.serverIp,
    };
    let checkDomainUrl = `${url.checkDomainUrl}`;
    postActionForm(checkDomainUrl, params, 120000)
      .then(function (res) {
        loadingBtn.value = false;
        if (res.code === 200) {
          spinning.value = true;
          tipTitle.value = '正在发布站点';
          let data = {
            serverId: selectServer.id,
            domain: wpPublishForm.domain,
            siteCode: wpPublishForm.siteCode,
          };
          let wpSiteReleaseUrl = `${url.wpSiteReleaseUrl}`;
          postActionForm(wpSiteReleaseUrl, data, 120000)
            .then(function (res) {
              if (res.code === 200) {
                createMessage.success(res.message);

                spinning.value = false;
                tipTitle.value = '';
                modalVisible.value = false;
                emit('reload');
              }
            })
            .catch(function () {
              createMessage.error('网络超时，请重试!');
              emit('reload');
            });
        } else if (res.code === 101) {
          createMessage.error('域名请勿以http://或https://开头');
        } else if (res.code === 103) {
          createMessage.error('请确认您的域名已指向CNAME或IP');
        } else if (res.code === 100) {
          createMessage.warning('请勿提交我们的CNAME或IP');
        } else if (res.code === 102) {
          createMessage.warning('您填写的域名已发布或被他人使用，请勿重复提交！');
        }
      })
      .catch(function (err) {
        console.log(err);
      });
  }

  function handleCancel() {
    wpPublishForm.cname = '';
    wpPublishForm.ip = '';
    wpPublishForm.domain = '';
    wpPublishForm.siteCode = '';
    spinning.value = false;
    modalVisible.value = false;
    loadingDrawerBtn.value = false;
    loadingBtn.value = false;
  }

  defineExpose({ init });
</script>

<style scoped lang="less"></style>
