<script setup>
import {ref} from "vue"
import _ from "lodash"
import { useRouter} from 'vue-router';
import { ArrowDown,ArrowUp } from '@element-plus/icons-vue'
import moment from "moment";

import { dataMainInterface,customInterence } from '@/api/api.js';
import {dataReportStatisticHook} from './hook.js';

const $router=useRouter()

const productOpts=ref([])
const selectProductIndex=ref(0)

/* 获取表格数据 */
const getTableData=()=>{
	dataLoading.value = false;
	const productOpt = productOpts.value[selectProductIndex.value]
	const collectMap = {
		999:'collectStatistic',
		998:'chartStatistic'
	}
	const InterfaceName = selectProductIndex.value>=998?collectMap[selectProductIndex.value]:'ficcProductStatistic'
	dataMainInterface[InterfaceName]({
		DataType: default_tab.value === '周度统计表' ? 'week' : default_tab.value === '月度统计表' ? 'month' : 'time_interval',
		StartDate: select_date.value ? select_date.value[0] : '',
		EndDate: select_date.value ? select_date.value[1] : '',
		ProductId:productOpt?productOpt.ProductId:'',
		ProductType:productOpt?productOpt.ProductType:'',
	}).then(res => {
		const { Data,Ret } = res;
		if(Ret !== 200) return

		//总合计数据处理
		totalGroupArr.value = filterTableData(Data.SellerYbLogRecordNumList,{},'ficcproduct');

		//处理数据结构
		let data = _.cloneDeep(Data.List).sort((a,b) => b.Item.length - a.Item.length);
		if(!['admin','ficc_admin'].includes(Role.value)) data = data.sort((a,b) => b.Item.length - a.Item.length);

		data.forEach(item => {
			item.showDetail=false
			
			let groupDataArr = filterTableData(item.SellerYbLogRecordNumList,{
				rs_name: item.Name + '合计'
			},'ficcproduct');
			item.subGroupArr=groupDataArr

			item.Item && item.Item.forEach(sub_item => {
				
				let dataArr = filterTableData(sub_item.SellerYbLogRecordNumList,{
					rs_name : sub_item.Name,

				},'ficcproduct')
				sub_item.dataArr=dataArr
			})
		})

		datalist.value = data;
		dataLoading.value = true;
		
	})
}

//获取产品选项数据
const getProductOpts=async()=>{
	const res=await customInterence.getSubProduct({StatisticFlag:true})
	if(res.Ret===200){
		productOpts.value=res.Data||[]
		selectProductIndex.value=0
		getTableData()
	}
}

const productChange=(index)=>{
	selectProductIndex.value=index 
	getTableData()
}

/* 获取数据对应表头 */
const getColumnTitle=(index)=>{
	let title = '';

	if(['周度统计表','月度统计表'].includes(default_tab.value)) {
		title = [0,1,2].includes(index) 
		? tableTheadColumns.value[0] 
		: [3,4,5].includes(index) 
		? tableTheadColumns.value[1] 
		: [6,7,8].includes(index) 
		? tableTheadColumns.value[2] 
		: [9,10,11].includes(index) 
		? tableTheadColumns.value[3]
		: [12,13,14].includes(index) 
		? tableTheadColumns.value[4]
		: [15,16,17].includes(index) 
		? tableTheadColumns.value[5] 
		: '';
	} else {
		title = default_tab.value || `${select_date.value[0]}~${select_date.value[1]}`;
	}
	
	return title
}

