<template>
	<div class="list-container">
		<span class="tag">{{title}}</span>
		<el-table
			:data="tableData"
			@sort-change="sortChangeHandle"
			border
			v-loading="isShowloadding"
			class="table-cont"
		>
			<el-table-column
				v-for="item in tableColumns"
				:key="item.label"
				:label="item.label"
				:width="item.widthsty"
				:min-width="item.minwidthsty"
				:max-width="item.maxwidthsty"
				:prop="item.key"
				align="center"
				:sortable="['viewTotal','RoadShowTotal','LastViewTime','ExpireDay','createTime','Deadline'].includes(item.key) ? 'custom' : false"
			>
				<!-- thead -->
				<template slot="header"  slot-scope="{}">
					<template v-if="['todo','Deadline'].includes(item.key)">
						<div class="todolabel" :class="{sort:sort_obj.SortByTodo}" style="display:inline-block;" v-if="item.key==='todo'">
							<span>To-Do</span><!-- <img :src="todoSrc" style="margin-left:3px;width:22px;height:22px;padding:3px;"/> -->
						</div>
						<div class="todolabel" :class="{sort:sort_obj.param==='deadline'}" style="display:inline-block;" v-if="item.key==='Deadline'">
							<span>DL</span>
							<el-tooltip effect="dark" placement="top-start" content="未完成To Do任务的截止日期-当前日期">
								<i class="el-icon-info" />
							</el-tooltip>
							<!-- <img :src="todoSrc" style="margin-left: 3px;width: 22px;height: 22px;padding:3px;"/> -->	
						</div>	
						
					</template>
					<template v-else>
						<span>{{item.label}}</span>
					</template>
				</template>	
				<!-- tbody -->
				<template slot-scope="{row}">
					<span v-if="item.key === 'CompanyName'" @click="goDetail(row)" 
					class="customName editsty" :class="{'isShared':row.IsShared,'status-noallow':!row.IsShow}"
					:style="row.IsSuspend===1?'color:#bbb;':''"
					>
						{{row.CompanyName}}
					</span>

					<template v-else-if="item.key === 'CompanyType'">
						<template v-if="row.CompanyType.indexOf('/')!==-1">
							<span :style="row.IsSuspend===1?'color:#bbb;':''"
								  :class="{'status-noallow':!row.IsShow}"
							>{{row.CompanyType.split('/')[0]}}</span>
							<span v-if="row.FiccPackageType"  class="ficc-package">{{row.FiccPackageType == 1 ? '大套餐': '小套餐'}}</span>
							<br/>
							<span :style="row.IsSuspend===1?'color:#bbb':''"
								  :class="{'status-noallow':!row.IsShow}"
							>{{row.CompanyType.split('/')[1]}}</span>
						</template>
						<template v-else>
							<span :style="row.IsSuspend===1?'color:#bbb':''" :class="{'status-noallow':!row.IsShow}">{{row.CompanyType}}</span>
							<span v-if="row.FiccPackageType&&row.CompanyType.includes('ficc')"  class="ficc-package">{{row.FiccPackageType == 1 ? '大套餐': '小套餐'}}</span>
						</template>
					</template>
					
					<template v-else-if="item.key==='IndustryName'">
						<p :style="row.IsSuspend===1?'color:#bbb':''" :class="{'status-noallow':!row.IsShow}" v-for="item in row.IndustryName.split('/')" :key="item">{{item}}</p>
					</template>

					<template v-else-if="item.key==='SellerName'">
						<p :style="row.IsSuspend===1?'color:#bbb':''" :class="{'status-noallow':!row.IsShow}" v-for="item in row.SellerName.split('/')" :key="item">{{item}}</p>
					</template>

					<span v-else-if="item.key === 'City'" :class="{'status-noallow':!row.IsShow}">
						{{row.Province}}<br/>{{row.City}}
					</span>

					<template v-else-if="item.key === 'Status'">
						<p style="margin:3px 0;" :style="row.IsSuspend===1?'color:#bbb':''" :class="{'status-noallow':!row.IsShow}" v-for="(item,index) in row.Status.split('/')" :key="item">
							{{item}}
							<template v-if="item==='试用'">
								<span class="status-try">{{row.TryStageSlice[index]?trialTags[row.TryStageSlice[index].TryStage].label:trialTags[1].label}}</span>
							</template>
							
						</p>
					</template>

					<span v-else-if="item.key === 'viewTotal'">
						<el-tooltip :disabled="row.IsSuspend===1 || (row.FiccView+row.RaiView)===0||!row.IsShow">
								<div slot="content"><p v-if="row.FiccView">FICC报告阅读次数：{{row.FiccView}}</p><p v-if="row.RaiView">权益报告阅读次数：{{row.RaiView}}</p></div>
								<span :style="row.IsSuspend===1?'color:#bbb':'color:#409EFF;cursor:pointer;'" :class="{'status-noallow':!row.IsShow}">
									{{row.AllViewTotal}}
								</span>
							</el-tooltip>
					</span>

					<span v-else-if="item.key === 'LastViewTime'" :class="{'status-noallow':!row.IsShow}">
						{{
							row.FiccLastViewTime
							? `ficc： ${$moment(row.FiccLastViewTime).format('YYYY.MM.DD')}`
							: row.RaiLastViewTime
							? `权益： ${$moment(row.RaiLastViewTime).format('YYYY.MM.DD')}`
							: "--"
						}}
					</span>
					<span v-else-if="item.key==='RoadShowTotal'">	
						<span :style="row.IsSuspend===1?'color:#bbb':''" :class="{'status-noallow':!row.IsShow}" @click="accumulativeFrequencyClick(row)" class="editsty" v-if="row.RoadShowTotal > 0">{{row.RoadShowTotal}}</span>
						<span  :style="row.IsSuspend===1?'color:#bbb':''" :class="{'status-noallow':!row.IsShow}" v-else>{{row.RoadShowTotal}}</span>
					</span>

					<span v-else-if="item.key === 'EndDate'" :class="{'status-noallow':!row.IsShow}">
						<!-- 正常的时间显示 -->
						<template v-if="row.StartDate.indexOf('/')==-1">
							<template v-if="act_status=='流失'">
								创建时间：{{row.CreatedTime|formatTime}}
							</template>
							<template v-else-if="row.Status == '永续'">
								永久
							</template>
							<template v-else-if="act_status == '冻结'">
								{{row.FreezeStartDate}}~{{row.FreezeEndDate}}
							</template>
							<template v-else>
								{{row.StartDate}}~{{row.EndDate}}
							</template>
						</template>
						<!-- 公用客户的时间显示 -->
						<template v-else>
							{{row.StartDate.substr(0,10)}}~{{row.EndDate.substr(0,10)}}/{{row.StartDate.substr(11)}}~{{row.EndDate.substr(11)}}
						</template>
					</span>
					<div class="todo-btn" v-else-if="item.key==='todo'">
						<p class="hint" :style="`background-color:${getTodoBtnColor(row.TodoButtonColor)}`"></p>
						<div class="btnwrap">
							<span class="item" :class="{'status-noallow':!row.IsShow}"
							v-for="item in getToDoBtn(row)" 
							:key="item.key"
							:style="item.style"
							@click="!item.disable&&handleToDoBtnClick(row,item.key)"
							>{{item.label}}</span>
						</div>
					</div>
					<span v-else-if="item.key==='Deadline'" :class="{'status-noallow':!row.IsShow}">{{row[item.key]||'--'}}</span>
					<span :class="{'status-noallow':!row.IsShow}" v-else>{{ row[item.key]}}</span>
				</template>
			</el-table-column>
			<el-table-column
				:prop="'createTime'"
				:label=" '创建时间'"
				sortable="custom"
				align="center" 
				min-width="105"
			>
				<template slot-scope="{row}">
					<span :class="{'status-noallow':!row.IsShow}">
						{{$moment(row.CreatedTime).format('YYYY.MM.DD')}}
					</span> 
				</template>
			</el-table-column>
			<div slot="empty" style="lineHeight:44px;margin:60px 0;color:#999;">
				<img src="~@/assets/img/cus_m/nodata.png" alt="" style="display:block;width:160px;height:128px;margin: auto;">
				<span>暂无数据</span>
			</div>
		</el-table>
		<div class="bottom">
			<m-page
				:total="total"
				:page_no="page_no"
				@handleCurrentChange="handleCurrentChange"
			/>
		</div>
		<!-- 销售To Do的弹窗 -->
		<Modify-to-do-dialog 
			:todoInfo.sync="todoInfo" 
			:type="modifyToDoType"
			:isModifyDialogShow.sync="isModifyDialogShow"
			@modify="handleModifyToDo"
		></Modify-to-do-dialog>
		<check-to-do-dialog 
			:todoInfo.sync="todoInfo" 
			:ischeckToDoDialogShow.sync="ischeckToDoDialogShow"
			@check="handleApprove"
		></check-to-do-dialog>
		<history-to-do-dialog :todoInfo.sync="todoInfo" :isHistoryDialogShow.sync="isHistoryDialogShow"></history-to-do-dialog>
		<!-- 路演的弹窗 -->
		<accumulative-frequency-dlg :accumulativeFrequencyDlg.sync="accumulativeFrequencyDlg" :accumulativeFrequencyItem.sync="accumulativeFrequencyItem" />
	</div>
