<template>
  <a-drawer
    :title="modalTitle"
    :maskClosable="true"
    width="850"
    placement="right"
    :closable="true"
    @close="handleCancel"
    v-model:open="modalVisible"
    :ok-button-props="okBtnStatus"
    destroy-on-close
    style="overflow: auto; padding-bottom: 53px"
  >
    <template v-if="gtmAddedStatus">
      <a-spin :spinning="spinning" :tip="tipTitle">
        <a-form ref="ruleForm" :model="googleGtmForm" :label-col="labelCol" :wrapper-col="wrapperCol">
          <div>
            <p style="text-align: center; font-weight: bold">拷贝跟踪代码并添加至网站；请勿重复添加跟踪代码。</p>
          </div>
          <a-form-item label="GTM Head" name="head">
            <a-textarea
              v-model:value="googleGtmForm.head"
              id="googleGtmHead"
              type="textarea"
              :autosize="{ minRows: 10, maxRows: 15 }"
              :readOnly="true"
            />
          </a-form-item>
          <a-form-item label="GTM Body" name="body">
            <a-textarea
              v-model:value="googleGtmForm.body"
              id="googleGtmBody"
              type="textarea"
              :autosize="{ minRows: 10, maxRows: 15 }"
              :readOnly="true"
            />
          </a-form-item>
        </a-form>
      </a-spin>
    </template>

    <template v-if="gtmAddingStatus">
      <a-spin :spinning="spinning" :tip="tipTitle">
        <a-form ref="ruleForm" :model="googleGtmForm" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-item v-if="gtmAddingStatus" label="GA账号" name="gaAccount">
            <a-select
              allow-clear
              placeholder="请选择GA账号"
              style="text-align: left"
              v-model:value="gaAccountID"
              :options="gaAccountsList"
              @change="changeAccount"
              :field-names="{ label: 'displayName', value: 'id' }"
            />
          </a-form-item>
        </a-form>
      </a-spin>
    </template>

    <div
      v-if="!gtmAddedStatus"
      :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="addGTMBySys" :loading="loadingDrawerBtn"> 生成 GA 跟踪代码 </a-button>
    </div>
  </a-drawer>
</template>

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

  const { createMessage } = useMessage();

  const modalTitle = ref('跟踪代码');
  const loadingDrawerBtn = ref(false);
  const labelCol = reactive({ span: 3 });
  const wrapperCol = reactive({ span: 21 });
  const spinning = ref(false);
  const tipTitle = ref('');
  const gtmAddingStatus = ref(false);
  let siteInfo = reactive({ id: '', code: '', domain: '', name: '' });
  const gtmAddedStatus = ref(false);

  const okBtnStatus = ref(true);
  const modalVisible = ref(false);

  let googleGtmForm = reactive({ head: '', body: '' });
  let gaAccountsList = reactive([{ displayName: '', id: '' }]);
  const gaAccountID = ref(null);

  function init(record) {
    modalVisible.value = true;
    modalTitle.value = record.name;
    siteInfo = record;
    getGTMSnippets(record);
  }

  // 获取GTM代码
  function getGTMSnippets(record) {
    let gtmGTMUrl = `/gtm/get?siteCode=${record.code}`;
    spinning.value = true;
    getAction(gtmGTMUrl, {})
      .then((res) => {
        spinning.value = false;

        if (res.code === 200 && res.result.gtmHead !== '' && res.result.gtmBody !== '') {
          googleGtmForm.head = res.result.gtmHead;
          googleGtmForm.body = res.result.gtmBody;
          gtmAddedStatus.value = true;
        } else {
          getGAAccounts();
          gtmAddingStatus.value = true;
        }
      })
      .catch(function (err) {
        cleanAllFormData();
        createMessage.error('网络超时，请重试!' + err.message());
        spinning.value = false;
      });
  }
  // 获取GA账号列表
  function getGAAccounts() {
    let gtmListUrl = `/gtm/listGAAccounts`;
    spinning.value = true;
    getAction(gtmListUrl, {})
      .then(function (res) {
        if (res.code === 200) {
          gaAccountsList = res.result;
        }

        modalVisible.value = true;
        modalTitle.value += ' 系统生成跟踪代码';
        okBtnStatus.value = false;
        spinning.value = false;
      })
      .catch(function (err) {
        cleanAllFormData();
        createMessage.error('网络超时，请重试!' + err.message());
        spinning.value = false;
      });
  }

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

  function handleCancel() {
    cleanAllFormData();
  }

  function cleanAllFormData() {
    okBtnStatus.value = true;
    spinning.value = false;
    tipTitle.value = '';
    modalVisible.value = false;
    modalTitle.value = '';
    googleGtmForm = {
      head: '',
      body: '',
    };

    gtmAddedStatus.value = false;
    gtmAddingStatus.value = false;
  }

  function addGTMBySys() {
    if (gaAccountID.value == '' || gaAccountID.value == null) {
      createMessage.info('请先选择GA账号！');
      return;
    }

    let params = {
      siteCode: siteInfo.code,
      gaAccountId: gaAccountID.value,
    };

    loadingDrawerBtn.value = true;

    let gtmAddUrl = `/gtm/add`;
    spinning.value = true;
    postActionForm(gtmAddUrl, params, 300000)
      .then(function (res) {
        if (res.code == 200) {
          createMessage.success('跟踪代码已生成！');

          googleGtmForm.head = res.result.gtmHead;
          googleGtmForm.body = res.result.gtmBody;
        } else {
          createMessage.error('网站跟踪代码生成失败！');
        }
        loadingDrawerBtn.value = false;
        gtmAddedStatus.value = true;
        gtmAddingStatus.value = false;
        spinning.value = false;
      })
      .catch(function (e) {
        console.log('生成GTM代码报错：', e.message(), e);
        createMessage.error('网络超时，请重试');
        spinning.value = false;
      });
  }

  defineExpose({ init });
</script>
