<template>
  <div class="p-2">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :xxl="6" :xl="7">
            <a-form-item name="name" label="站点名称">
              <j-input placeholder="请输入站点名称" v-model:value="queryParam.name" allow-clear />
            </a-form-item>
          </a-col>

          <a-col :xxl="6" :xl="7">
            <a-form-item name="domain" label="站点域名">
              <j-input placeholder="请输入站点域名" v-model:value="queryParam.domain" allow-clear />
            </a-form-item>
          </a-col>

          <a-col :xxl="6" :xl="8">
            <a-form-item label="发布状态">
              <j-search-select allow-clear placeholder="请选择发布状态" v-model:value="queryParam.status" dict="site_status" />
            </a-form-item>
          </a-col>

          <a-col v-if="isAdmin" :xxl="6" :xl="7">
            <a-form-item label="租户">
              <j-search-select
                allow-clear
                placeholder="请选择租户"
                v-model:value="queryParam.channelProviderId"
                dict="sys_tenant,name,id,del_flag=0 AND status=1"
              />
            </a-form-item>
          </a-col>

          <template v-if="toggleSearchStatus">
            <!--            <a-col :xxl="12" :xl="10">-->
            <!--              <a-form-item label="创建时间">-->
            <!--                <j-range-date placeholder="请选择开始日期" class="query-group-cust" v-model:value="queryParam.ctime" />-->
            <!--              </a-form-item>-->
            <!--            </a-col>-->

            <!--            <a-col :xl="10" :lg="11" :md="12" :sm="24">-->
            <!--              <a-form-item label="到期时间">-->
            <!--                <j-range-date placeholder="请选择开始日期" class="query-group-cust" v-model:value="queryParam.etime" />-->
            <!--              </a-form-item>-->
            <!--            </a-col>-->
          </template>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
                </a>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <!--        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>-->
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <!--        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>-->
        <!--        <a-dropdown v-if="selectedRowKeys.length > 0">-->
        <!--          <template #overlay>-->
        <!--            <a-menu>-->
        <!--              <a-menu-item key="1" @click="batchHandleDelete">-->
        <!--                <Icon icon="ant-design:delete-outlined" />-->
        <!--                删除-->
        <!--              </a-menu-item>-->
        <!--            </a-menu>-->
        <!--          </template>-->
        <!--          <a-button-->
        <!--            >批量操作-->
        <!--            <Icon icon="mdi:chevron-down" />-->
        <!--          </a-button>-->
        <!--        </a-dropdown>-->
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction
          style="padding: 5px 8px; display: flex; justify-content: space-around"
          :actions="getTableAction(record)"
          :dropDownActions="getDropDownAction(record)"
        />
      </template>
      <template #bodyCell="{ column, record, index, text }">
        <div v-if="column.dataIndex == 'name'">
          <a :href="record.domain" target="_blank">{{ text }}</a>
        </div>
        <div v-if="column.dataIndex == 'domain'">
          <a :href="record.domain" target="_blank">{{ text }}</a>
        </div>

        <div v-if="column.dataIndex == 'subscribePlan'">
          <template v-if="text === null || text === ''"> 无 </template>
          <template v-else>
            <a-popover>
              <template #content>
                <a-descriptions bordered :column="{ xxl: 1, xl: 1, lg: 1, md: 1, sm: 1, xs: 1 }" title="SEO套餐详情" size="default">
                  <a-descriptions-item label="套餐名">
                    {{ text.planName }}
                  </a-descriptions-item>
                  <a-descriptions-item label="关键词"> {{ text.keywordCount }}个 </a-descriptions-item>
                  <a-descriptions-item label="服务时间">
                    <template v-if="text.serviceTime != 0"> {{ text.serviceTime }}个月 </template>
                    <template v-else> 长期 </template>
                  </a-descriptions-item>
                  <a-descriptions-item label="价格"> {{ text.price }}元 </a-descriptions-item>
                </a-descriptions>
              </template>
              <a-tag color="blue">
                {{ text.planName }}
              </a-tag>
            </a-popover>
          </template>
        </div>

        <div v-if="column.dataIndex == 'status_dictText'">
          <template v-if="record.status == 1">
            <a-tag color="blue">
              {{ text }}
            </a-tag>
          </template>
          <template v-else-if="record.status == 2">
            <a-tag color="green">
              {{ text }}
            </a-tag>
          </template>
          <template v-else>
            <a-tag color="red">
              {{ text }}
            </a-tag>
          </template>
        </div>

        <div v-if="column.dataIndex == 'siteCurrentStep'">
          <span v-if="text === null || text === undefined || text === ''"> - </span>
          <template v-else>
            <a @click="handleProcess(record, 'site')"> <span class="circle" style="background-color: #7194f8"></span>{{ text }} </a>
          </template>
        </div>

        <div v-if="column.dataIndex == 'completeProcess'">
          <a-progress :stroke-color="{ '0%': '#108ee9', '100%': '#87d068' }" :percent="record.completeProcess" />
        </div>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <AdwebSiteModal ref="registerModal" @success="handleSuccess" />

    <site-set-enquiry ref="siteSetEnquiryRef" @success="reload" />
    <!-- 自动化嵌入GTM 代码     -->
    <gtm-add ref="gtmRef" />
    <!--建站流程-->
    <site-process ref="siteProcessRef" :visible="seoProcessVisible" :title="processTitle" @close="closeProcess" @reload="reload" />
    <google-ads-modal ref="googleAdsModalRef" @success="reload" />
    <facebook-modal ref="faceBookModalRef" @success="reload" />
    <Sohoeb2bOrder ref="sohoeb2bOrderRef" @reload="reload" />
    <SiteRelease ref="siteReleaseRef" @reload="reload" />
  </div>
