<template>
    <div class="demo-wrap main-content12">
        <div class="flex-between flex-end pagetitle">
            <h4>{{ pageTitle }}</h4>
            <CustomDropdown ref="dropdownRef" :placeholder="textDesc" width="280px">
                <DateSelect slot="normal" :view="view" v-model="selectedDate" @update-count="handleUpdateView"
                    @change="handleDateChange" />
            </CustomDropdown>
        </div>
        <div v-if="dataRank == 1 && (dataType == 'ver_type' || dataType == 'check_type')"
            style="margin-bottom: 20px;text-align: left" class="beforeNotice">
            <p class="noticeTop flex"><img src="@/assets/site/siteSemInfo_Icon.svg" alt=""> 未计成本</p>
            <div v-if="dataType == 'ver_type'" class="noticeBot column">
                <p>1. AI（服务器成本） <span v-if="view == 'year'" style="color:red;">2025年（含）后计入成本</span></p>
                <p>2. Turnitin <span v-if="view == 'year'" style="color:red;">2025年（含）后计入成本</span></p>
                <p>3. 学术（知网PMLC，硕博VIP）<span v-if="view == 'year'" style="color:red;">2025年（含）后计入成本</span></p>
            </div>
            <div v-if="dataType == 'check_type'" class="noticeBot column">
                <p>1. AI（服务器成本）</p>
                <p>2. Turnitin国际版、TurnitinUK版、Turnitin国际版+AI</p>
                <p>3. 知网PMLC，硕博VIP <span v-if="view == 'year'" style="color:red;">2025年（含）后计入成本</span></p>
            </div>
        </div>
        <div class=" flex-common" id="">
            <el-form>
                <GuipTable :tableData="tableData" style="width: 100%" :border="true" @sort-change="handleSortChange" :loading="loading"
                    @cell-mouse-enter="handleRowHover">
                    <el-table-column fixed="left" prop="sort" label="排序" width="70"></el-table-column>
                    <el-table-column fixed="left"
                        v-if="(dataRank == 1 || dataRank == 2) && (dataType == 'ver_type' || dataType == 'check_type')"
                        prop="name" :key="selectedType" :label="type_select[selectedType]" min-width="120">

                        <template slot="header">
                            <el-select class="custom-select tableHeaderSelect" popper-class="custom-select-dropdown"
                                v-model="selectedType" @change="changeRankType">
                                <el-option v-for="(item,type) in type_select" :key="type" :label="item" :value="type">
                                </el-option>
                            </el-select>
                        </template>
                        <template slot-scope="scope">
                            <GuipToolTip :content=" scope.row.name">
                                <span class=nowrap>{{ scope.row.name }}</span>
                            </GuipToolTip>
                        </template>

                    </el-table-column>
                    <el-table-column v-else fixed="left" prop="name" :label="type_desc[dataType]" width="150"></el-table-column>

                    <el-table-column v-for="(field, index) in valueFields" :key="field" :label="labels[index]"
                        :prop="String(index + 1)"
                        :render-header=" (h, scope) => index == 3 ? renderHeaderWithIcon(h, scope, require('@/assets/require.svg')) : scope.column.label"
                        sortable="custom" min-width="170">

                        <!--产品利润排行展示查看更多-->
                        <template v-if="index == 3 && dataRank == 1" scope="{ row, $index }">
                                <el-popover v-model="row.id_popover" :ref="`popover-${row.id}`"
                                placement="bottom" trigger="manual" :append-to-body="false"  :visible-arrow="true"
                                popper-class="custom-popover"  @show="popshow" >

                                <div v-if="type != 'agent'" class="pop-wrap">
                                    <div class="flex-between flex pop-top">
                                        <h3>
                                             {{ row.name }}
                                            <span class="lookMore" @click="goLookMoreData(row.id)">查看更多</span>
                                        </h3>
                                        <span class="flex point" @click="closePop(row,'id')">
                                            <img src="@/assets/register/close.svg">
                                        </span>
                                    </div>
                                    <el-table :data="tableData1" style="width: 100%">
                                        <el-table-column prop="value_1" width="200" label="日期"></el-table-column>

                                        <el-table-column width="200" :label="rank_type_desc[dataRank]">
                                            <template slot-scope="scope">
                                                <div class="flex">
                                                    {{ scope.row.value_2 }}
                                                </div>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                                <div v-else class="pop-wrap">
                                    <div class="flex-between flex pop-top">
                                        <h3>
                                            {{ row.name }}
                                            <span class="lookMore" @click="goLookCheckTypeRank(row.id)">查看更多</span>
                                        </h3>
                                        <span class="flex point" @click="closePop(row,'id')">
                                            <img src="@/assets/register/close.svg">
                                        </span>
                                    </div>
                                    <el-table :data="tableData1" style="width: 100%">
                                        <el-table-column prop="sort" width="95" label="排序">

                                        </el-table-column>
                                        <el-table-column prop="name" width="250" label="服务名称"></el-table-column>
                                        <el-table-column prop="rate" width="130" label="毛利占比">
                                            <template slot-scope="scope">
                                                <div class="flex">
                                                    {{ scope.row.rate }} %
                                                </div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column width="150" :label="rank_type_desc[dataRank]">
                                            <template slot-scope="scope">
                                                <div class="flex">
                                                    {{ scope.row.value_1 }}
                                                </div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="value_2" width="130" label="订单数"></el-table-column>
                                    </el-table>
                                </div>

                                <div class="flex" slot="reference">
                                    <!-- {{ row[field] }} -->
                                    {{ $formatNumber(row[field]) }}
                                        <svg-icon  :size="14" v-if="row[field] *100 != 0" 
                                            :path="require('@/assets/super/list-detail.svg')" :color="'#8A9099'"
                                            :hoverColor="'#006AFF'" @click="handleClick(row, $index, 'id')" />
                                </div>
                            </el-popover>

                        </template>
                        <template v-else slot-scope="scope">
                            <div class="flex">
                                {{ $formatNumber(scope.row[field]) }}
                            </div>
                        </template>
                    </el-table-column>

                    <!--产品利润排行展示代理商排行-->
                    <el-table-column v-if="dataRank == 1 && (dataType == 'ver_type' || dataType == 'check_type')"
                        :render-header=" (h, scope) => renderHeaderWithIcon(h, scope, require('@/assets/require.svg')) "
                        key="top" prop="top" label="代理商排行" width="250">
                        <template v-slot="{ row, $index }">
                            <!-- :fallback-placements="['bottom','top','left']" -->
                            <el-popover v-model="row.id_popover_2" :ref="`popover_2-${$index}`"
                                placement="bottom" trigger="manual" :append-to-body="false"  :visible-arrow="true"
                                popper-class="custom-popover"  @show="popshow" >
                            <!-- <el-popover v-model="row.id_popover_2" :ref="`popover_2-${$index}`" trigger="manual"
                                popper-class="custom-popover"  @show="popshow" :append-to-body="false" 
                                 :visible-arrow="true" 
                               > -->
                                <div class="pop-wrap">
                                    <div class="flex-between flex pop-top">
                                        <h3>
                                            {{ row.name }} 代理商排行
                                            <span class="lookMore" @click="goLookAgentRank(row.id)">查看更多</span>
                                        </h3>
                                        <span class="flex point" @click="closePop(row,'id')">
                                            <img src="@/assets/register/close.svg">
                                        </span>
                                    </div>
                                    <GuipTable :tableData="tableData1" :key="dateCurrent" style="width: 100%" max-height="218">
                                        <el-table-column prop="sort" width="100" label="排行"></el-table-column>
                                        <el-table-column prop="name" width="200" label="代理商"></el-table-column>
                                        <el-table-column prop="value_1" width="200" label="销售额"></el-table-column>
                                    </GuipTable>
                                </div>
                                <span v-if="top_list[row.id]" slot="reference" class="flex">
                                    No.1 {{ top_list[row.id]['name'] }}
                                    <svg-icon :size="14" @click="handleClick2(row, $index, 'id')"
                                        :path="require('@/assets/super/list-detail.svg')" :color="'#8A9099'"
                                        :hoverColor="'#006AFF'" />
                                </span>
                                <span v-else slot="reference">暂无排行</span>
                            </el-popover>
                        </template>
                    </el-table-column>
                </GuipTable>
                <el-pagination background @size-change='handleSizeChange' @current-change='handleCurrentChange'
                    :current-page="currentPage" :page-size=pageSize layout="prev, pager, next,jumper"
                    :total="parseInt(total)">
                </el-pagination>
            </el-form>
        </div>
    </div>
