<template>
  <div>
    <a-row class="r1" style="margin: 20px">
      <a-col :span="24">
        <span class="t1">{{ siteinfo.length > 1 ? '请选择站点：' : '套餐：' }}</span>
        <select-site v-if="siteinfo.length > 1" @com-methods="changeSite" selectWidth="300px" />
        <span style="margin-left: 16px" class="t1"
          >{{ selectSiteInfo.planName && selectSiteInfo.planType !== 'STATIONCONSTRUCTION' ? selectSiteInfo.planName : '暂无SEO推广套餐~' }}
          <a-popover placement="bottom" v-show="selectSiteInfo.planName && selectSiteInfo.planType !== 'STATIONCONSTRUCTION'">
            <template #content>
              <span> 指定词数：{{ last(comprehenInfo.specifyKeywordNum) }}&nbsp; </span>
              <span> 关键词数：{{ last(comprehenInfo.longTailKeywordNum) }}&nbsp; </span>
              <span> 外链数：{{ last(comprehenInfo.outerLinkNum) }}&nbsp; </span>
              <span> 文章数：{{ last(comprehenInfo.articleNum) }} </span>
            </template>
            <img
              src="https://cutomer-static-bucket.s3.cn-northwest-1.amazonaws.com.cn/public/material/220803883dfy/document/changjianwenti_1676606434975.png"
              alt="issue"
              width="25px"
              height="25px"
            />
          </a-popover>
        </span>
      </a-col>
    </a-row>
    <a-row class="r2" type="flex" justify="center" align="middle">
      <a-col :span="6">
        <p class="t1"><img src="../../../assets/seo/zhidingci.svg" />指定词</p>
        <p class="t2" v-if="comprehenInfo.specifyKeywordNum == null"> - </p>
        <p class="t2" v-else>
          <span>{{ comprehenInfo.specifyKeywordNum }}</span>
        </p>
      </a-col>
      <a-col :span="6">
        <p class="t1"><img src="../../../assets/seo/changweici.svg" />关键词</p>
        <p class="t2" v-if="comprehenInfo.longTailKeywordNum == null"> - </p>
        <p class="t2" v-else>
          <span>{{ comprehenInfo.longTailKeywordNum }}</span>
        </p>
      </a-col>
      <a-col :span="6">
        <p class="t1"><img src="../../../assets/seo/lianjieshu.svg" />外链数</p>
        <p class="t2" v-if="comprehenInfo.outerLinkNum == null"> - </p>
        <p class="t2">
          <span>{{ comprehenInfo.outerLinkNum }}</span>
        </p>
      </a-col>
      <a-col :span="6">
        <p class="t1"><img src="../../../assets/seo/wenzhangshu.svg" />文章数</p>
        <p class="t2" v-if="comprehenInfo.articleNum == null"> - </p>
        <p class="t2">
          <span>{{ comprehenInfo.articleNum }}</span>
        </p>
      </a-col>
    </a-row>
    <a-row class="r3" type="flex" :gutter="16">
      <a-col :span="12">
        <div class="wrap">
          <p class="t1">指定词排名</p>
          <div class="content">
            <div class="d1"><img src="../../../assets/seo/NO1.svg" />1-10位</div>
            <div class="d2"
              ><a @click="getTableInfoRank(3, 1)">{{ filtr_null(rankInfo.appointKeyword.firstNum) }}</a
              >个
            </div>
          </div>
          <div class="content">
            <div class="d1"><img src="../../../assets/seo/NO2.svg" />11-30位</div>
            <div class="d2"
              ><a @click="getTableInfoRank(7, 1)">{{ filtr_null(rankInfo.appointKeyword.secondNum) }}</a
              >个
            </div>
          </div>
          <div class="content">
            <div class="d1"><img src="../../../assets/seo/NO3.svg" />31-100位</div>
            <div class="d2"
              ><a @click="getTableInfoRank(8, 1)">{{ filtr_null(rankInfo.appointKeyword.thirdType) }}</a
              >个
            </div>
          </div>
        </div>
      </a-col>
      <a-col :span="12">
        <div class="wrap">
          <p class="t1">关键词排名</p>
          <div class="content">
            <div class="d1"><img src="../../../assets/seo/NO1.svg" />1-10位</div>
            <div class="d2">
              <a @click="longGetTableInfoRank(3)">{{ filtr_null(rankInfo.longTailKeyword.firstNum) }}</a
              >个
            </div>
          </div>
          <div class="content">
            <div class="d1"><img src="../../../assets/seo/NO2.svg" />11-30位</div>
            <div class="d2"
              ><a @click="longGetTableInfoRank(7)">{{ filtr_null(rankInfo.longTailKeyword.secondNum) }}</a
              >个
            </div>
          </div>
          <div class="content">
            <div class="d1"><img src="../../../assets/seo/NO3.svg" />31-100位</div>
            <div class="d2"
              ><a @click="longGetTableInfoRank(8)">{{ filtr_null(rankInfo.longTailKeyword.thirdType) }}</a
              >个
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template #bodyCell="{ column, record, index, text }"> </template>
    </BasicTable>
    <!-- 表单区域 -->
    <SeoKpiStatisticsModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="serp-seoKpiStatistics" setup>
  import { ref, reactive, computed, unref, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/src/components/Table';
  import { useModal } from '/src/components/Modal';
  import { useListPage } from '/src/hooks/system/useListPage';
  import { columns, searchFormSchema, superQuerySchema } from './SeoKeywordsRank.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, getAllSites } from './SeoKeywordsRank.api';
  import { downloadFile } from '/src/utils/common/renderUtils';
  import { useUserStore } from '/src/store/modules/user';
  import selectSite from '@/components/Adweb/selectSite.vue';
  import { getAction } from '@/api/manage/manage';
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'seo_keywords_rank',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'seo_keywords_rank',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  const siteinfo = ref([]);
  const selectSiteInfo = ref({ planId: '', planName: '', planType: '', subscriptionId: '' });
  const siteCode = ref('');
  let comprehenInfo = ref({ specifyKeywordNum: 0, longTailKeywordNum: 0, outerLinkNum: 0, articleNum: 0 });
  const keywords = ref('');
  const rankInfo = ref({
    appointKeyword: { firstNum: 0, secondNum: 0, thirdType: '' },
    longTailKeyword: { firstNum: 0, secondNum: 0, thirdType: '' },
  });
  const dataSource = ref([]);
  const ipagination = ref({ current: 1, total: 0 });
  const longDataSource = ref([]);
  const longIpagination = ref({ current: 1, total: 0 });
  const show = ref();
  const keywordType = ref();
  const longShow = ref();
  // const loading = ref(false);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '去查询',
        onClick: handleEdit.bind(null, record),
      },
    ];
  }

  //切换站点
  function changeSite(value, e) {
    getSiteInfo();
    selectSiteInfo.value = e.info;
    siteCode.value = value;
    queryParam.reachStandard = undefined;
    keywords.value = '';
    localStorage.setItem('siteCode', value);
    resetAllInfo();
    getAllInfo();
  }
  //先执行获取site信息，只有在获取到siteCode之后，才能执行以下方法
  function getSiteInfo() {
    getAllSites().then((res) => {
      siteinfo.value = res;
      if (res.length > 0) {
        let isInSite = false;
        for (let i in res) {
          if (localStorage.getItem('siteCode') !== null && res[i].code === localStorage.getItem('siteCode')) {
            isInSite = true;
            selectSiteInfo.value = res[i];
          }
        }
        if (localStorage.getItem('siteCode') !== null && isInSite) {
          siteCode.value = localStorage.getItem('siteCode');
        } else {
          siteCode.value = res[0].code;
          selectSiteInfo.value = res[0];
          localStorage.setItem('siteCode', res[0].code);
        }
      }
      resetAllInfo();
      getAllInfo();
    });
  }

  function resetAllInfo() {
    comprehenInfo.value = { specifyKeywordNum: 0, longTailKeywordNum: 0, outerLinkNum: 0, articleNum: 0 };
    rankInfo.value = { appointKeyword: {}, longTailKeyword: {} };
    dataSource.value = [];
    ipagination.value = { current: 1, total: 0 };
    longDataSource.value = [];
    longIpagination.value = { current: 1, total: 0 };
  }

  function getAllInfo() {
    let d = {
      siteCode: siteCode.value,
      subscriptionId: selectSiteInfo.value.subscriptionId ?? '',
    };
    getAction('/seo/seoKeywordsRank/comprehensiveInfo', d)
      .then((res) => {
        if (res.code == 200) {
          comprehenInfo.value = res.result;
        }
      })
      .finally(() => {
        getRankInfo();
        setTableQuery();
        // longSetTableQuery()
      });
  }
  function first(value) {
    if (value && value != null) {
      let a = value.split('/');
      return a[0];
    } else {
      return '- ';
    }
  }
  function last(value) {
    if (value && value != null) {
      let a = value.split('/');
      return a[1];
    } else {
      return ' -';
    }
  }
  function filtr_null(value) {
    if (value != null) {
      return value;
    } else {
      return '- ';
    }
  }
  //点击排名数量事件
  function getTableInfoRank(d, keywordType) {
    show.value = d;
    queryParam.reachStandard = undefined;
    if (keywordType) {
      keywordType.value = keywordType;
    }
    setTableQuery();
  }
  //由于页面的业务关联很多，故将所有的查询条件封装
  function setTableQuery() {
    queryParam.siteCode = siteCode.value;
    if (show.value == 3) {
      queryParam.rankStart = '1';
      queryParam.rankEnd = '10';
    } else if (show.value == 4) {
      queryParam.rankStart = '1';
      queryParam.rankEnd = '30';
    } else if (show.value == 5) {
      queryParam.rankStart = '1';
      queryParam.rankEnd = '50';
    } else if (show.value == 6) {
      queryParam.rankStart = '1';
      queryParam.rankEnd = '100';
    } else if (show.value == 7) {
      queryParam.rankStart = '11';
      queryParam.rankEnd = '30';
    } else if (show.value == 8) {
      queryParam.rankStart = '31';
      queryParam.rankEnd = '100';
    } else {
      queryParam.rankStart = undefined;
      queryParam.rankEnd = undefined;
    }
    queryParam.keywordType = keywordType.value;
    queryParam.keywords = keywords.value;
    // loadData(1)
  }
  // function loadData(arg) {
  //   let a = []
  //   if (arg === 1) {
  //     ipagination.value.current = 1
  //   }
  //   var params = getQueryParams()//查询条件
  //   params.subscriptionId = selectSiteInfo.value.subscriptionId;
  //   params.keywordType = 1;
  //   loading.value = true
  //   getAction(url.list, params).then((res) => {
  //     if (res.success) {
  //       let alldata  = res.result.records
  //       if(alldata.length > 0){
  //         for(let i in alldata){
  //           let rankInfo = alldata[i].rankInfo;
  //           a.push({
  //             id:alldata[i].id,
  //             keywords:alldata[i].keywords,
  //             keywordType:alldata[i].keywordType,
  //             keywordsLength:alldata[i].keywordsLength,
  //             rankInfo:rankInfo,
  //             ...rankInfo
  //           })
  //         }
  //         dataSource = a;
  //         getTableColums()
  //         ipagination.total = res.result.total
  //       }else{
  //         dataSource = a;
  //         ipagination.total = 0
  //       }
  //
  //     }
  //     if (res.code === 510) {
  //       $message.warning(res.message)
  //     }
  //     loading = false
  //   })
  // },
  //点击排名数量事件
  function longGetTableInfoRank(d) {
    longShow.value = d;
    // longQueryParam.reachStandard = undefined
    // longSetTableQuery()
  }
  //获取排行榜数据
  function getRankInfo() {
    let d = {
      siteCode: siteCode.value,
      subscriptionId: selectSiteInfo.value.subscriptionId ? selectSiteInfo.value.subscriptionId : '',
    };
    getAction('/seo/seoKeywordsRank/getRankInfo', d).then((res) => {
      console.log(res.code == 200);
      if (res.code == 200) {
        rankInfo.value.appointKeyword = res.result.appointKeyword;
        rankInfo.value.longTailKeyword = res.result.longTailKeyword;
        console.log(rankInfo.value.a);
      }
    });
  }
  //动态处理表格列
  function getTableColums() {
    that.columns = [
      {
        title: '序号',
        dataIndex: 'rowIndex',
        key: 'rowIndex',
        width: 40,
        align: 'center',
        fixed: 'left',
        scopedSlots: { customRender: 'dataNo' },
      },
      {
        title: '关键词',
        dataIndex: 'keywords',
        key: 'keywords',
        fixed: 'left',
        scopedSlots: { customRender: 'keywords' },
        width: 350,
      },
    ];
    let obj = that.dataSource[0].rankInfo;
    let dateInfo = Object.keys(obj);
    dateInfo.sort().reverse();
    for (let i in dateInfo) {
      that.columns.push({
        title: dateInfo[i],
        dataIndex: dateInfo[i],
        key: dateInfo[i],
        scopedSlots: { customRender: 'tag' },
        align: 'center',
      });
    }
    that.columns.push({
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      align: 'center',
      scopedSlots: { customRender: 'action' },
      fixed: 'right',
      width: 50,
    });
  }
  onMounted(() => {
    getSiteInfo();
  });
