<template>
	<div class="statistic-container">
		<!-- <div class="frequency-cont"> -->
			<ul class="custom-tab-box" v-if="Role==='admin'">
				<li v-for="tab in productionTabs" :key="tab.key" class="custom-tab" :class="{activeTab: tab.label=== default_productionTab}" @click="changeProdTabHandle(tab)">{{ tab.label }}</li>
			</ul>
		<!-- </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="select_date"
			type="date" 
			range
			value-type="format"
			:clearable="false"
			@change="dateChange"
			placeholder="请选择统计时间"/>
    </div>
		<div class="table-cont" v-show="dataLoading">
			<!-- <table>
				<thead>
					<tr>
						<td rowspan="2" class="thead-rs" v-if="Role.includes('admin')">
							<div class="thead-rs-div">组别</div>
						</td>
						<td rowspan="2" class="thead-rs">
							<div class="thead-rs-div">销售</div>
						</td>
						<td rowspan="2" class="thead-rs">
							<div class="thead-rs-finish">
								未完成
								<el-tooltip 
									effect="dark" 
									placement="top-start"
									content="截止日期小于等于今天的未完成To Do任务统计"
								>
									<i class="el-icon-info"/>
								</el-tooltip>
							</div>	
						</td>
						<td rowspan="2" class="thead-rs">
							<div class="thead-rs-finish">
								进行中
								<el-tooltip 
									effect="dark" 
									placement="top-start"
									content="进行中且未到截止日期的To Do任务统计"
								>
									<i class="el-icon-info"/>
								</el-tooltip>
							</div>	
						</td>
						<td rowspan="2" class="thead-rs">
							<div class="thead-rs-finish">
								累计完成
								<el-tooltip 
									effect="dark" 
									placement="top-start"
									content="该销售累计完成To Do任务数量"
								>
									<i class="el-icon-info"/>
								</el-tooltip>
							</div>	
						</td>
						<td
							:colspan="2"
							v-for="(_,index) in WeekNum"
							:key="index" 
							class="head-column"
						>
							{{tableTheadColumns[index]}}<br/>({{weekTime[index]}})
						</td>
					</tr>
					<tr>
						<template v-for="(item,index) in new Array(WeekNum).fill('')">
							<td :key="index+'_0'">
								<div style="width:80px;display:inline-block;">
									新建To Do
								</div>
							</td>
							<td :key="index+'_1'">
								<div style="width:80px;display:inline-block;">
									完成To Do
								</div>
							</td>
						</template>
					</tr>
				</thead>
			</table>	 -->
			<div class="table-body-wrapper">
				<table v-if="this.tbodyShow" >
					<thead>
						<tr>
							<td rowspan="2" class="thead-rs" v-if="Role.includes('admin')">
								<div class="thead-rs-div">组别</div>
							</td>
							<td rowspan="2" class="thead-rs">
								<div class="thead-rs-div">销售</div>
							</td>
							<td rowspan="2" class="thead-rs">
								<div class="thead-rs-finish">
									未完成
									<el-tooltip 
										effect="dark" 
										placement="top-start"
										content="截止日期小于等于今天的未完成To Do任务统计"
									>
										<i class="el-icon-info"/>
									</el-tooltip>
								</div>	
							</td>
							<td rowspan="2" class="thead-rs">
								<div class="thead-rs-finish">
									进行中
									<el-tooltip 
										effect="dark" 
										placement="top-start"
										content="进行中且未到截止日期的To Do任务统计"
									>
										<i class="el-icon-info"/>
									</el-tooltip>
								</div>	
							</td>
							<td rowspan="2" class="thead-rs">
								<div class="thead-rs-finish">
									累计完成
									<el-tooltip 
										effect="dark" 
										placement="top-start"
										content="该销售累计完成To Do任务数量"
									>
										<i class="el-icon-info"/>
									</el-tooltip>
								</div>	
							</td>
							<td
								:colspan="['周度统计表','月度统计表'].includes(default_tab) ? 2 : 1"
								v-for="item in contractTableThead"
								: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+'_0'">
									<div style="display:inline-block;">
										新建To Do
									</div>
								</td>
								<td :key="index+'_1'">
									<div style="display:inline-block;">
										完成To Do
									</div>
								</td>
							</template>
						</tr>
					</thead>
					<tbody v-for="item in datalist" :key="item.Name">
							<tr v-if="Role.includes('admin')">
								<td colspan="2" @click="item.showDetail=!item.showDetail">{{item.Name}}合计<i v-if="item.Item.length" :class="item.showDetail?'el-icon-arrow-up':'el-icon-arrow-down'"></i></td>
								<td>{{item.DoingExpiredGroupNum}}</td>
								<td>{{item.DoingNum}}</td>
								<td>{{item.FinishNum}}</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">
								<!-- List[0] -->
								<tr v-if="Role.includes('admin')" v-show="item.showDetail">
									<td :rowspan="item.Item.length+1" class="thead-rs">
										<div class="thead-rs-div">{{item.Name}}</div>
									</td>
								</tr>
								<!-- List[0].Item[0] -->
								<tr v-for="rs in item.Item" :key="rs.AdminId" v-show="item.showDetail">
									<td class="thead-rs" :class="[{link: item.Item.length}]">
										<!-- {{rs.Name}} -->
										<div class="thead-rs-div" @click="goList2('name',rs)" style="cursor:pointer;">{{rs.Name}}</div>
									</td>
									<!-- 未完成列 -->
									<td class="thead-rs" 
										:style="rs.DoingExpiredNum?'cursor: pointer':''"
										:class="[{link: item.Item.length&&rs.DoingExpiredNum>0}]" @click="goList2('num',rs)">
										<div class="thead-rs-finish">{{rs.DoingExpiredNum}}</div>
									</td>
									<!-- 进行中列 -->
									<td class="thead-rs" 
										:style="rs.DoingNum?'cursor: pointer':''"
										:class="[{link: item.Item.length&&rs.DoingNum>0}]" @click="goList2('doingNum',rs)">
										<div class="thead-rs-finish">{{rs.DoingNum}}</div>
									</td>
									<!-- 累计完成列 -->
									<td class="thead-rs" >
										<div class="thead-rs-finish">{{rs.FinishNum}}</div>
									</td>
									<td 
										:class="['data-cell',{link: item.Item.length}]" 
										v-for="(data,data_key) in rs.dataArr" 
										:key="data_key"
									>
										
										<span 
											style="display:inline-block;"
											@click="goList(data,data_key,item.Item)" 
											v-if="Object.prototype.toString.call(data.value) === '[object Number]'"
										>
											{{ data.value !== 0 ? data.value : '' }}
										</span>

										<span 
											style="display:inline-block;"
											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 v-if="Role.includes('admin')">
							<td colspan="2">{{this.ProductId===1?'ficc':'权益'}}总合计</td>
							<td>{{DoingExpiredAllNum}}</td>
							<td>{{DoingAllNum}}</td>
							<td>{{FinishAllNum}}</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 style="lineHeight:44px;margin:60px 0;color:#999;text-align:center;" v-else>
					<img src="~@/assets/img/cus_m/nodata.png" alt="" style="display:block;width:160px;height:128px;margin: auto;">
					<span>暂无数据</span>
				</div>
			</div>	
		</div>
	</div>
