<template>
	<el-row class="mt-8px" :gutter="8" justify="space-between">
		<!-- 待办-待审核商户、待审核商品 -->
		<el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px" v-if="isShowToBeDone">
			<el-card shadow="never">
				<template #header>
					<div class="h-3 flex justify-between items-center cursor-pointer" @click="refreshToDo">
						<span>待办</span>
					</div>
				</template>
				<el-skeleton :loading="loading" animated>
					<ToBeDone ref="toBeDoneRef" />
				</el-skeleton>
			</el-card>
		</el-col>

		<!-- 订单 -->
		<el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px"  v-if="isShowOrder">
			<el-card shadow="never">
				<template #header>
					<div class="h-3 flex justify-between items-center">
						<span>订单</span>
						<div class="!w-240px flex" v-if="!mobile">
							<el-date-picker
								v-model="state.orderTime"
								value-format="YYYY-MM-DD"
								type="daterange"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1'), new Date('1')]"
								@change="changeOrderTime"
							/>
						</div>
						<el-button @click="showOrderTime" v-else-if="mobile && !state.orderStatrTime && !state.orderEndTime">选择日期</el-button>
						<span style="font-size: 14px" v-else @click="showOrderTime">{{ state.orderStatrTime }} - {{ state.orderEndTime }}</span>
						<van-calendar v-model:show="state.mobileOrderTimeShow" type="range" :min-date="minDate"  @confirm="MobilechangeOrderTime" />
					</div>
				</template>
				<el-skeleton :loading="loading" animated>
					<el-row>
						<el-col>
								<el-skeleton :loading="loading" animated>
									<Echart :options="lineOptions" :height="250" @chart-init="OrderRefInit"/>
								</el-skeleton>
						</el-col>
					</el-row>
				</el-skeleton>
			</el-card>
		</el-col>

		<!-- 平台收益 -->
		<el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px"  v-if="isShowPtProfit">
			<el-card shadow="never">
				<template #header>
					<div class="h-3 flex justify-between items-center">
						<span>平台收益</span>
					</div>
				</template>
				<el-skeleton :loading="loading" animated>
					<el-row>
						<el-col>
							<!-- <el-card shadow="hover" class="mb-8px border-none"> -->
								<el-skeleton :loading="loading" animated>
									<Echart :options="pieOptionsData" :height="280" />
								</el-skeleton>
							<!-- </el-card> -->
						</el-col>
					</el-row>
				</el-skeleton>
			</el-card>
		</el-col>

		<!-- 消费者数量 -->
		<el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px"  v-if="isShowMember">
			<el-card shadow="never">
				<template #header>
					<div class="h-3 flex justify-between items-center">
						<span>消费者数量</span>
					</div>
				</template>
				<el-skeleton :loading="loading" animated>
					<el-row>
						<el-col>
								<MemberStatisticsCard />
						</el-col>
					</el-row>
				</el-skeleton>
			</el-card>
		</el-col>
		
		<!-- 消费者充值 -->
		<el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px"  v-if="isShowRecharge ">
			<el-card shadow="never">
				<template #header>
					<div class="h-3 flex justify-between items-center">
						<span>充值</span>
					</div>
				</template>
				<el-skeleton :loading="loading" animated>
					<el-row>
						<el-col>
							<Echart :height="300" :options="lineChartOptions" />
						</el-col>
					</el-row>
				</el-skeleton>
			</el-card>
		</el-col>
	</el-row>
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { pointsToPoint } from '@/utils'
import { debounce } from 'lodash-es'
import { lineOptions,pieOptions} from './echarts-data'
import MemberStatisticsCard from '@/views/mall/home/components/MemberStatisticsCard.vue'
import { PtProfitApi } from '@/api/system/distri/ptprofit'
import { getPtOrderList,getRechargeRecord } from '@/api/home/index'
import ToBeDone from './components/ToBeDone.vue'
import { checkPermi } from '@/utils/permission'
import { useAppStore } from '@/store/modules/app'
import { formatDate } from '@/utils/formatTime'
import dayjs from 'dayjs'
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)
defineOptions({ name: 'Home' })
const toBeDoneRef = ref(null)
// 防抖 防止快速刷新
const refreshToDo = debounce(() => {
	toBeDoneRef.value.getList()
}, 1000)
const loading = ref(true)


const state = reactive({
	orderTime:'',
	orderStatrTime: '',
	orderEndTime: '',
	mobileOrderTimeShow:false
})
const isShowToBeDone = computed(() => checkPermi(['sale:merchant-apply:query']) ||  checkPermi(['	product:spu:query'])  )
const isShowOrder = computed(() => checkPermi(['trade:order:query']))
const isShowPtProfit = computed(() => checkPermi(['distri:pt-profit:query']) )
const isShowRecharge = computed(() =>  checkPermi(['distri:consumption-top-up-log:ptTopUpWithUserTopUpList']))
const isShowMember = computed(() => checkPermi(['statistics:member:query']) )