</template>

<script>
import { dataMainInterface,customInterence} from '@/api/api.js';
import mPage from '@/components/mPage.vue';
import ModifyToDoDialog from '@/views/custom_manage/compontents/ModifyToDoDialog.vue'
import CheckToDoDialog from '@/views/custom_manage/compontents/CheckToDoDialog.vue'
import HistoryToDoDialog from '@/views/custom_manage/compontents/HistoryToDoDialog.vue'
import AccumulativeFrequencyDlg from '@/views/custom_manage/compontents/accumulativeFrequencyDlg.vue'
export default {
	name: '',
	components: { mPage,ModifyToDoDialog,CheckToDoDialog,HistoryToDoDialog,AccumulativeFrequencyDlg },
	data() {
		return {
			title: '',
			ids:'',//公司id
			tableData:[],
			tableColumns:[
				{
					label: '客户名称',
					key: 'CompanyName',
					minwidthsty: '150px',
				},
				{
					label:'TO-DO',
					key:'todo',
					minwidthsty: '100px',
					maxwidthsty: '130px'
				},
				{
          			label: "DL",
          			key: "Deadline",
          			minwidthsty: "100px",
					maxwidthsty: '130px'
        		},
				{
					label: '类型',
					key: 'CompanyType',
					widthsty: '80px',
				},
				{
					label: '所属行业',
					key: 'IndustryName',
					widthsty: '110px',
				},
				{
					label: '客户地址',
					key: 'City',
					widthsty: '110px',
				},
				{
					label: '销售',
					key: 'SellerName',
					widthsty: '110px',
				},
				{
					label: '状态',
					key: 'Status',
					widthsty: '110px',
				},
				{
					label: '阅读',
					key: 'viewTotal',
					widthsty: '110px',
				},
				{
					label: '路演',
					key: 'RoadShowTotal',
					widthsty: '110px',
				},
				{
					label: '最近阅读',
					key: 'LastViewTime',
					widthsty: '160px',
				},
				{
					label: '服务期限',
					key: 'EndDate',
					minwidthsty: '100px',
				},
				{
					label: '到期',
					key: 'ExpireDay',
					widthsty: '105px'
				}
			],
			sort_obj: {
				param: '',
				type: '',
				SortByTodo:false,
			},//排序字段
			isShowloadding:false,
			total: 0,
			page_no: 1,
			pageSize: 10,
			todoSrc:require('@/assets/img/icons/todo2.png'),
			todoBtnType:[
				{
					label:'新建',
					key:'add'
				},
				{
					label:'编辑',
					key:'edit'
				},
				{
					label:'完成',
					key:'confirm'
				},
				{
					label:'历史',
					key:'history'
				}
			],//销售To-Do的按钮
			todoInfo:null,//
			isModifyDialogShow:false,//是否显示销售To-Do新建/编辑的弹窗
			ischeckToDoDialogShow:false,//是否显示销售To-Do的确认完成弹窗
			isHistoryDialogShow:false,//是否显示销售To-Do的历史记录弹窗
			modifyToDoType:'add',//新增or编辑
			accumulativeFrequencyDlg:false,//路演业阅读的弹框
			trialTags:[ 
				{
					value:0
				},
				{
					label: '未分类',
					value: 1
				},
				{
					label: '推进',
					value: 2
				},
				{
					label: '跟踪',
					value: 3
				},
				{
					label: '预备',
					value: 4
				}
			],// 试用的标签状态
		}
	},
	methods: {

		/* 获取数据	 */
		getTableData() {
			this.isShowloadding = true;
			const { param, type,SortByTodo } = this.sort_obj;

			dataMainInterface.newcustomList({
				PageSize: this.pageSize,
				CurrentIndex: this.page_no,
				SortParam: param,
				SortType: type,
				SortByTodo:SortByTodo,
				CompanyIds: this.ids
			}).then(res => {
				const { Ret,Data } = res;
				if(Ret !== 200) return
				
				this.total = res.Data.Paging.Totals;
				this.tableData = Data.List || [];
				this.isShowloadding = false;
			})
		},

		/* 切换页码 */
		handleCurrentChange(page) {
			this.page_no = page;
			this.getTableData();
		},

		/* 排序变化时 */
		sortChangeHandle({ prop,order }) {
			console.log(prop,order)
			this.page_no = 1;

			const typeMap = {
				'RoadShowTotal': 'roadShowTotal',
				'LastViewTime': 'viewTime',
				'ExpireDay': 'expireDay',
				'Deadline': "deadline",
			}
			if(prop==='todo'){
				const {SortByTodo} = this.sort_obj
				this.sort_obj={
					type:'',
					param:'',
					SortByTodo:!SortByTodo
				}
			}else if (prop === "Deadline") {
				const { param } = this.sort_obj;
				this.sort_obj = {
					type: param === typeMap[prop] ? "" : "asc",
					param: param === typeMap[prop] ? "" : typeMap[prop],
					SortByTodo:false,
				};
			}else{
				this.sort_obj = {
					type: order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : '',
					param: typeMap[prop] || prop,
					SortByTodo:false
				}	
			}
			
			this.getTableData();
		},

		/* 前往详情页 */
		goDetail({CompanyId}) {
			this.$router.push({
				path:'/customDetail',
				query:{
					id: CompanyId,
				}
			})
		},

		//销售To-Do的按钮,根据每一行的信息决定显示哪些按钮,必须返回一个数组
		getToDoBtn(row){
			let todoBtn = []
			//该字段为true说明已有任务,隐藏新建按钮
			if(row.TodoStatus){
				todoBtn = this.todoBtnType.filter(i=>i.key!=='add')
			}else{
				todoBtn =  this.todoBtnType.filter(i=>i.key!=='edit')
			}
			todoBtn = todoBtn.filter(i=>i.key!=='confirm')
			//该字段为false说明操作人有权限审核,显示确认完成按钮
			if(!row.HiddenConfirm){	
				let temp = {label:'完成',key:'confirm'}
				if(row.CanConfirm){
					temp.disable=false
					temp.style=''
				}else{
					temp.disable=true
					temp.style='color:#DCDFE6;'
				}
				todoBtn.splice(1,todoBtn.length-2,temp)
			}
			if(row.HiddenCreate){
				todoBtn.shift()
			}
			return todoBtn
		},

		//销售To-Do的hint颜色
		getTodoBtnColor(colorName){
			if(colorName==='red'){
				return '#D1433A'
			}else if(colorName==='green'){
				return '#61D13A'
			}else{
				return '#999999'
			}
		},

		//销售To-Do的点击事件
		handleToDoBtnClick(row,type){
			this.todoInfo = row
			//打开新建/编辑弹窗
			if(['add','edit'].includes(type)){
				this.modifyToDoType = type
				this.isModifyDialogShow = true
				this.ischeckToDoDialogShow = false
				this.isHistoryDialogShow=false
			}
			//打开审核记录弹窗
			if(type==='confirm'){
				this.ischeckToDoDialogShow=true
				this.isModifyDialogShow=false
				this.isHistoryDialogShow=false
			}
			//打开历史记录弹窗
			if(type==='history'){
				this.isHistoryDialogShow=true
				this.isModifyDialogShow=false
				this.ischeckToDoDialogShow=false
			}
		},

		//处理销售ToDo
		//新建\编辑弹窗的确认事件
		async handleModifyToDo({type,Description,ProductId,CompanyId,Id,EndTime}){
			//console.log(type,Description,ProductId,CompanyId)
			let res
			if(type==='add'){
				res = await customInterence.addToDoItem({Description,ProductId,CompanyId,EndTime})
			}else{
				res = await customInterence.editToDoItem({Description,Id})
			}
			if(res.Ret===200){
					this.isModifyDialogShow=false
					this.$message.success(`${type==='add'?'提交':'保存'}成功`);
					this.getTableData()
				}			
		},
		handleApprove({Id}){
			customInterence.checkToDo({Id}).then(res=>{
				if(res.Ret===200){
					this.ischeckToDoDialogShow=false
					this.$message.success(`审核完成`);
					this.getTableData()
				}
			})
		},
		accumulativeFrequencyClick(item){
			this.accumulativeFrequencyDlg = true
			this.accumulativeFrequencyItem = item
		},

	},
	/* 页面跳转前记录参数 */
	beforeRouteLeave(to, form, next) {
		let backData = {
			page_no: this.page_no,
			ids: this.ids,
			title: this.title
		}
		sessionStorage.setItem('newCustomBack',JSON.stringify(backData))
		localStorage.removeItem("newCustomBack");
		next()
	},
	/* 页面进入前是否清除参数 */
	beforeRouteEnter(to,from,next) {
		if(from.path!='/customDetail') {
			sessionStorage.removeItem('newCustomBack')
		}
		next()
	},
	mounted() {
		if(this.$route.query.ids) {
			this.ids = decodeURIComponent(this.$route.query.ids);
			this.title = decodeURIComponent(this.$route.query.title);
			let backData = {
        		page_no: this.page_no,
        		ids: this.ids,
        		title: this.title,
      		};
			localStorage.setItem("newCustomBack", JSON.stringify(backData));
		}

		if(sessionStorage.getItem('newCustomBack')) {
			let { page_no,ids,title  } = JSON.parse(sessionStorage.getItem('newCustomBack'));
			this.page_no = page_no;
			this.ids = ids;
			this.title = title;
		}else if(localStorage.getItem("newCustomBack")){
      		let { page_no, ids, title } = JSON.parse(
        	localStorage.getItem("newCustomBack")
      	);
      		this.page_no = page_no;
      		this.ids = ids;
      		this.title = title;
    	}
		this.ids && this.getTableData();
	},
}
</script>
<style lang="scss">
.todolabel{
	&+span.caret-wrapper{
		.sort-caret.ascending{
			border-bottom-color: #C0C4CC;
		}
		.sort-caret.descending{
			border-top-color: #C0C4CC
		}
	}
}
.todolabel.sort{
	&+span.caret-wrapper{
		.sort-caret.ascending{
			border-bottom-color: #409EFF;
		}
	}
}
</style>
<style lang="scss" scoped>
*{ box-sizing: border-box; }
.list-container {
	min-height: calc(100vh - 120px);
	background-color: #fff;
	box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
	border-radius: 4px;
	padding: 30px 20px;
	.isShared::after{
		content: '共享';
		font-size: 12px;
		// padding: 0px 0px 0px 2px;
		width: 40px;
		color: #3994fb;
		background-color: #dcecfc;
		position: absolute;
		left: 0;
		bottom: 0;
		border-top-right-radius: 5px;
	}
	.ficc-package {
		display: inline-block;
		font-size: 12px;
		padding:0 5px;
		border-radius: 5px;
		color: #3994fb;
		background-color: #dcecfc;
	}
	.status-noallow{
		cursor: not-allowed !important;
		color: #bbb !important;
		pointer-events:none !important;
	}
	.status-try{
		display: inline-block;
		background-color: #ECF5FF;
		border-radius: 4px;
		color:#409EFF;
		border: 1px solid #E4E7ED;
		height: 24px;
		line-height: 24px;
		text-align: center;
		padding:0 6px;
	}
	.tag {
		padding: 10px 24px;
		display: inline-block;
		background: #E8F3FF;
		color: #2D8CF0;
		font-size: 14px;
		border-radius: 4px;
	}
	.table-cont {
		margin-top: 20px;
		margin-bottom: 20px;
	}
	.todo-btn{
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 10px;
		.hint{
			width: 8px;
			height: 8px;
			background-color: #D1433A;
			border-radius: 50%;
			margin-right: 10px;
		}
		.btnwrap{
			display: flex;
			align-content: space-around;
			flex-direction: column;
			justify-content: space-between;
			span.item{
				margin-right: 10px;
				font-size: 14px;
				color:#409EFF;
				cursor: pointer;
				&:last-child{
					margin-right: none;
				}
			}
		}
		
		
	}
	.bottom {
		height: 40px;
	}
}
</style>
