<template>
    <div class="demo-wrap min-flex-right">
        <div class="flex-between">
            <h2>{{ filterTitle ? filterTitle : pageTitle }}</h2>
            <CustomDropdown v-if="showDateSelect"
                            ref="dropdownRef"
                            :placeholder="'（'+viewDesc[this.view]+')'+text"
                            width="280px">
                <DateSelect slot="normal"
                            :view="view"
                            :onlyYear="onlyYear"
                            v-model="selectedDate"
                            @update-count="handleUpdateView"
                            @change="handleDateChange"/>
            </CustomDropdown>
        </div>
        <div class=" flex-common" v-if="dataType == 'year'">
            <el-form>
                <el-table :data="tableData"
                          style="width: 100%"
                          @sort-change="handleSortChange"
                          @cell-mouse-enter="handleRowHover">

                    <el-table-column prop="sort" label="排序" width="100"></el-table-column>

                    <el-table-column prop="1" label="年份" sortable="custom">
                        <template slot-scope="scope">
                            {{ scope.row.value_1 }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="2" :label="rank_type_desc[dataRank]" sortable="custom">
                        <template slot-scope="scope">
                            {{ scope.row.value_2 }}
                        </template>
                    </el-table-column>

                    <el-table-column label="代理商排行">
                        <template v-slot="{ row, $index }">
                            <el-popover v-model="row.id_popover"
                                        placement="top"
                                        trigger="manual"
                                        :ref="`popover-${$index}`"
                                        @show="popshow">

                                <div class="pop-wrap">
                                    <div class="flex-between flex pop-top">
                                        <h3>
                                            {{ row.value_1 }} {{ rank_type_desc[dataRank] }}
                                            <span @click="goLookMoreData(row.value_1)">查看更多</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="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>
                                    </el-table>
                                </div>

                                <span v-if="top_list[row.id]" slot="reference">
                                    No.1 {{ top_list[row.id]['name'] }}
                                    <HoverImage v-if="show_detail_index == row.sort"
                                        @click="handleClick(row, $index, 'id')"
                                        :normal="require('@/assets/super/list-detail.svg')"
                                        :hover="require('@/assets/super/list-detail-hover.svg')"/>
                                </span>
                                <span v-else slot="reference">暂无排行</span>
                            </el-popover>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </div>

        <div class=" flex-common" v-if="dataType == 'month'">
            <el-form>
                <el-table :data="tableData"
                          style="width: 100%"
                          @sort-change="handleSortChange"
                          @cell-mouse-enter="handleRowHover">

                    <el-table-column prop="sort" label="排序" width="100"></el-table-column>

                    <el-table-column prop="1" label="月份" sortable="custom">
                        <template slot-scope="scope">
                            {{ scope.row.value_1 }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="2" :label="rank_type_desc[dataRank]" sortable="custom">
                        <template slot-scope="scope">
                            <div class="flex">
                                {{ scope.row.value_2 }}
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="代理商排行">
                        <template v-slot="{ row, $index }">
                            <el-popover v-model="row.id_popover"
                                        placement="top"
                                        trigger="manual"
                                        :ref="`popover-${$index}`"
                                        @show="popshow">
                                <div class="pop-wrap">
                                    <div class="flex-between flex pop-top">
                                        <h3>
                                            {{ row.value_1 }} {{ rank_type_desc[dataRank] }}
                                            <span @click="goLookMoreData(row.value_1)">查看更多</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="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>
                                    </el-table>
                                </div>
                                <span v-if="top_list[row.id]" slot="reference">
                                    No.1 {{ top_list[row.id]['name'] }}
                                    <HoverImage v-if="show_detail_index == row.sort"
                                        @click="handleClick(row, $index, 'id')"
                                        :normal="require('@/assets/super/list-detail.svg')"
                                        :hover="require('@/assets/super/list-detail-hover.svg')"/>
                                </span>
                                <span v-else slot="reference">暂无排行</span>
                            </el-popover>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </div>

        <div class=" flex-common" v-if="dataType == 'day'">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                <h3 style="margin: 0;"></h3>
                <span style="font-size: 14px; color: #999;">总{{ rank_type_desc[dataRank] }}：{{ total_value }}</span>
            </div>

            <el-form>
                <el-table :data="tableData"
                          style="width: 100%"
                          @sort-change="handleSortChange"
                          @cell-mouse-enter="handleRowHover">

                    <el-table-column prop="sort" label="排序"></el-table-column>

                    <el-table-column prop="1" label="日期" sortable="custom">
                        <template slot-scope="scope">
                            {{ scope.row.value_1 }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="2" :label="rank_type_desc[dataRank]" sortable="custom">
                        <template slot-scope="scope">
                            <div class="flex">
                                {{ scope.row.value_2 }}
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </div>

        <div class=" flex-common" v-if="dataType == 'agentnew'">
            <el-form>
                <el-table :data="tableData"
                          style="width: 100%"
                          @sort-change="handleSortChange"
                          @cell-mouse-enter="handleRowHover">

                    <el-table-column prop="1" label="加盟时间" sortable="custom">
                        <template slot-scope="scope">
                            {{ scope.row.regtime }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="nick" label="代理商昵称"></el-table-column>
                    <el-table-column prop="real_name" label="负责人"></el-table-column>
                    <el-table-column prop="phone" label="电话"></el-table-column>

                    <el-table-column prop="2" label="账户余额" sortable="custom">
                        <template slot-scope="scope">
                            {{ scope.row.remain_money }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="3" label="累计总额/元" sortable="custom">
                        <template slot-scope="scope">
                            {{ scope.row.total_money }}
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </div>

        <div class=" flex-common" v-if="dataType == 'order'">
            <el-form>
                <el-table :data="tableData" style="width: 100%">
                    <el-table-column prop="sale_id" label="订单ID"></el-table-column>
                    <el-table-column prop="income" label="收入"></el-table-column>
                    <el-table-column prop="cost" label="成本"></el-table-column>
                    <el-table-column prop="profit" label="毛利"></el-table-column>
                    <el-table-column prop="is_refund" label="是否退款">
                        <template slot-scope="scope">
                            {{ scope.row.is_refund == 1 ? '是' : '否' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="sale_date" label="销售日期"></el-table-column>
                </el-table>
            </el-form>
            <Pagination :curPage="cur_page" :hasNext="has_next" @change="handleChange" />
        </div>
    </div>
</template>
<script>
import DateSelect from '@/components/super/DateSelect.vue';
import CustomDropdown from '@/components/CustomDropdown.vue';
import HoverImage from "@/components/super/HoverImage.vue";
import Pagination from "@/components/Pagination.vue";

export default {
    name: 'rank_detail',
    props: {
        pageTitle: {
            type: String,
            default: ''
        },
        rank_type: {
            type: Number,
            default: 0
        },
        type: {
            type: String,
            default: ''
        },
        showDateSelect: {
            type: Boolean,
            default: true
        },
        lookMore:{
            type: Boolean,
            default: true
        },
    },
    components: {
        Pagination,
        HoverImage,
        DateSelect,
        CustomDropdown
    },
    data() {
        return {
            viewDesc: {
                'month': '月份',
                'monthTwo': '月份',
                'year': '年份',
            },
            rank_type_desc: {
                1: '毛利润',
                2: '订单数',
                3: '退单数',
            },
            aid: 0,
            ver_type: 0,
            check_type: 0,
            showfilterTitle: false,
            filterTitle: "",
            view: 'year',
            onlyYear: true,
            dataType: '',
            dataRank: '',
            text: '',//下拉框显示具体文案
            selectedDate: new Date(),//默认当天日期
            tableData: [],
            total_value: 0,
            tableData1: [],
            top_list: [],
            growth_list: [],
            show_detail_index: 0,
            has_next: false,
            cur_page: 1,
            page_size: 20,
            page_point: 0,
        }
    },
    mounted() {
        this.init()
    },
    computed: {},
    watch: {
        '$route'() {
            this.init()
        }
    },
    methods: {
        init() {
            document.title = this.pageTitle;

            this.text = ""
            if (this.showDateSelect) this.text = this.getNowYear()
            this.dataRank = this.rank_type
            this.dataType = this.type
            this.aid = this.$route.query.aid
            this.ver_type = this.$route.query.ver_type
            this.check_type = this.$route.query.check_type
            if (this.$route.query.date) this.text = this.$route.query.date
            if (this.$route.query.type) this.dataType = this.$route.query.type
            if (this.$route.query.rank_type) this.dataRank = this.$route.query.rank_type
            if (Object.keys(this.$route.query).length > 0) this.showfilterTitle = true

            this.getData()
        },
        handleUpdateView(newView) {
            this.view = newView;
        },
        getNowYear() {
            const now = new Date();
            const year = now.getFullYear();
            const currentYearMonth = `${year}`;
            return `${currentYearMonth}`
        },
        getDate(dateStr) {
            const date = new Date(dateStr);
            const year = date.getFullYear(); // 2025
            const month = date.getMonth() + 1; // 3 (表示3月)
            if (this.view == 'year') {
                return `${year}`
            } else {
                return `${year}-${month}`
            }
        },
        handleDateChange(date) {
            this.text = this.getDate(date)
            this.selectedDate = date;
            localStorage.setItem('date', JSON.stringify(date))

            this.$refs.dropdownRef.closeDropdown();
            this.getData()
        },
        goLookMoreData(date) {
            let query = {}
            query.date = date
            query.rank_type = this.dataRank
            query.type = 'agent'
            window.open(this.$router.resolve({
                path: '/super/ranking/list',
                query: query
            }).href, '_blank')
        },
        closePop(row, type) {
            row[type + '_popover'] = false; // 关闭弹框
        },
        handleClick(row, index, type) {
            // 关闭其他行的弹框
            this.tableData.forEach((item, i) => {
                if (i !== index) {
                    item[type + '_popover'] = false;
                }
            });
            // 打开当前行的弹框
            row[type + '_popover'] = true;

            this.getRankingList({date: row.value_1});
        },
        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}) {
            this.currentPage = 1;

            let sort_by = 0;
            let sort_order = 0;
            if (order == 'ascending') {
                sort_by = prop;
                sort_order = 1;
            }
            if (order == 'descending') {
                sort_by = prop;
                sort_order = 2;
            }
            this.getData({sort_by: sort_by, sort_order: sort_order})
        },
        handleRowHover(row) {
            this.show_detail_index = row.sort
        },
        getData(obj){
            if (this.dataType == 'agentnew') {
                this.getAgentNew(obj)
                return true;
            }

            if (this.dataType == 'order') {
                this.getOrderList()
                return true;
            }

            this.getRankingDetail(obj)
        },
        getRankingDetail(obj) {
            const that = this
            that.tableData = []
            that.top_list = []
            that.total_value = 0
            this.$http('POST', '/supernew/ajax_get_rank_detail', {
                rank_type: that.dataRank,
                aid: that.aid,
                ver_type: that.ver_type,
                check_type: that.check_type,
                date: that.text,
                ...obj
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData = response.data.list
                    that.total_value = response.data.total_value
                    that.top_list = response.data.top_list
                    that.total = response.data.total

                    if (that.showfilterTitle) that.filterTitle = response.data.title
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        getRankingList(obj) {
            const that = this
            that.tableData1 = []
            this.$http('POST', '/supernew/ajax_get_agent_rank_list', {
                rank_type: that.dataRank,
                cur_page: 1,
                page_size: 5,
                ...obj
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData1 = response.data.list
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        getAgentNew(obj) {
            const that = this
            that.tableData = []
            this.$http('POST', '/supernew/ajax_new_agent_list', {
                ...obj
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData = response.data.list
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        getOrderList(obj) {
            const that = this
            that.tableData = []
            this.$http('POST', '/supernew/ajax_get_order_check_list', {
                aid: that.aid,
                ver_type: that.ver_type,
                check_type: that.check_type,
                page_point: that.page_point,
                lose: 1,
                ...obj
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData = response.data.list
                    that.has_next = response.data.hasNext
                    if(!that.has_next) that.cur_page = response.data.cur_page
                    that.page_point = response.data.page_point
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        handleChange(payload) {
            this.cur_page = payload.cur_page
            this.getOrderList(payload)
        }
    }
}
</script>
<style scoped lang="scss">

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

  .pop-top {
    h3 {
      font-family: Microsoft YaHei UI;
      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;
    }
  }
}
</style>