<template>
    <div class="page-container" 
      v-loading="applyHttpsDomain.isShowWaitLoading"
      :element-loading-text="applyHttpsDomain.waitLoadingText"
      >
      <div class="card">
        <div class="tip-title flex">
          <img src="@/assets/site/prompt-icon-1.svg" alt="" class="mr-10">使用提示
        </div>
        <div class="card-content">
            <div class="number-container mr-10">1.</div>
            <div class="descriptions">
                <div class="desc-item"><div class="desc-text"><p style="color: #1E2226;">使用场景</p></div></div>
                <div class="desc-item"><div class="desc-text"><p>推广途径需求：使用360，百度等推广方式时，需要使用您自己的域名</p></div></div>
                <div class="desc-item"><div class="desc-text"><p>宣传自己公司：有自己的公司，使用自己公司域名更容易让人记住，能达到宣传效果</p></div></div>
            </div>
        </div>
        <div class="card-content">
            <div class="number-container mr-10">2.</div>
            <div class="descriptions">
                <div class="desc-item"><div class="desc-text"><p style="color: #1E2226;">说明</p></div></div>
                <div class="desc-item"><div class="desc-text"><p>站点级：使用自己的域名，生成独立的访问链接，站点下的服务链接根据站点生成</p></div></div>
                <div class="desc-item"><div class="desc-text"><p>服务级：对单独的服务链接进行设置，设置后只改变此服务的链接，不影响站点及其他服务链接</p></div></div>
            </div>
        </div>
        <div class="card-content">
            <div class="number-container mr-10">3.</div>
            <div class="descriptions">
                <div class="desc-item"><div class="desc-text"><p style="color: #1E2226;">使用</p></div></div>
                <div class="desc-item"><div class="desc-text"><p>站点专属域名设置路径：首页->站点设置</p></div></div>
                <div class="desc-item"><div class="desc-text"><p>服务专属域名设置路径：首页->服务列表->修改->独立域名（服务未开通需要先开通服务）</p></div></div>
            </div>
        </div>
        <div class="card-content">
            <div class="number-container mr-10">4.</div>
            <div class="descriptions">
                <div class="desc-item"><div class="desc-text"><p style="color: #1E2226;">如何添加专属域名</p></div></div>
                <div class="desc-item"><div class="desc-text"><p>备案：所添加的域名必须在阿里云备案</p></div></div>
                <div class="desc-item"><div class="desc-text"><p>解析：将域名增加CNAME解析到“ lunwen.kuailedns.com ”（记录类型：CNAME；记录值：lunwen.kuailedns.com）</p></div></div>
            </div>
        </div>
      </div>

      <div class="register-wrap">
          <div class="step3-wrap">
              <div>
                  <div class="flex-common table-wrap">
                      <div class="step3-top flex">
                          <h3 class="flex">域名列表</h3>
                          <GuipButton @click="showAddDomainDialog">新增域名</GuipButton>
                      </div>
                      <el-form>
                          <GuipTable :border="true" :tableData="domainList" :loading="tableLoading">
                            <el-table-column prop="domain" fixed="left" label="域名"></el-table-column>
                            <el-table-column prop="beian" label="备案"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                <div class="flex">
                                    <el-button v-if="scope.row.is_https == false" @click="showGetHttpsCert(scope.row)" type="text">申请免费HTTPS证书</el-button>
                                    <el-button v-else @click="showGetHttpsCert(scope.row)" type="text">更新HTTPS证书</el-button>
                                    <span class="expiretime gray" v-if="scope.row.is_https == true && scope.row.https_expiring_soon == false">（{{ scope.row.https_expire_time }}）</span>
                                    <span class="expiretime red" v-if="scope.row.is_https == true && scope.row.https_expiring_soon == true">（{{ scope.row.https_expire_time }}）</span>
                                </div>
                                </template>
                            </el-table-column>
                          </GuipTable>
                      </el-form>
                  </div>
              </div>
          </div>
      </div>

      <GuipDialog :dialogVisible="applyHttpsDomain.isShowDialog" title="申请HTTPS证书" :show-close-button="false"
          :show-cancel-button="true" @confirm="handleConfirm" @cancel="handleCancel"
          @close="handleClose" @dialogVisibleChange="dialogVisibleChange"
          :close-on-click-modal="false"
          :confirmText="applyHttpsDomain.confirmText">
          <!-- 自定义内容 -->
          <el-form>
            <GuipInput column="column" v-model="applyHttpsDomain.domain" ref="GuipInput" label="域名" class="mt10" disabled />
            <div class="tip-message" v-if="applyHttpsDomain.isShowDnsTxt">
              <p class="flex"> <img src="@/assets/tip_blue.svg" alt="" class="mr-10">请添加DNS解析记录</p>
              <p>记录类型：TXT</p>
              <p>主机记录：_acme-challenge</p>
              <p>记录值：{{ applyHttpsDomain.dnsValue }}</p>
            </div>
            
          </el-form>
      </GuipDialog>

      <domainAdd :visible="isShowAddDomainDialog" :authToken="authToken" @update:visible="handleEvent"></domainAdd>

    </div>