</script>

<style scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
  .r2 {
    background: #fff;
    padding: 30px;
    margin: 10px;

    .ant-col {
      text-align: center;
      color: #000;

      img {
        width: 13px;
        margin: -3px 5px 0 0;
      }

      .t1 {
        font-size: 14px;
      }

      .t2 {
        font-size: 27px;
        margin-bottom: 0;
        font-weight: 500;
      }
    }
  }
  .r3 {
    padding-left: 10px;
    padding-right: 10px;
    .wrap {
      padding: 20px;
      background: #fff;
      margin-bottom: 10px;

      .t1 {
        color: #000;
        font-size: 14px;
        font-weight: 500;
      }

      .content {
        display: block;
        overflow: hidden;
        line-height: 1;
        border-bottom: 1px solid #ddd;
        padding: 20px 0;

        &:last-child {
          border-bottom: none;
          padding-bottom: 0;
        }

        .d1 {
          float: left;
          width: 50%;
          line-height: 25px;
          color: #000;

          img {
            width: 15px;
            margin: -4px 5px 0 0;
          }
        }

        .d2 {
          float: right;
          width: 50%;
          text-align: right;

          &.d3 {
            span {
              color: #000;
            }
          }

          a {
            font-size: 25px;
            font-weight: 500;
          }
        }
      }
    }
  }
</style>