</template>
<script>
import DateSelect from '@/components/super/DateSelect.vue';
import GuipTable from '@/components/GuipTable.vue';
import CustomDropdown from '@/components/CustomDropdown.vue';
import SvgIcon from '@/components/SvgIcon.vue';
import GuipToolTip from '@/components/GuipToolTip.vue';
import {getDate,getFormattedDate} from "@/utils/common.js"

// import HoverImage from '@/components/super/HoverImage.vue';
export default {
    name: 'rank_batch_list',
    props: {
        pageTitle: {
            type: String,
            default: ''
        },
        rank_type: {
            type: Number,
            default: 0
        },
        type: {
            type: String,
            default: ''
        }
    },
    components: {
        // HoverImage,
        GuipToolTip,
        SvgIcon,
        GuipTable,
        DateSelect,
        CustomDropdown
    },
    data() {
        return {
            loading: false,
            dateCurrent:Date.now(),
            viewDesc: {
                'month': '月份',
                'monthTwo': '月份',
                'year': '年份',
            },
            rank_type_desc: {
                1: '毛利润',
                2: '订单数',
                3: '退单数',
                4: '充值金额',
            },
            type_desc: {
                'agent': '代理商昵称',
                'ver_type': '品牌名称',
                'check_type': '服务名称',
            },
            type_select: {
                'ver_type': '按品牌名称',//2
                'check_type': '按服务名称',//1
            },
            selectedType: 'check_type',
            view: 'month',
            labels: ['', '', '', ''],
            current_month: '',
            valueFields: ['value_1', 'value_2', 'value_3', 'value_4'],
            currentPage: 1,    //当前页
            pageSize: 10,   //每页的容量
            total: 0,   //列表总数
            sort_by: 4,
            sort_order: 2,
            text: '',//下拉框显示具体文案
            textDesc: '',//下拉框显示具体文案
            selectedDate: new Date(),//默认当天日期
            dataType: '',
            dataRank: '',
            tableData: [],
            top_list: [],
            tableData1: [],
            show_detail_index: 0,
        }
    },
    mounted() {
        this.init()
    },
    computed: {},
    watch: {
        '$route'() {
            this.init()
        }
    },
    methods: {
        init() {
            this.selectedType = this.type;
            document.title = this.pageTitle;
            this.text = this.getNowDate()
            this.dataType = this.type
            this.dataRank = this.rank_type


            this.getRankingData();
        },
        handleUpdateView(newView) {
            this.view = newView;
        },
        getNowDate() {
            const viewdesc = this.viewDesc[this.view];
            const currentYearMonth = getFormattedDate('YYYY-MM')
            this.textDesc = viewdesc + currentYearMonth;
            return `${currentYearMonth}`
        },
        handleDateChange(date) {
            const viewdesc = this.viewDesc[this.view];
            this.text = this.view == 'year' ? getDate(date,'yyyy') : getDate(date,'yyyy-mm')
            this.textDesc = viewdesc + this.text;
            this.selectedDate = date;
            localStorage.setItem('date', JSON.stringify(date))

            this.$refs.dropdownRef.closeDropdown();

            this.currentPage = 1;
            this.getRankingData()
        },
        goLookMoreData(id) {
            let query = {}
            query.date = this.text
            query.rank_type = this.dataRank
            if (this.dataType == 'agent') {
                query.aid = id
            }
            if (this.dataType == 'ver_type') {
                query.ver_type = id
            }
            if (this.dataType == 'check_type') {
                query.check_type = id
            }
            window.open(this.$router.resolve({
                path: '/super/ranking/detail',
                query: query
            }).href, '_blank')
        },
        goLookAgentRank(id) {
            let query = {}
            query.date = this.text
            query.rank_type = this.dataRank
            query.type = 'agent'
            if (this.dataType == 'ver_type') {
                query.ver_type = id
            }
            if (this.dataType == 'check_type') {
                query.check_type = id
            }
            window.open(this.$router.resolve({
                path: '/super/ranking/list',
                query: query
            }).href, '_blank')
        },
        goLookCheckTypeRank(id) {
            let query = {}
            query.date = this.text
            query.rank_type = this.dataRank
            query.type = 'check_type'
            query.aid = id
            window.open(this.$router.resolve({
                path: '/super/ranking/list',
                query: query
            }).href, '_blank')
        },
        closePop(row, type) {
            row[type + '_popover'] = false;
            row[type + '_popover_2'] = false;
        },
        handleClick(row, index, type) {
            // 关闭其他行的弹框
            this.tableData.forEach((item, i) => {
                item[type + '_popover_2'] = false;
                if (i !== index) {
                    item[type + '_popover'] = false;
                }
            });
            // 打开当前行的弹框
            row[type + '_popover'] = true;

            let obj = {}
            if (this.dataType == 'agent') {
                obj.aid = row.id
            }
            if (this.dataType == 'ver_type') {
                obj.ver_type = row.id
            }
            if (this.dataType == 'check_type') {
                obj.check_type = row.id
            }
            if (this.dataType == 'agent') {
                let obj = {}
                obj.aid = row.id
                this.getCheckTypeRankingList(obj);
            } else {
                this.getRankingDetail(obj);
            }
        },
        handleClick2(row, index, type) {
            console.log('执行了');
            // 关闭其他行的弹框
            this.tableData.forEach((item, i) => {
                item[type + '_popover'] = false;
                if (i !== index) {
                    item[type + '_popover_2'] = false;
                }
            });
            // 打开当前行的弹框
            row[type + '_popover_2'] = true;

            let obj = {}
            if (this.dataType == 'agent') {
                obj.aid = row.id
            }
            if (this.dataType == 'ver_type') {
                obj.ver_type = row.id
            }
            if (this.dataType == 'check_type') {
                obj.check_type = row.id
            }
            this.getAgentRankingList(obj);
        },
        popshow() {
            var ariaEls = document.querySelectorAll('.el-popover')
            ariaEls.forEach((item) => {
                item.removeAttribute('aria-hidden')
            })

            ariaEls = document.querySelectorAll('.el-radio__original')
            ariaEls.forEach((item) => {
                item.removeAttribute('aria-hidden')
            })
        },
        handleSortChange({ prop, order }) {
            console.log('prop--排序', prop);
            this.sort_by = 4;
            this.sort_order = 2;
            if (order == 'ascending') {
                this.sort_by = prop;
                this.sort_order = 1;
            }
            if (order == 'descending') {
                this.sort_by = prop;
                this.sort_order = 2;
            }
            this.currentPage = 1;
            this.getRankingData()
        },
        handleRowHover(row) {
            this.show_detail_index = row.sort
        },
        changeRankType() {
            // const dataRankObj = {
            //     'check_type':'1',
            //     'ver_type':'2'
            // }
            this.dataType = this.selectedType
            // this.dataRank = dataRankObj[this.selectedType]
            this.getRankingData()
        },
        // 获取排名数据：根据当前选择的数据类型调用相应的排名接口
        getRankingData() {
            this.setLabelText();
            if (this.dataType == 'agent') {
                this.getAgentRanking()
            }
            if (this.dataType == 'ver_type') {
                this.getVerRanking()
            }
            if (this.dataType == 'check_type') {
                this.getTypeRanking()
            }
        },
        setLabelText() {
            const date = new Date(this.text);
            const year = date.getFullYear();
            const month = date.getMonth() + 1;

            const currentYear = new Date().getFullYear();
            const currentMonth = new Date().getMonth() + 1;

            this.current_month = '';
            if (this.view === 'month' && year == currentYear && month == currentMonth) {
                this.current_month = '(当月)';
            }
            //表格 头部label 
            this.labels = [];
            if (this.view === 'year') {
                for (let i = 3; i >= 0; i--) {
                    this.labels.push((year - i) + '年' + this.rank_type_desc[this.rank_type]);
                }
            } else {
                const monthLabels = [];
                for (let i = 3; i >= 0; i--) {
                    let m = month - i;
                    if (m <= 0) m += 12;

                    monthLabels.push(m + '月' + this.rank_type_desc[this.rank_type]);
                }
                this.labels = monthLabels;
            }
        },
        getAgentRanking() {
            //代理商排行
            const that = this
            that.tableData = []
            this.$http('POST', '/supernew/ajax_get_agent_batch_list', {
                date: that.text,
                rank_type: that.dataRank,
                sort_by: that.sort_by,
                sort_order: that.sort_order,
                cur_page: that.currentPage,
                page_size: that.pageSize,
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData = response.data.list
                    that.total = response.data.total
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        getVerRanking() {
            //品牌排行
            const that = this
            that.tableData = []
            that.top_list = []
            this.$http('POST', '/supernew/ajax_get_ver_batch_list', {
                date: that.text,
                rank_type: that.dataRank,
                sort_by: that.sort_by,
                sort_order: that.sort_order,
                cur_page: that.currentPage,
                page_size: that.pageSize,
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData = response.data.list
                    that.top_list = response.data.top_list
                    that.total = response.data.total
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        getTypeRanking() {
            console.log(this.dataRank,'that.dataRank===');
            //产品排行
            const that = this
            that.tableData = []
            that.top_list = []
            this.loading = true;
            this.$http('POST', '/supernew/ajax_get_type_batch_list', {
                date: that.text,
                rank_type: that.dataRank,
                sort_by: that.sort_by,
                sort_order: that.sort_order,
                cur_page: that.currentPage,
                page_size: that.pageSize,
            }).then(response => {
                this.loading = false;
                this.$nextTick(() => {
                    that.tableData = response.data.list
                    that.top_list = response.data.top_list
                    that.total = response.data.total
                })
            }).catch(error => {
                this.loading = false;
                console.error(error, 'error')
            })
        },
        getRankingDetail(obj) {
            const that = this
            that.tableData1 = []
            this.$http('POST', '/supernew/ajax_get_rank_detail', {
                date: that.text,
                rank_type: that.dataRank,
                sort_by: 2,
                sort_order: 2,
                ...obj
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData1 = response.data.list.slice(0, 5)
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        getAgentRankingList(obj) {
            const that = this
            that.tableData1 = []
            this.$http('POST', '/supernew/ajax_get_agent_rank_list', {
                date: that.text,
                rank_type: that.dataRank,
                cur_page: 1,
                page_size: 5,
                ...obj
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData1 = response.data.list
                    that.dateCurrent = Date.now();
                    console.log(that.tableData1,'tableData1=');
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        getCheckTypeRankingList(obj) {
            const that = this
            that.tableData1 = []
            this.$http('POST', '/supernew/ajax_get_type_rank_list', {
                date: that.text,
                rank_type: that.dataRank,
                cur_page: 1,
                page_size: 5,
                ...obj
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData1 = response.data.list.slice(0, 5)
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.getRankingData()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getRankingData()
        },
    }
}
</script>
<style scoped lang="scss">
.pagetitle {
    margin-bottom: 12px;
    h4 {
        margin-bottom: 0;
    }
}

.pop-wrap {
  display: flex;
  flex-direction: column;
  gap: 20px;
  box-sizing: border-box;

  .pop-top {
    h3 {
      font-size: 16px;
      font-weight: bold;
      line-height: 18px;
      letter-spacing: 0.08em;
      color: #1D2129;
      margin: 0;

      span {
        display: inline-block;
        margin-left: 12px;
        font-size: 14px;
        line-height: 18px;
        color: #006AFF;
      }
    }

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

.lookMore {
    cursor: pointer;
    font-weight: 400;
}

.beforeNotice {
    border-radius: 4px;
    background: #F2F7FF;
    border: 1px solid #BFDAFF;
    padding: 20px 14px;
    color: #1E2226;
    letter-spacing: 0.08em;

    .noticeTop {
        gap: 8px;
        margin-bottom: 12px;

    }

    .noticeBot {
        gap: 10px;
    }

}

.tableHeaderSelect ::v-deep .el-input__inner {
    font-size: 14px;
    font-weight: normal;
    letter-spacing: 0.08em;
    color: #1E2226;
    height: 100%;
}
</style>