</template>
<script>
import GuipButton from '@/components/GuipButton.vue';
import GuipTable from '@/components/GuipTable.vue';
import GuipDialog from '@/components/GuipDialog.vue';
import GuipInput from '@/components/GuipInput.vue';
import domainAdd from '@/components/domainAdd.vue';

export default {
  components: {
    GuipButton,
    GuipTable,
    GuipDialog,
    GuipInput,
    domainAdd,
  },
  data() {
    return {
      // AUTH
      token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NTI2NDY1NDUsIm5iZiI6MTc1MjY0NjU0NSwiZXhwIjoxNzU1MjM4NTQ1LCJ1c2VyIjoic3VidXNlciIsImxvZ2luX3R5cGUiOjAsImFpZCI6IjEifQ.G-Is-x9qPMiV_urOlDPQVRjfAIozySxL5EK2k82d46k',
      // 域名列表
      domainList: [],
      // 表格加载
      tableLoading: false,

      applyHttpsDomain: {
        domain: '',
        isShowDialog: false,
        confirmText: '申请',
        confirmType: 1, // 1:申请 2:验证
        isShowWaitLoading: false,
        waitLoadingText: '申请中，请稍等',
        getDnsTxtTimer: null,
        timerTime: 2000,
        isShowDnsTxt: false,
        getVerifyDnsResultTimer: null,
        dnsValue: '',
      },

      isShowAddDomainDialog: false,
      authToken: '',
    }
  },
  computed: {
    
  },
  mounted() {
    this.getPrivateDomains()
  },
  methods: {
    // 获取支付列表
    getPrivateDomains() {
        this.tableLoading = true
        const that = this
        that.payList = []
        this.$http('POST', '/agentnew/ajax_get_private_domain_list', {
            gid: this.gid,
        },{
            headers:{
                'Auth': this.token
            }
        }).then(response => {
            this.tableLoading = false
            this.$nextTick(() => {
                that.domainList = response.data
            })
        }).catch(error => {
            console.error(error, 'error')
        })
    },

    applyHttpsCert() {
      this.$http('POST', '/agentnew/ajax_apply_https_cert', {
          domain: this.applyHttpsDomain.domain,
      }, {
          headers: {
              'Auth': this.token
          }
      }).then(response => {
          this.$nextTick(() => {
              if (response.status) {
                console.log(response.data)
                // 已经申请过 直接出现验证弹层
                if (response.data.data && response.data.data.name && response.data.data.value) {
                  this.applyHttpsDomain.dnsValue = response.data.data.value
                  // 弹层内容更新
                  this.applyHttpsDomain.confirmText = '已解析，现在验证';
                  this.applyHttpsDomain.isShowDnsTxt = true;
                  this.applyHttpsDomain.confirmType = 2;
                  // 打开弹层
                  this.applyHttpsDomain.isShowDialog = true;
                  // 关闭等待加载
                  this.applyHttpsDomain.isShowWaitLoading = false;
                  // 清除定时器
                  this.clearApplyHttpsTimer();
                  return true;
                }
                
                // 显示等待加载
                this.applyHttpsDomain.isShowWaitLoading = true;
                this.applyHttpsDomain.waitLoadingText = '申请中，请稍等';

                // 关闭弹框
                this.applyHttpsDomain.isShowDialog = false;
                
                // 开始轮询获取DNS TXT
                this.startTimer(response.data.keys);
              } else {
                  this.$Message.error(response.info);
              }
          })
      }).catch(error => {
          console.error(error, 'error')
      })
    },
    getHttpsDnsTxt(getHttpsDnsTxt) {
      this.$http('POST', '/agentnew/ajax_get_https_dns_txt', {
          keys: getHttpsDnsTxt
      }, {
          headers: {
              'Auth': this.token
          }
      }).then(response => {
          this.$nextTick(() => {
              if (response.status) {
                if (response.data.wait == 1) {
                  return;
                }

                this.applyHttpsDomain.dnsValue = response.data.value
                // 弹层内容更新
                this.applyHttpsDomain.confirmText = '已解析，现在验证';
                this.applyHttpsDomain.isShowDnsTxt = true;
                this.applyHttpsDomain.confirmType = 2;
                // 打开弹层
                this.applyHttpsDomain.isShowDialog = true;
                // 关闭等待加载
                this.applyHttpsDomain.isShowWaitLoading = false;
                // 清除定时器
                this.clearApplyHttpsTimer();
              } else {
                  // 关闭等待加载
                  this.applyHttpsDomain.isShowWaitLoading = false;
                  // 清除定时器
                  this.clearApplyHttpsTimer();
                  // 提示错误信息
                  this.$Message.error(response.info);
              }
          })
      }).catch(error => {
          console.error(error, 'error')
      })
    },
    verifyHttpsCertDns() {
      this.$http('POST', '/agentnew/ajax_verify_https_cert_dns', {
        domain: this.applyHttpsDomain.domain
      }, {
        headers: {
            'Auth': this.token
        }
      }).then(response => {
        this.$nextTick(() => {
          if (response.status) {
            // 显示等待加载
            this.applyHttpsDomain.isShowWaitLoading = true;
            this.applyHttpsDomain.waitLoadingText = '验证中，请稍等';

            // 关闭弹框
            this.applyHttpsDomain.isShowDialog = false;
            
            // 开始轮询获取DNS TXT
            this.startTimer(response.data.keys);
          } else {
            // 关闭等待加载
            this.applyHttpsDomain.isShowWaitLoading = false;
            this.$Message.error(response.info);
            this.clearApplyHttpsTimer();
          }
        })
      }).catch(error => {
          console.error(error, 'error')
      })
    },
    getVerifyHttpsCertDnsResult(keys) {
      this.$http('POST', '/agentnew/ajax_get_verify_https_cert_dns_result', {
        keys: keys
      }, {
        headers: {
            'Auth': this.token
        }
      }).then(response => {
        this.$nextTick(() => {
          if (response.status) {
            if (response.data.wait == 1) {
              return;
            }
            // 关闭等待加载
            this.applyHttpsDomain.isShowWaitLoading = false;
            // 清除定时器
            this.clearApplyHttpsTimer();

            this.$Message.error(response.info);
          } else {
            this.applyHttpsDomain.isShowWaitLoading = false;
            this.$Message.error(response.info);
            this.clearApplyHttpsTimer();
          }
        })
      }).catch(error => {
          console.error(error, 'error')
      })
    },
    // 2. 开始轮询
    startTimer(keys) {
      console.log(this.applyHttpsDomain, 'this.applyHttpsDomain')
      console.log(keys, 'keys')
      // 先清除已有定时器（避免重复）
      this.clearApplyHttpsTimer();

      if (this.applyHttpsDomain.confirmType == 1) {
        // 立即执行第一次请求
        this.getHttpsDnsTxt(keys);
        
        // 设置定时器
        this.applyHttpsDomain.getDnsTxtTimer = setInterval(() => {
          this.getHttpsDnsTxt(keys);
        }, this.applyHttpsDomain.timerTime);

      } else if (this.applyHttpsDomain.confirmType == 2) { 
        // 立即执行第一次请求
        this.getVerifyHttpsCertDnsResult(keys);
        
        // 设置定时器
        this.applyHttpsDomain.getVerifyDnsResultTimer = setInterval(() => {
          this.getVerifyHttpsCertDnsResult(keys);
        }, this.applyHttpsDomain.timerTime);
      }
    },
    // 5. 清除轮询
    clearApplyHttpsTimer() {
      if (this.applyHttpsDomain.getDnsTxtTimer) {
        clearInterval(this.applyHttpsDomain.getDnsTxtTimer);
        this.applyHttpsDomain.getDnsTxtTimer = null;
      }
      if (this.applyHttpsDomain.getVerifyDnsResultTimer) {
        clearInterval(this.applyHttpsDomain.getVerifyDnsResultTimer);
        this.applyHttpsDomain.getVerifyDnsResultTimer = null;
      }
    },
    
    // 弹框相关方法---start
    showGetHttpsCert(row) {
      console.log(row, 'row');
      this.applyHttpsDomain.domain = row.domain;
      this.applyHttpsDomain.isShowDialog = true;
    },
    // 确认按钮事件
    handleConfirm() {
      console.log(this.applyHttpsDomain, 'applyHttpsDomain')
      if (this.applyHttpsDomain.confirmType == 1) {
        this.applyHttpsCert();
      } else if (this.applyHttpsDomain.confirmType == 2) {
        this.verifyHttpsCertDns();
      }
    },
    // 取消按钮事件
    handleCancel() {
      this.applyHttpsDomain.isShowDialog = false;
    },
    // 关闭弹框事件
    handleClose() {
      this.applyHttpsDomain.isShowDialog = false;
    },
    dialogVisibleChange(data) {
      console.log(data, 'data098908090');
    },
    // 弹框相关方法---end
    handleClick(tab, event) {
      console.log(tab, event);
    },
    showAddDomainDialog() {
      this.isShowAddDomainDialog = true;
      this.authToken = this.token;
    },
    handleEvent(data) {
        console.log(data, 'handleEvent');
        this.isShowAddDomainDialog = data
    },

  },
  // 6. 组件销毁前清除定时器
  beforeUnmount() {
    this.clearApplyHttpsTimer();
  }

};
</script>
<style lang="scss" scoped>
.page-container {
    padding: 32px 32px;
}
.tip-title { 
  /* body/body 2_bold */
  font-family: Microsoft YaHei UI;
  font-size: 14px;
  font-weight: bold;
  line-height: normal;
  letter-spacing: 0.08em;
  /* text/text_1 */
  color: #1E2226;
}
.mr-10 {
  margin-right: 10px;
}

