<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 placeholder="请选择发布状态" v-model:value="queryParam.status" dict="site_status" />
            </a-form-item>
          </a-col>

          <template v-if="toggleSearchStatus">
            <a-col :xxl="6" :xl="7">
              <a-form-item label="渠道商">
                <a-select placeholder="请选择渠道商" v-model:value="queryParam.channelProviderId" showSearch allowClear :filterOption="filterOption">
                  <a-select-option v-for="data in channelProviderList" :key="data.username" :value="data.workNo">
                    {{ data.username }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <!--            <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 :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" />
    <!--SEO流程-->
    <seo-process ref="seoProcessRef" :visible="seoProcessVisible" :title="processTitle" @close="closeProcess" @reload="reload" />
  </div>
</template>

<script lang="ts" name="adweb-adwebSite" setup>
  import { computed, onBeforeMount, reactive, ref } from 'vue';
  import { getAction } from '/@/api/manage/manage';
  import { BasicTable, TableAction } from '/src/components/Table';
  import { useListPage } from '/src/hooks/system/useListPage';
  import { columns, superQuerySchema } from './AdwebSite.data';
  import { batchDelete, deleteOne, getExportUrl, getImportUrl, list, gtmListUrl, saveOrUpdate } from './AdwebSite.api';
  import AdwebSiteModal from './components/AdwebSiteModal.vue';
  import { useUserStore } from '/src/store/modules/user';
  import SeoProcess from '@/views/adweb/site/components/SeoProcess.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';

  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 seoProcessRef = ref();
  const gtmRef = ref();
  const siteSetEnquiryRef = ref();

  const isAdmin = computed(() => userStore.getRoleList.includes(RoleEnum.ADMIN));
  const { createMessage } = useMessage();

  let channelProviderList = reactive([{ username: '', workNo: '' }]);
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'adweb站点配置表单',
      api: list,
      columns,
      canResize: false,
      useSearchForm: true,
      showTableSetting: true,
      actionColumn: {
        width: 120,
        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);
  //渠道商搜索
  const filterOption = (input: string, option: any) => {
    console.log(option, 'optionoption');
    return option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  onBeforeMount(() => {
    getChannelProvider();
  });

  function getChannelProvider() {
    getAction('/adweb/system/getChannelProvider', null).then((res) => {
      channelProviderList = res.result;
    });
  }
  /**
   * 高级查询事件
   */
  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) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }

  /**
   * 详情
   */
  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(() => {});
  }

  /**
   * 批量删除事件
   */
  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),
      },
      {
        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: '跟踪代码',
        onClick: addGtm.bind(null, record),
      });
    }

    if (isAdmin.value) {
      dropDown.push({
        label: '资源删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
      });
    }
    return dropDown;
  }

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

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

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

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

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

  function closeProcess() {
    seoProcessVisible.value = false;
  }
</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>