// 订单
let OrderRef;
function OrderRefInit(instance){
	OrderRef = instance;
}
const minDate = new Date(2024, 5, 12);
let lineOptionsData = reactive<EChartsOption>(lineOptions) as EChartsOption
const getOrder = async (startTime?:string, endTime?:string) => {
	const data = await getPtOrderList({startTime,endTime})
	set(
		lineOptionsData,
		'xAxis.data',
		data.xaxis.data
	)
	const series = data?.series.map((v) => {
		return {
			count: v.count,
			value: v.money / 100
		}
	})
	lineOptionsData!.series![0].data =  series;
	if (OrderRef) {
    OrderRef.setOption(lineOptionsData,true);

  }
}
function changeOrderTime(value){
	state.orderStatrTime = value[0]
	state.orderEndTime = value[1]
	getOrder(state.orderStatrTime,state.orderEndTime)
}

function showOrderTime(){
	state.mobileOrderTimeShow = true;
}
function closeOrderTime(){
	state.mobileOrderTimeShow = false;
}
function MobilechangeOrderTime(value){
	closeOrderTime()
	state.orderStatrTime = dayjs(value[0]).format('YYYY-MM-DD')
	state.orderEndTime = dayjs(value[1]).format('YYYY-MM-DD')
	getOrder(state.orderStatrTime,state.orderEndTime)
}

// 平台收益
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
const getPtProfit = async () => {
	
	const data = await PtProfitApi.getPtProfitPage({ pageNo: 1, pageSize: 10})
	pieOptionsData!.series![0].data = [
		{ value: pointsToPoint(data?.list[0].profit), name: '利润(硒泽源)' },
		{ value: pointsToPoint(data?.list[0].ptTotalAdd), name: '平台总收入' },
		{ value: pointsToPoint(data?.list[0].ptAdd), name: '平台服务费' },
		{ value: pointsToPoint(data?.list[0].ptGrossAdd), name: '平台存余' }
	]
}

// 充值
const lineChartOptions = reactive<EChartsOption>({
	title: {
    text: '',  // 初始标题为空，稍后动态设置
    left: 'center', // 标题水平居中
    top: '2%', // 标题距离顶部位置
  },
  dataset: {
    dimensions: ['date', 'consumptionPoints'],
    source: []
  },
  legend: {
    show: false // 隐藏图例 "总额"
  },
  series: [
    { 
      name: '总额',
      type: 'line',
      smooth: true,
      areaStyle: null  
    }
  ],
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    formatter: (params: any) => {
      const currentData = params[0].data.consumptionPoints;
      return `日期: ${params[0].name}<br/>当天充值金额: ￥${currentData}`;
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    axisTick: {
      show: false
    },
    axisLabel: {
      formatter: (date: string) => formatDate(date, 'MM-DD') // 格式化日期
    }
  },
  yAxis: {
    axisTick: {
      show: false
    },
		axisLabel: {
			margin: 2,
			formatter: function (value, index) {
					if (value >= 10000 && value < 10000000) {
							value = value / 10000 + "万";
					} else if (value >= 10000000) {
							value = value / 10000000 + "千万";
					}
					return value;
			}
		},
		nameGap: 30,      // 增加 Y 轴和标签之间的间距
  },
	grid: {
		left: 35
	},
  dataZoom: [
		{
      type: 'inside', 
      start: 100, 
      end: 100, 
      zoomOnMouseWheel: 'shift',  // PC端支持 shift+鼠标滚轮缩放
      moveOnMouseMove: true,      // 支持单指拖动进行平移
      moveOnMouseWheel: true 
    },
		
  ],
	axisPointer: {
		type: 'none'  // 禁用 X 和 Y 轴上的指示线
	},
	

}) as EChartsOption

// 获取充值记录数据
const getRecharge = async () => {
  const data = await getRechargeRecord();
  
  if (lineChartOptions.dataset && lineChartOptions.dataset['source']) {
    const totalRecords = data.topUpList.length;
    const lastSevenRecords = data.topUpList.slice(Math.max(totalRecords - 7, 0));
    // 设置总额标题
    lineChartOptions.title.text = `总额: ￥${pointsToPoint(data.totalConsumptionPoints)}`;

    // 将所有数据存入 source，并转换为人民币金额
    lineChartOptions.dataset['source'] = data.topUpList.map((v) => {
      return {
        date: v.date,
        consumptionPoints: pointsToPoint(v.consumptionPoints) // 使用 pointsToPoint 转换为金额
      };
    });
    
    // 确保初始显示的是最后7条数据
    if (totalRecords > 7) {
      lineChartOptions.dataZoom[0].start = ((totalRecords - 7) / totalRecords) * 100; // 显示最后7条
    }
  }
};

const getAllApi = async () => {
	const promises = [];
	if (isShowOrder.value) {
    promises.push(getOrder());
  }
  if (isShowPtProfit.value) {
    promises.push(getPtProfit());
  }
  if (isShowRecharge.value) {
    promises.push(getRecharge());
  }
	if (promises.length > 0) {
    await Promise.any(promises);
  }
	loading.value = false
}

getAllApi()
</script>
<style scoped lang='scss'>
.kjfs {
	cursor: pointer;
	width: 65px;
	height: 65px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	border-radius: 4px;
	border: 1px solid #e4e7ed;
	padding: 10px;
	font-size: 14px;
}

.border-none {
	border: none;
}
</style>