<script>
import { defineComponent } from "vue";

export default defineComponent({
  beforeRouteEnter(to, from, next) {
		// 从续约客户列表进来才使用 renewalTab
		if(from.path != '/newCustomlist'){
			sessionStorage.removeItem('renewalTab')
		}
		next()
  },
});
</script>

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

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

const $router = useRouter()

//1 ficc 2权益
const tipMap=new Map([
	['试用','在所选时间段内，新建的或转为试用状态的客户数量（正式转试用的除外）'],
	['活跃1','在所选时间段内，累计报告阅读次数由＜50次，转变为≥50次的试用客户数量<br/>在所选时间段内，累计报告阅读次数由＜50次，转变为≥50次的非新增试用客户数量'],
	['活跃2','在所选时间段内，互动量由＜50次，转变为≥50次的试用客户数量'],
	['正式1','首次申请转正的审批通过时间，在所选时间段内的客户数'],
	['正式2','新签合同的开始日期在统计时间段内的客户'],
])

/* 获取表格数据 */
const getTableData=()=>{
	dataLoading.value = false;
	dataMainInterface.newcustomStatistic({
		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:activeTab.value.productionId
	}).then(res => {
		const { Data,Ret } = res;
		if(Ret !== 200) return

		//总合计数据处理
		totalGroupArr.value = filterTableData(Data.CompanyReportRecordNumList);

		//处理数据结构
		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.CompanyReportRecordNumList,{
				rs_name: item.Name + '合计'
			});
			item.subGroupArr=groupDataArr
			// $set(item,'subGroupArr',groupDataArr)

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

				})
				sub_item.dataArr=dataArr
				// $set(sub_item,'dataArr',dataArr)
			})
		})

		datalist.value = data;
		dataLoading.value = true;
		// console.log(data);
		/**
		 * 前一版每页显示前4周和前4个月的数据时  为7%
		 * 现在每页显示前6周和前6个月的数据
		 */
		// const dynamic_width = {
		// 	'周度统计表': '5%',
		// 	'月度统计表': '5%',
		// }
		// console.log(this.default_tab);
		// this.$nextTick(() => {
		// 	this.dataLoading = true;
			// $('table').find('td').css({ width: dynamic_width[this.default_tab]&&dynamic_width[this.default_tab]})
			// $('table').find('.thead-rs').css({ width: dynamic_width[this.default_tab] ? dynamic_width[this.default_tab] : '120px' })
			// $('table').find('.head-column').css({ width: dynamic_width[this.default_tab] ? dynamic_width[this.default_tab] : '25%' })
		// })
	})
}
/* 进入列表 */
const goList=({ ids, key, rs_name, value },index, parent,sub_index= "")=>{
	if(!parent.length || !value) return
	if(sub_index && (!value[sub_index] || !parent.length)) return

	let column_title = getColumnTitle(index);

	let title =  encodeURIComponent(`${column_title}/${rs_name}/${key}`);
	sessionStorage.setItem('renewalTab',activeTab.value.tabName)	
	const {href}=$router.resolve({
		name: 'newCustomlist',
		query: {
			ids: sub_index !== '' ? encodeURIComponent(ids[sub_index]) : encodeURIComponent(ids),
			title
		}
	})
	window.open(href,'_blank')
}

/* 获取数据对应表头 */
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
}
// HOOKS
const HOOK = dataReportStatisticHook({getTableData})
const {dataLoading,default_tab,select_date,totalGroupArr,datalist,tableTheadColumns,staticTabs}=HOOK.datas
const {Role,activeTab}=HOOK.computeds
const {filterTableData,switchTab,dateChange,changeTabHandle}=HOOK.functions

getTableData()

</script>

<template>
	<div class="statistic-container">
		<div class="custom-tab-box" v-if="Role==='admin'">
			<div class="custom-tab" :class="activeTab.tabName =='FICC' && 'activeTab'" @click="switchTab('FICC')">
				FICC
			</div>
			<div class="custom-tab" :class="activeTab.tabName =='QY' && 'activeTab'" @click="switchTab('QY')">
				权益
			</div>
		</div>
		<div class="frequency-cont">
			<ul class="frequency-ul">
				<li v-for="tab in staticTabs" :key="tab" :class="{act: tab=== default_tab}" @click="changeTabHandle(tab)">{{ tab }}</li>
			</ul>
			<date-picker
			v-model:value="select_date"
			type="date" 
			range
			value-type="format"
			:clearable="false"
			@change="dateChange"
			placeholder="请选择统计时间"/>
		</div>
		<div class="table-cont" v-show="dataLoading">
			<div class="table-body-wrapper">
				<table>
					<thead style="z-index: 1;">
						<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}}
								<el-tooltip 
									effect="dark" 
									placement="top-start"
									v-if="!['周度统计表','月度统计表'].includes(default_tab)"
								>
									<el-icon :size="14" style="vertical-align: text-top;"><InfoFilled /></el-icon>
									<template #content>
										<div v-html="tipMap.get(item==='试用'?item:`${item}${activeTab.productionId}`)"></div>
									</template>
								</el-tooltip>
							</td>	
						</tr>
						<tr v-if="['月度统计表'].includes(default_tab)">
							<template v-for="(item,index) in new Array(6).fill('')" :key="index" >
								<td>
									试用
									<el-tooltip 
										effect="dark" 
										placement="top-start" 
										v-if="index === 0"
										:content="tipMap.get('试用')"
									>
										<el-icon :size="14" style="vertical-align: text-top;"><InfoFilled /></el-icon>
									</el-tooltip>
								</td>
								<td>
									活跃
									<el-tooltip 
										effect="dark" 
										placement="top-start" 
										v-if="index === 0"
										:content="tipMap.get('活跃'+activeTab.productionId)"
									>
										<el-icon :size="14" style="vertical-align: text-top;"><InfoFilled /></el-icon>
										<template #content>
											<div v-html="tipMap.get('活跃'+activeTab.productionId)"></div>
										</template>
									</el-tooltip>
								</td>
								<td>
									正式
									<el-tooltip 
										effect="dark" 
										placement="top-start" 
										v-if="index === 0"
										:content="tipMap.get('正式'+activeTab.productionId)"
									>
										<el-icon :size="14" style="vertical-align: text-top;"><InfoFilled /></el-icon>
									</el-tooltip>
								</td>
							</template>
						</tr>
						<tr v-else-if="['周度统计表'].includes(default_tab)" >
							<template v-for="(item,index) in new Array(6).fill('')" :key="index" style="display: table;">
								<td>
									试用
								<el-tooltip 
									effect="dark" 
									placement="top-start" 
									v-if="index === 0"
									:content="tipMap.get('试用')"
								>
									<el-icon :size="14" style="vertical-align: text-top;"><InfoFilled /></el-icon>
								</el-tooltip>
								</td>
								<td>
									活跃
									<el-tooltip 
										effect="dark" 
										placement="top-start" 
										v-if="index === 0"
										:content="tipMap.get('活跃'+activeTab.productionId)"
									>
										<el-icon :size="14" style="vertical-align: text-top;"><InfoFilled /></el-icon>
										<template #content>
											<div v-html="tipMap.get('活跃'+activeTab.productionId)"></div>
										</template>
									</el-tooltip>
								</td>
								<td>
									正式
									<el-tooltip 
										effect="dark" 
										placement="top-start" 
										v-if="index === 0"
										:content="tipMap.get('正式'+activeTab.productionId)"
									>
										<el-icon :size="14" style="vertical-align: text-top;"><InfoFilled /></el-icon>
									</el-tooltip>
								</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]'"
									>
										{{ 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]'"
										>
											{{ 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';
</style>