</template>

<script>
import { dataMainInterface } from '@/api/api.js';
import mixin from './mixin';
export default {
	name:'',
	mixins: [ mixin ],
	data () {
		return {
			// tableTheadColumns: ['本周','上一周','上两周','上三周','上四周','上五周','上六周'],
			productionTabs:[
				{
					label:'FICC',
					key:1
				},{
					label:'权益',
					key:2
				}
			],
			default_productionTab:'FICC',
			activeTab:1,
			weekTime:[this.getWeekOrMonthDate(0),this.getWeekOrMonthDate(1),this.getWeekOrMonthDate(2),this.getWeekOrMonthDate(3),this.getWeekOrMonthDate(4),this.getWeekOrMonthDate(5),this.getWeekOrMonthDate(6),this.getWeekOrMonthDate(7)],
			tbodyShow:false,
			DoingExpiredAllNum:0,
			DoingAllNum:0, //进行中的总合计数量
			FinishAllNum:0
		};
	},
	computed:{
		/* Role() {
      		return localStorage.getItem("Role");
    	}, */
		ProductId(){
			if(['admin'].includes(this.Role)){
				if(localStorage.getItem("todoStatisicSection")){
					this.activeTab = Number(localStorage.getItem("todoStatisicSection"))
					this.default_productionTab=this.productionTabs[this.activeTab-1].label
					localStorage.removeItem("todoStatisicSection")
				}
				return this.activeTab
			}else if(this.Role.includes('ficc')){
				return 1
			}else if(this.Role.includes('rai')){
				return 2
			}
		},
		contractTableThead:function(){
      if(['周度统计表','月度统计表'].includes(this.default_tab)){
        return this.tableTheadColumns
      }
      return  ['新建To Do','完成To Do']
    }
		//显示数据的周数,管理员6周,组长7周 crm_8.2
		//显示的周数 组长和管理员也改为6周 crm_11.1
		// WeekNum(){
		// 	if(this.Role.includes('admin')){
		// 		return 6
		// 	}else{
		// 		return 7
		// 	}
		// }
	},
	methods: {

		/* 获取表格数据 */
		getTableData() {
			this.dataLoading = false;
			dataMainInterface.todoStatistic({
				DataType: this.default_tab === '周度统计表' ? 'week' : this.default_tab === '月度统计表' ? 'month' : 'time_interval',
				ProductId:this.ProductId,
				StartDate: this.select_date ? this.select_date[0] : '',
				EndDate: this.select_date ? this.select_date[1] : '',
			}).then(res => {
				const { Data,Ret } = res;
				if(Ret !== 200) return
				//如果没有数据
				if(!Data.CompanyTodoReportRecordNumList.length){
					this.tbodyShow = false
				}else{
					this.tbodyShow = true
				}
				//总合计数据处理
				this.totalGroupArr = this.filterTableData(Data.CompanyTodoReportRecordNumList);
				this.DoingExpiredAllNum = Data.DoingExpiredAllNum
				this.DoingAllNum = Data.DoingAllNum
				this.FinishAllNum = Data.FinishAllNum
				//处理数据结构
				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 => {
          if(this.Role.includes('admin')){
           item.showDetail=false 
          }else{
            item.showDetail=true
          }
					
					let groupDataArr = this.filterTableData(item.CompanyTodoReportRecordNumList,{
						rs_name: item.Name + '合计'
					});
					this.$set(item,'subGroupArr',groupDataArr)
					
					item.Item && item.Item.forEach(sub_item => {
						let dataArr = this.filterTableData(sub_item.CompanyTodoReportRecordNumList ,{
							rs_name : sub_item.Name,

						})

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

				this.datalist = data;
				this.$nextTick(() => {
					this.dataLoading = true;
				})
			})
		},

		/* 进入列表 */
		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 = this.getColumnTitle(index);

			let title =  encodeURIComponent(`${column_title}/${rs_name}/${key}`);

			//console.log(`${column_title}/${rs_name}/${key}`)
			//console.log('sub_index',sub_index,'ids',ids)
			if(['admin'].includes(this.Role)){
				localStorage.setItem('todoStatisicSection',this.activeTab)
			}
			const {href}=this.$router.resolve({
				name: '客户任务列表',
				query: {
					ids: sub_index !== '' ? encodeURIComponent(ids[sub_index]) : encodeURIComponent(ids),
					title
				}
			})
			window.open(href,'_blank')
		},
		/* 点击销售员/未完成/进行中 进入列表 */
		goList2(type,data){
			let routerINS=null
			if(['admin'].includes(this.Role)){
				localStorage.setItem('todoStatisicSection',this.activeTab)
			}
			if(type==='name'){
				routerINS=this.$router.resolve({
					name: '客户列表',
					query: {
						adminId:data.AdminId
					}
				})
				window.open(routerINS.href,'_blank')
			}else if(type === 'num'){
				if(data.DoingExpiredNum===0) return
				routerINS=this.$router.resolve({
					name: '未完成任务列表',
					query: {
						ids: data.DoingExpiredCompanyIds,
						title:`${data.Name}/未完成`
					}
				})
				window.open(routerINS.href,'_blank')
			}else{
				console.log(type,data);
				if(data.DoingNum===0) return
				routerINS=this.$router.resolve({
					name: '进行中任务列表',
					query: {
						ids: data.DoingCompanyIds,
						title:`${data.Name}/进行中`
					}
				})
				window.open(routerINS.href,'_blank')
			}

			

		},

		// /* 获取数据对应表头 */
		// getColumnTitle(index) {
		// 	let title = '';
		// 	let currentIndex = parseInt(index/2)
		// 	console.log('index',index,'current',currentIndex)
		// 	title = `${this.tableTheadColumns[currentIndex]} (${this.weekTime[currentIndex]}) `
		// 	return title
		// },
    /* 获取数据对应表头 */
		getColumnTitle(index) {
			let title = '';

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

		//重写一下这个方法
		filterTableData(data,other_param={}){
			let list = data.map(item => ([
				{
					key: '新建To Do',
					value: item.AddMap,
					ids: item.AddIdMap,
					...other_param
				},
				{
					key: '完成To Do',
					value: item.ApproveMap,
					ids: item.ApproveIdMap,
					...other_param
				},
				/* {
					key: '上周/新建To Do',
					value: item.FormalAddMap,
					ids: item.FormalAddIdMap,
					...other_param
				},
				{
					key: '上周/完成To Do',
					value: item.FormalApproveMap,
					ids: item.FormalApproveIdMap,
					...other_param
				}, */
			]))
			
			return list.flat(Infinity);
		}

	},
	mounted() {
		this.getTableData();
	},
}
</script>
<style lang='scss' scoped>
*{ box-sizing: border-box;}
@import './index.scss';
.table-body-wrapper{
	/* width: max-content; */
	/* overflow-x: hidden; */
	max-height: calc(100vh - 310px) !important;
	// margin-right: -6px !important;
}
//保证小屏时td的宽度
.table-cont{
	// width: 100%;
	// overflow-x: scroll;
	// .thead-rs{
	// 	&-div{
	// 		width:100px;
	// 		display:inline-block;
	// 	}
	// 	&-finish{
	// 		width:90px;
	// 		display:inline-block;
	// 	}
		
	// }
	/* .data-cell{
		span{
			width:80px !important;
			display: inline-block;
		}
	} */
}
</style>