</template>

<script lang="ts" name="adweb-adwebSite" setup>
  import { computed, nextTick, onBeforeMount, reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, superQuerySchema } from './AdwebSite.data';
  import { batchDelete, deleteOne, getExportUrl, getImportUrl, list, saveOrUpdate } from './AdwebSite.api';
  import AdwebSiteModal from './components/AdwebSiteModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import SiteProcess from '@/views/adweb/site/components/SiteProcess.vue';
  import JInput from '@/components/Form/src/jeecg/components/JInput.vue';
  import JSearchSelect from '@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import GtmAdd from '@/views/adweb/site/components/GtmAdd.vue';
  import { RoleEnum } from '@/enums/roleEnum';
  import { useMessage } from '@/hooks/web/useMessage';
  import SiteSetEnquiry from '@/views/adweb/site/components/SiteSetEnquiry.vue';
  import GoogleAdsModal from './components/GoogleAdsModal.vue';
  import FacebookModal from './components/FacebookModal.vue';
  import { getAuthCache } from '@/utils/auth';
  import { TENANT_ID } from '@/enums/cacheEnum';
  import { getTenantById } from '@/views/system/tenant/tenant.api';
  import Sohoeb2bOrder from '@/views/adweb/site/components/Sohoeb2bOrder.vue';
  import SiteRelease from '@/views/adweb/site/components/SiteRelease.vue';

  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const userStore = useUserStore();
  const processTitle = ref('');
  const seoProcessVisible = ref(false);
  const siteProcessRef = ref();
  const sohoeb2bOrderRef = ref();
  const siteReleaseRef = ref();
  const gtmRef = ref();
  const siteSetEnquiryRef = ref();
  const googleAdsModalRef = ref();
  const faceBookModalRef = ref();

  // admin 判断和后端保持一致
  // src/main/java/org/jeecg/modules/adweb/system/service/impl/SysAdwebApiImpl.java L60
  // TODO 将此判断加入store,方便所有组件全局调用

  console.log(userStore.getRoleList, '当前用户所属角色');
  const isAdmin = computed(() => {
    return (
      userStore.getRoleList.includes(RoleEnum.ADMIN) ||
      userStore.getRoleList.includes(RoleEnum.ADWEB_ADMIN) ||
      userStore.getRoleList.includes(RoleEnum.SEO_ADMIN) ||
      userStore.getRoleList.includes(RoleEnum.ADWEB_SITE_MANAGER) ||
      userStore.getRoleList.includes(RoleEnum.ADWEB_SEO_MANAGER)
    );
  });

  // 租户管理员角色
  const isTenantAdmin = computed(() => {
    return userStore.getRoleList.includes(RoleEnum.ADWEB_CHANNEL_ADMIN);
  });

  // 是否是苏豪纺织的租户
  const isSohoeb2b = ref(false);

  const { createMessage } = useMessage();

  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'adweb站点配置表单',
      api: list,
      columns,
      defSort: {
        column: 'utime',
        order: 'desc',
      },
      canResize: false,
      useSearchForm: true,
      showTableSetting: true,
      actionColumn: {
        width: 180,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'adweb站点配置表单',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] =
    tableContext;
  const labelCol = reactive({
    xs: 24,
    sm: 4,
    xl: 6,
    xxl: 4,
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

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

  onBeforeMount(async () => {
    isSohoeb2bTenant();
  });

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    searchQuery();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    if (isAdmin.value) {
      registerModal.value.disableSubmit = false;
      registerModal.value.edit(record);
    } else {
      return window.open(record.domain + '/adweb-admin/');
    }
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  async function siteDeleteStatus(record) {
    record.status = 0;

    await saveOrUpdate(record, true)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
        } else {
          createMessage.warning(res.message);
        }

        reload();
      })
      .finally(() => {});
  }

  function isSohoeb2bTenant() {
    getTenantById({ id: getAuthCache(TENANT_ID) }).then((res) => {
      isSohoeb2b.value = res.name.includes('苏豪纺织集团');
    });
  }

  /**
   * 批量删除事件
   */
  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 getDropDownAction(record) {
    let dropDown = [
      // {
      //   label: '详情',
      //   onClick: handleDetail.bind(null, record),
      // },
    ];

    // 站点不是删除状态
    if (record.status === 2) {
      dropDown.push({
        label: '发布上线',
        onClick: wpSiteRelease.bind(null, record),
      });
    }

    // 针对苏豪纺织租户管理员，或者是管理员
    if ((isTenantAdmin.value && isSohoeb2b.value) || isAdmin.value) {
      dropDown.push({
        label: '订单设置',
        onClick: setSohoeb2bOrder.bind(null, record),
      });
    }

    dropDown.push({
      label: '询盘设置',
      onClick: setEnquiry.bind(null, record),
    });

    // 站点不是删除状态
    if (record.status != 0) {
      dropDown.push({
        label: '站点删除',
        onClick: siteDeleteStatus.bind(null, record),
      });
    }

    // 站点已发布，并且是正式域名时可以添加GTM 代码
    if (record.isDomain === 1 && record.status === 1) {
      dropDown.push(
        {
          label: 'GTM代码',
          onClick: addGtm.bind(null, record),
        },
        {
          label: 'Google Ads',
          onClick: bindGoogleAds.bind(null, record),
        },
        {
          label: 'FaceBook绑定',
          onClick: addFaceBook.bind(null, record),
        }
      );
    }

    // 当前是管理员，并且站点是被删除状态
    if (isAdmin.value && record.status === 0) {
      dropDown.push({
        label: '资源删除',
        popConfirm: {
          title: '该站点将从系统中删除，站点资源将会保留15天，是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
      });
    }

    return dropDown;
  }

  // 添加gtm
  function addGtm(r) {
    gtmRef.value.init(r);
  }

  // 询盘设置
  function setEnquiry(record) {
    siteSetEnquiryRef.value.init(record);
  }

  function setSohoeb2bOrder(record) {
    sohoeb2bOrderRef.value.init(record);
  }

  function wpSiteRelease(record) {
    siteReleaseRef.value.init(record);
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();

    if (queryParam.status) {
      delete queryParam.status;
    }
    if (queryParam.channelProviderId) {
      delete queryParam.channelProviderId;
    }

    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  function handleProcess(record, type) {
    seoProcessVisible.value = true;
    processTitle.value = record.name;
    siteProcessRef.value.init(record, type);
    siteProcessRef.value.isCustomer = true;
  }

  function closeProcess() {
    seoProcessVisible.value = false;
  }

  function bindGoogleAds(record) {
    nextTick(() => {
      googleAdsModalRef.value.init({ record });
    });
  }

  function addFaceBook(record) {
    faceBookModalRef.value.init({ record });
  }
</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust {
      min-width: 100px !important;
    }
    .query-group-split-cust {
      width: 30px;
      display: inline-block;
      text-align: center;
    }
    .ant-form-item:not(.ant-form-item-with-help) {
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),
    :deep(.ant-input-number) {
      width: 100%;
    }
  }
</style>