/* 进入列表 */
const goList=({ ids, key, rs_name, value },index, parent,sub_index= "")=>{
	if(!parent.length || !value||key=='合计') return
	if(sub_index && (!value[sub_index] || !parent.length)) return
	const productOpt = productOpts.value[selectProductIndex.value]
	// 产品ID (收藏统计fakeId:998,999)
	const productionId = productOpt?productOpt.ProductId:selectProductIndex.value
	// 产品类型 (收藏统计fakeType:998,999)
	const ProductType=productOpt?productOpt.ProductType:selectProductIndex.value
	// 客户状态
	const CompanyStatus = key
	//销售ids
	const SellerIds = ids
	console.log('value',ids)
	
	// 开始结束日期
	let StartDate=''
	let EndDate=''
	
	// 应该是前几周
	let num = Math.floor(index/3) 
	if(default_tab.value=='周度统计表'){
		StartDate = moment().subtract(num, 'week').startOf('isoWeek').format('YYYY-MM-DD');
		EndDate = moment().subtract(num, 'week').endOf('isoWeek').format('YYYY-MM-DD');
	}else{
		StartDate = moment().subtract(num, 'M').startOf('month').format('YYYY-MM-DD');
		EndDate = moment().subtract(num, 'M').endOf('month').format('YYYY-MM-DD');
	}

	let column_title = getColumnTitle(index);

	let title =  encodeURIComponent(`${column_title}/${rs_name}/${key}`);
	sessionStorage.setItem('renewalTab',activeTab.value.tabName)	
	const {href}=$router.resolve({
		path: '/ficcProductlist',
		query: {
			ids: sub_index !== '' ? encodeURIComponent(ids[sub_index]) : encodeURIComponent(ids),
			title,
			productionId,
			ProductType,
			CompanyStatus,
			StartDate,
			EndDate,
			SellerIds
		}
	})
	
	window.open(href,'_blank')
}

const HOOK = dataReportStatisticHook({getTableData})
const {dataLoading,default_tab,select_date,totalGroupArr,datalist,tableTheadColumns,staticTabs}=HOOK.datas
const {Role,activeTab}=HOOK.computeds
const {filterTableData,changeTabHandle}=HOOK.functions
//start
getProductOpts()

</script>

