<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 :key="index+'_2'">正式</td>
								<td :key="index+'_0'">试用</td>
								<td :key="index+'_1'">合计</td>
							</template>
						</tr>
						<tr v-else-if="['周度统计表'].includes(default_tab)">
							<template v-for="(item,index) in new Array(6).fill('')">
								<td :key="index+'_2'">
									正式
									<!-- <el-tooltip 
										effect="dark" 
										placement="top-start" 
										v-if="index === 0"
										:content="tipMap.get('正式')"
									>
										<i class="el-icon-info"/>
									</el-tooltip> -->
								</td>
								<td :key="index+'_0'">
									试用
								<!-- <el-tooltip 
									effect="dark" 
									placement="top-start" 
									v-if="index === 0"
									:content="tipMap.get('试用')"
								>
									<i class="el-icon-info"/>
								</el-tooltip> -->
								</td>
								<td :key="index+'_1'">
									合计
								</td>
								
							</template>
						</tr>
					</thead>
					<tbody v-for="item in datalist" :key="item.Name">
							<tr>
								<td colspan="2" 
									@click="item.showDetail=!item.showDetail" 
								>{{item.Name}}合计<i :class="item.showDetail?'el-icon-arrow-up':'el-icon-arrow-down'" v-if="item.Item.length"></i></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>

<script>
import { dataMainInterface,customInterence } from '@/api/api.js';
import mixin from './mixin';
export default {
    name:'',
	mixins: [ mixin ],
    data () {
		return {
			tipMap: new Map([
				['试用','在所选时间段内，新建的或转为试用状态的客户数量（正式转试用的除外）'],
				['正式','首次申请转正的审批通过时间，在所选时间段内的客户数'],
			]),
			productOpts:[],
			selectProductIndex:0
		};
	},
    mounted() {
		this.getProductOpts();
	},
    methods: {
        /* 获取表格数据 */
		getTableData() {
			this.dataLoading = false;
      const productOpt = this.productOpts[this.selectProductIndex]
      const collectMap = {
        999:'collectStatistic',
        998:'chartStatistic'
      }
      const InterfaceName = this.selectProductIndex>=998?collectMap[this.selectProductIndex]:'ficcProductStatistic'
			dataMainInterface[InterfaceName]({
				DataType: this.default_tab === '周度统计表' ? 'week' : this.default_tab === '月度统计表' ? 'month' : 'time_interval',
				StartDate: this.select_date ? this.select_date[0] : '',
				EndDate: this.select_date ? this.select_date[1] : '',
				ProductId:productOpt?productOpt.ProductId:'',
				ProductType:productOpt?productOpt.ProductType:'',
			}).then(res => {
				const { Data,Ret } = res;
				if(Ret !== 200) return

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

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

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

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

						},'ficcproduct')

						this.$set(sub_item,'dataArr',dataArr)
					})
				})

				this.datalist = data;
				this.dataLoading = true;
				
			})
		},

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

		productChange(index){
			this.selectProductIndex=index 
			this.getTableData()
		},

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

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

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

			let column_title = this.getColumnTitle(index);

			let title =  encodeURIComponent(`${column_title}/${rs_name}/${key}`);
			sessionStorage.setItem('renewalTab',this.activeTab.tabName)	
			const {href}=this.$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')
		},
	},
}
</script>

<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>