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

export default defineComponent({
	/* 页面进入前是否清除参数 */
  beforeRouteEnter(to, from, next) {
		if(from.path!='/customDetail') {
			sessionStorage.removeItem('newCustomBack')
		}
		next()
  },
});
</script>

<script setup>
import { ref,reactive } from "vue";
import {onBeforeRouteLeave,useRouter,useRoute} from "vue-router"
import { ElMessage } from 'element-plus'
import moment from 'moment'
import { InfoFilled } from '@element-plus/icons-vue'


import { dataMainInterface,customInterence} from '@/api/api.js';
import mPage from '@/components/mPage.vue';
import ModifyToDoDialog from '@/views/custom_manage/components/ModifyToDoDialog.vue'
import CheckToDoDialog from '@/views/custom_manage/components/CheckToDoDialog.vue'
import HistoryToDoDialog from '@/views/custom_manage/components/HistoryToDoDialog.vue'
import AccumulativeFrequencyDlg from '@/views/custom_manage/components/accumulativeFrequencyDlg.vue'
import { formatTime } from '@/utils/date'

const $router = useRouter()
const $route = useRoute()

const title=ref('')
const ids=ref('')//公司id
const tableData=ref([])
const 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'
	}
]
let sort_obj=reactive({
	param: '',
	type: '',
	SortByTodo:false,
})//排序字段
const isShowloadding=ref(false)
const total=ref(0)
const page_no=ref(1)
const pageSize=ref(0)
const todoBtnType=[
	{
		label:'新建',
		key:'add'
	},
	{
		label:'编辑',
		key:'edit'
	},
	{
		label:'完成',
		key:'confirm'
	},
	{
		label:'历史',
		key:'history'
	}
]//销售To-Do的按钮
const todoInfo=ref(null)//
const isModifyDialogShow=ref(false)//是否显示销售To-Do新建/编辑的弹窗
const ischeckToDoDialogShow=ref(false)//是否显示销售To-Do的确认完成弹窗
const isHistoryDialogShow=ref(false)//是否显示销售To-Do的历史记录弹窗
const modifyToDoType=ref('add')//新增or编辑
const accumulativeFrequencyDlg=ref(false)//路演业阅读的弹框
const accumulativeFrequencyItem=ref(null)
const trialTags=[ 
	{
		value:0
	},
	{
		label: '未分类',
		value: 1
	},
	{
		label: '推进',
		value: 2
	},
	{
		label: '跟踪',
		value: 3
	},
	{
		label: '预备',
		value: 4
	}
]// 试用的标签状态

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

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

/* 切换页码 */
const handleCurrentChange=(page)=> {
	page_no.value = page;
	getTableData();
}

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

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

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

//销售To-Do的按钮,根据每一行的信息决定显示哪些按钮,必须返回一个数组
const getToDoBtn=(row)=>{
	let todoBtn = []
	//该字段为true说明已有任务,隐藏新建按钮
	if(row.TodoStatus){
		todoBtn = todoBtnType.filter(i=>i.key!=='add')
	}else{
		todoBtn =  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颜色
const getTodoBtnColor=(colorName)=>{
	if(colorName==='red'){
		return '#D1433A'
	}else if(colorName==='green'){
		return '#61D13A'
	}else{
		return '#999999'
	}
}

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

//处理销售ToDo
//新建\编辑弹窗的确认事件
const handleModifyToDo=async({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){
			isModifyDialogShow.value=false
			ElMessage.success(`${type==='add'?'提交':'保存'}成功`);
			getTableData()
		}			
}
const handleApprove=({Id})=>{
	customInterence.checkToDo({Id}).then(res=>{
		if(res.Ret===200){
			ischeckToDoDialogShow.value=false
			ElMessage.success(`审核完成`);
			getTableData()
		}
	})
}
const accumulativeFrequencyClick=(item)=>{
	accumulativeFrequencyDlg.value = true
	accumulativeFrequencyItem.value = item
}

const init=()=>{
	if($route.query.ids) {
		ids.value = decodeURIComponent($route.query.ids);
		title.value = decodeURIComponent($route.query.title);
		let backData = {
					page_no: page_no.value,
					ids: ids.value,
					title: title.value,
				};
		localStorage.setItem("newCustomBack", JSON.stringify(backData));
	}

	if(sessionStorage.getItem('newCustomBack')) {
		let backParams = JSON.parse(sessionStorage.getItem('newCustomBack'));
		page_no.value = backParams.page_no;
		ids.value = backParams.ids;
		title.value = backParams.title;
	}else if(localStorage.getItem("newCustomBack")){
				let backParams = JSON.parse(localStorage.getItem("newCustomBack"));
				page_no.value = backParams.page_no;
				ids.value = backParams.ids;
				title.value = backParams.title;
		}
	ids.value && getTableData();
}

/* 页面跳转前记录参数 */
onBeforeRouteLeave((to, form, next) =>{
	let backData = {
		page_no: page_no.value,
		ids: ids.value,
		title: title.value
	}
	sessionStorage.setItem('newCustomBack',JSON.stringify(backData))
	localStorage.removeItem("newCustomBack");
	next()
})

init()

</script>

<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 #header>
					<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>
						</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任务的截止日期-当前日期">
								<el-icon :size="14" style="vertical-align: text-top;margin-left: 4px;"><InfoFilled /></el-icon>
							</el-tooltip>
						</div>	
						
					</template>
					<template v-else>
						<span>{{item.label}}</span>
					</template>
				</template>	
				<!-- tbody -->
				<template #default="{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">
							<template #content><p v-if="row.FiccView">FICC报告阅读次数：{{row.FiccView}}</p><p v-if="row.RaiView">权益报告阅读次数：{{row.RaiView}}</p></template>
							<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="row.Status=='流失'">
								创建时间：{{formatTime(row.CreatedTime)}}
							</template>
							<template v-else-if="row.Status == '永续'">
								永久
							</template>
							<template v-else-if="row.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 #default="{row}">
					<span :class="{'status-noallow':!row.IsShow}">
						{{moment(row.CreatedTime).format('YYYY.MM.DD')}}
					</span> 
				</template>
			</el-table-column>
			<template #empty>
				<div style="line-height: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>
			</template>
		</el-table>
		<div class="bottom">
			<m-page
				:total="total"
				:page_no="page_no"
				@handleCurrentChange="handleCurrentChange"
			/>
		</div>
		<!-- 销售To Do的弹窗 -->
		<Modify-to-do-dialog 
			:todoInfo="todoInfo" 
			:type="modifyToDoType"
			v-model:isModifyDialogShow="isModifyDialogShow"
			@modify="handleModifyToDo"
		></Modify-to-do-dialog>
		<check-to-do-dialog 
			:todoInfo="todoInfo" 
			v-model:ischeckToDoDialogShow="ischeckToDoDialogShow"
			@check="handleApprove"
		></check-to-do-dialog>
		<history-to-do-dialog :todoInfo="todoInfo" v-model:isHistoryDialogShow="isHistoryDialogShow"></history-to-do-dialog>
		<!-- 路演的弹窗 -->
		<accumulative-frequency-dlg v-model:accumulativeFrequencyDlg="accumulativeFrequencyDlg" v-model:accumulativeFrequencyItem="accumulativeFrequencyItem" />
	</div>
</template>

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