<template>
    <div class="statistic-container product-statistic-page">
        <div class="tabs-box">
			<span
				class="custom-tab" 
				:class="index===selectProductIndex ?'activeTab':''"
				v-for="(item,index) in productOpts"
				:key="item.ProductId+item.ProductType"
				@click="productChange(index)"
			>
				{{item.ProductName}}
			</span>
      <!-- 加一个 收藏统计 crm12.3改名为 研报 / 视频收藏统计 -->
      <span 
        class="custom-tab"
        :class="selectProductIndex===999 ?'activeTab':''"
        @click="productChange(999)"
      >
        研报 / 视频收藏统计
      </span>
      <!-- 再加一个 图收藏统计 -->
      <span 
        class="custom-tab"
        :class="selectProductIndex===998 ?'activeTab':''"
        @click="productChange(998)"
      >
        图收藏统计
      </span>
		</div>
		<div class="frequency-cont">
			<ul class="frequency-ul">
				<li v-for="tab in staticTabs.slice(0,2)" :key="tab" :class="{act: tab=== default_tab}" @click="changeTabHandle(tab)">{{ tab }}</li>
			</ul>
		</div>
        <div class="table-cont"  v-loading="!dataLoading">
            <div class="table-body-wrapper">
				<table>
					<thead>
						<tr>
							<td rowspan="2" class="thead-rs">组别</td>
							<td rowspan="2" class="thead-rs">销售</td>
							<td
								:colspan="['周度统计表','月度统计表'].includes(default_tab) ? 3 : 1"
								v-for="item in tableTheadColumns"
								:key="item" 
								class="head-column"
							>
								{{item}}
							</td>	
						</tr>
						<tr v-if="['月度统计表'].includes(default_tab)">
							<template v-for="(item,index) in new Array(6).fill('')">
								<td>正式</td>
								<td>试用</td>
								<td>合计</td>
							</template>
						</tr>
						<tr v-else-if="['周度统计表'].includes(default_tab)">
							<template v-for="(item,index) in new Array(6).fill('')">
								<td>
									正式
								</td>
								<td>
									试用
								</td>
								<td>
									合计
								</td>
								
							</template>
						</tr>
					</thead>
					<tbody v-for="item in datalist" :key="item.Name">
							<tr>
								<td colspan="2" 
									@click="item.showDetail=!item.showDetail" 
								>{{item.Name}}合计
								<el-icon :size="14" style="vertical-align: text-top;" v-if="item.Item.length">
									<ArrowUp v-show="item.showDetail" />
									<ArrowDown v-show="!item.showDetail" />
								</el-icon>	
							</td>
								<td 
									v-for="(group_data,group_data_key) in item.subGroupArr" 
									:key="group_data_key"
									:class="{link: item.Item.length}"
								>

									<span 
										@click="goList(group_data,group_data_key,item.Item)" 
										v-if="Object.prototype.toString.call(group_data.value) === '[object Number]'"
										:style="{color:group_data.key=='合计'?'#333':''}"
									>
										{{ group_data.value !== 0 ? group_data.value : '' }}
									</span>

									<span 
										v-else 
										v-for="(sub_data_value,sub_index) in group_data.value" 
										@click="goList(group_data,group_data_key,item.Item,sub_index)" 
										:key="sub_index" 
										:style=" sub_data_value ? '' : 'color:#666'"
									>
										{{sub_data_value}} 
										<span style="color:#666">{{ sub_index === group_data.value.length - 1 ? '' : '/' }}</span>
									</span>
								</td>
							</tr>
							<template v-if="item.Item.length" >
								<tr :style="{display:item.showDetail?'table-row':'none'}">
									<td :rowspan="item.Item.length+1" class="thead-rs">{{item.Name}}</td>
								</tr>

								<tr v-for="rs in item.Item" :key="rs.AdminId" :style="{display:item.showDetail?'table-row':'none'}">
									<td class="thead-rs">{{rs.Name}}</td>

									<td 
										:class="['data-cell',{link: item.Item.length}]" 
										v-for="(data,data_key) in rs.dataArr" 
										:key="data_key"
									>
										
										<span 
											@click="goList(data,data_key,item.Item)" 
											v-if="Object.prototype.toString.call(data.value) === '[object Number]'"
											:style="{color:data.key=='合计'?'#333':''}"
										>
											{{ data.value !== 0 ? data.value : '' }}
										</span>

										<span 
											v-else 
											v-for="(sub_data_value,sub_index) in data.value" 
											:key="sub_index" 
											:style=" sub_data_value ? '' : 'color:#666'" 
											@click="goList(data,data_key,item.Item,sub_index)"
										>
											{{sub_data_value}} 	
											<span style="color:#666">{{ sub_index === data.value.length - 1 ? '' : '/' }}</span>
										</span>
									</td>
									
								</tr>
							</template>	
							
					</tbody>

					<tfoot>
						<tr>
							<td colspan="2">{{activeTab.tabSummationName}}</td>
							<td v-for="(total_data,total_data_key) in totalGroupArr" :key="total_data_key">

								<span v-if="Object.prototype.toString.call(total_data.value) === '[object Number]'">
									{{ total_data.value !== 0 ? total_data.value : '' }}
								</span>

								<span v-else v-for="(sub_data_value,sub_index) in total_data.value" :key="sub_index">
									{{sub_data_value}} 
									<span>{{ sub_index === total_data.value.length - 1 ? '' : '/' }}</span>
								</span>
							</td>
						</tr>
					</tfoot>
				</table>
			</div>
        </div>
    </div>
</template>

<style lang='scss' scoped>
*{ box-sizing: border-box;}
@import './index.scss';
.product-statistic-page{
	min-height: calc(100vh - 120px);;
}
.tabs-box{
	font-size: 18px;
	color: #999;
	.custom-tab{
		display: inline-block;
		margin-right: 30px;
		margin-bottom: 20px;
		color: #333;
		cursor: pointer;
    font-family: SimHei;
	}
	.activeTab{
		color: #409EFF;
		border-bottom: 2px solid #409EFF;
	}
}
</style>