.card {
  display: flex;
  flex-direction: column;
  padding: 20px 14px;
  gap: 12px;
  border-radius: 4px;
  background: #F2F7FF;
  border: 1px solid #BFDAFF;
  margin-bottom: 12px;
}

.card-content {
    display: flex;
}

.number-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-width: 13px;
    height: 18px;
}

.descriptions {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.desc-item {
    display: flex;
    align-items: flex-start;
}

.desc-text {
  font-family: Microsoft YaHei UI;
  font-size: 14px;
  font-weight: normal;
  line-height: normal;
  letter-spacing: 0.08em;
  /* text/text_4 */
  color: #8A9099;
}

.expiretime {
  font-family: Microsoft YaHei UI;
  font-size: 12px;
  font-weight: normal;
  line-height: 13px;
  letter-spacing: 0.08em;
}

.tip-message {
    border-radius: 4px;
    /* middle/middle_blue_1 */
    background: #F2F7FF;
    /* middle/middle_blue_3 */
    border: 1px solid #BFDAFF;
    padding: 8px 13px;
    margin-bottom: 32px;
}
.tip-message p {
  line-height: 25px;
}

.red {
  color:#FF4D4F !important;
}

.gray {
  color:#8A9099 !important;
}

.ml-5 {
  margin-left: 5px;
}
.ml-8 {
  margin-left: 8px;
}
.mt-32 {
  margin-top: 32px;
}

a {
  text-decoration: none;
  color: #006AFF;
}


.el-table {
  min-height: auto !important;
}

::v-deep .custom-popover {
    position: fixed !important;
    // max-height: 290px;
    // overflow-y: auto;
    margin-top: 0 !important;
    margin-left: 0 !important;
    transform: none !important;
}

.register-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;

  .custom-icon {
    width: 24px;
    height: 24px;
  }

  .register-top {
    display: flex;
    justify-content: space-between;
    // height: 72px;
    align-items: center;
    padding: 20px 40px 20px 110px;
    background: linear-gradient(270deg, #F6EEF7 3%, #EDE9FB 97%);
    color: #23242B;
    letter-spacing: 0.08em;
    line-height: 32px;

    .register-top-left {
      display: flex;
      align-items: center;

      .register-top-left img {
        margin-right: 12px;
      }
    }
  }

  .step3-wrap {
    flex: 1;

    .step3-top {
      display: flex;
      justify-content: space-between;
      padding-bottom: 0;
      align-items: center;
      margin-bottom: 32px;
      h3{
        margin: 0;
        /* body/body 2_bold */
        font-family: Microsoft YaHei UI;
        font-size: 14px;
        font-weight: bold;
        line-height: normal;
        letter-spacing: 0.08em;
        /* text/text_1 */
        color: #1E2226;
      }

    }
  }

}


.table-wrap {
  span {
    color: #1E2226;
  }

  .edit_icon {
    display: none;
    transition: all .3s;
    margin-left: 8px;
  }

  .el-table__row:hover {
    .edit_icon {
      display: block;
      transition: all .3s;
    }
  }
}

.green,
.blue {
  width: 80px;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  color: #0DAF49 !important;
  letter-spacing: 0.08em;
  /* 基本 */
  width: 80px;
  border-radius: 4px;
  background: rgba(239, 255, 224, 0.5);
  box-sizing: border-box;
  border: 1px solid rgba(0, 194, 97, 0.6);
  margin-right: 8px;
}

.blue {
  background: #F2F7FF;
  border: 1px solid #BFDAFF;
  color: #006AFF !important;
}




.step-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 0 0 0;

  .step-item {
    align-items: center;
    display: flex;

    span {
      color: #1E2226;
      letter-spacing: 0.08em;
    }

    .custom-icon {
      margin-right: 12px;
    }
  }

  .checked span {
    font-size: 16px;
    font-weight: bold;
    color: #006AFF !important;
    transition: all .3s;

  }

  .success span {
    font-size: 16px;
    font-weight: normal;
    color: #006AFF !important;
    transition: all .3s;
  }

  .step-line {
    flex: 1;
    margin: 0 32px;
    border-bottom: 1px solid #DFE2E6;
  }

  .step_active-line {
    transition: all .3s;
    border-bottom: 1px solid #006AFF;
  }
}

.step-desc {
  padding-top: 6px;
  display: flex;
  justify-content: space-between;
  padding-bottom: 24px;
  color: #8A9099;

  span {
    padding-left: 36px;
  }
}


</style>
