<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 { useRouter,useRoute} from 'vue-router';
import {onBeforeRouteLeave} from "vue-router"

import { dataMainInterface } from '@/api/api.js';
import mPage from '@/components/mPage.vue';
import CollectDetail from '../components/CollectDetail.vue';
import CollectList from '../components/CollectList.vue';
import {formatTime} from '@/hooks/mixins/index.js'

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

const title=ref('')
const ids=ref('')//公司id
const tableData=ref([])
const tableColumns=reactive([
	{
		label: '联系人',
		key: 'OldRealName',
		minwidthsty: '80px',
	},
	{
		label: '点击量',
		key: 'YbLogNum',
		minwidthsty: '100px',
	},
	{
		label: '客户名称',
		key: 'CompanyName',
		minwidthsty: '180px',
	},
	{
		label: '客户类型',
		key: 'CompanyType',
		widthsty: '80px',
	},
	{
		label: '所属行业',
		key: 'IndustryName',
	},
	{
		label: '客户地址',
		key: 'City',
		widthsty: '110px',
	},
	{
		label: '所属销售',
		key: 'SellerName',
	},
	{
		label: '客户状态',
		key: 'Status',
		// widthsty: '180px',
	},
	{
		label: '累计阅读次数',
		key: 'viewTotal',
	},
	{
		label: '累计路演次数',
		key: 'RoadShowTotal',
	},
	{
		label: '最近一次阅读时间',
		key: 'LastViewTime',
		widthsty: '200px',
	},
	{
		label: '服务期限',
		key: 'EndDate',
		minwidthsty: '180px',
	},
	{
		label: '到期天数',
		key: 'ExpireDay',
		widthsty: '110px'
	}
])
let sort_obj=reactive({
	param: '',
	type: ''
})//排序字段
const total=ref(0)
const page_no=ref(1)
const pageSize=ref(20)
// 产品ID
const productionId=ref(0)
// 产品类型
const ProductType=ref(0)
const CompanyStatus=ref('')
const StartDate=ref('')
const EndDate=ref('')
const isCollectDetailShow=ref(false)//研报 / 视频收藏统计 弹窗
const customItem=ref(null)
const isCollectListShow=ref(false)//图收藏统计弹窗

/* 获取数据	 */
const getTableData=()=>{
	const { param, type } = sort_obj;
	const collectMap = {
		999:'collectStatisticList',
		998:'chartStatisticList'
	}
	const InterfaceName = productionId.value>=998&&ProductType.value>=998?collectMap[productionId.value]:'newCustomProductionList'
	dataMainInterface[InterfaceName]({
		ProductId:productionId.value,
		ProductType:ProductType.value,
		StartDate:StartDate.value,
		StartDate:StartDate.value,
		EndDate:EndDate.value,
		CompanyStatus: CompanyStatus.value,
		CurrentIndex: page_no.value,
		SortParam: param,
		SortType: type,
		SellerIds: ids.value,
		PageSize:pageSize.value
	}).then(res => {
		const { Ret,Data } = res;
		if(Ret !== 200) return

		total.value = res.Data.Paging.Totals;
		tableData.value = Data.List || [];
	})
}

/* 切换页码 */
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',
		'YbLogNum':'ybUserLog',
		'CollectNum':'ybCollectLog'
	}

	sort_obj = {
		type: order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : '',
		param: typeMap[prop] || prop
	}
	getTableData();
}

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

/* 打开收藏详情弹窗 */
const showCollectDetail=(item)=>{
	customItem.value = item
	//如果是 研报 / 视频收藏统计
	if(productionId.value===999&&ProductType.value===999){
		isCollectDetailShow.value = true
	}
	//如果是 图收藏统计
	if(productionId.value===998&&ProductType.value===998){
		isCollectListShow.value = true
	}
}

const init=()=>{
	if($route.query.ids) {
		ids.value = decodeURIComponent($route.query.ids);	
	}
	title.value = decodeURIComponent($route.query.title);
	if($route.query.sort_obj){
		sort_obj = $route.query.sort_obj
	}
	productionId.value = parseInt($route.query.productionId) || 0
	ProductType.value = parseInt($route.query.ProductType) || 0
	if(productionId.value>=998&&ProductType.value>=998){
		//如果从收藏统计进入详情，将点击量列换成收藏量列
		const index = tableColumns.findIndex(item=>item.label==='点击量')
		tableColumns.splice(index,1,{
				label: '收藏量',
				key: 'CollectNum',
				minwidthsty: '100px',
			},)
	}
	
	// 客户状态 
	CompanyStatus.value = $route.query.CompanyStatus || ''
	// 开始日期
	StartDate.value = $route.query.StartDate || ''
	// 结束日期
	EndDate.value = $route.query.EndDate || ''
	if($route.query.ids||$route.query.title||$route.query.sort_obj){
		let backData = {
			page_no: page_no.value,
			ids: ids.value,
			title: title.value,
			sort_obj
		};
		localStorage.setItem("newCustomBack", JSON.stringify(backData));
	}
	if(sessionStorage.getItem('newCustomBack')) {
		let data = JSON.parse(sessionStorage.getItem('newCustomBack'));
		page_no.value = data.page_no;
		ids.value = data.ids;
		title.value = data.title;
		sort_obj = data.sort_obj
	}else if(localStorage.getItem("newCustomBack")){
		let data = JSON.parse(localStorage.getItem("newCustomBack"));
		page_no.value = data.page_no;
		ids.value = data.ids;
		title.value = data.title;
		sort_obj = data.sort_obj
	}
	ids.value && getTableData();
}

/* 页面跳转前记录参数 */
onBeforeRouteLeave((to, form, next) =>{
	let backData = {
		page_no: page_no.value,
		ids: ids.value,
		title: title.value,
		sort_obj
	}
	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
			class="table-cont"
		>
			<el-table-column
				v-for="item in tableColumns"
				:key="item.label"
				:label="item.label"
				:width="item.widthsty"
				:min-width="item.minwidthsty"
				:prop="item.key"
				align="center"
				:sortable="['YbLogNum','CollectNum','viewTotal','RoadShowTotal','LastViewTime','ExpireDay','createTime'].includes(item.key) ? 'custom' : false"
			>
				<template #default="{row}">

					<span v-if="item.key === 'CompanyName'" @click="goDetail(row)" class="customName editsty">
						{{row.CompanyName}}
					</span>

					<span v-else-if="item.key === 'CompanyType'">
						<span :style="row.IsSuspend===1?'color:#bbb':''">{{row.CompanyType}}</span> 
						<span v-if="row.FiccPackageType"  class="ficc-package">{{row.FiccPackageType == 1 ? '大套餐': '小套餐'}}</span>
					</span>

					<span v-else-if="item.key === 'City'">
						{{`${row.Province}/${row.City}`}}
					</span>

					<span v-else-if="item.key === 'Status'">
						{{row.Status}}
					</span>

					<span v-else-if="item.key === 'viewTotal'">
						{{row.AllViewTotal}}
					</span>

					<span v-else-if="item.key === 'LastViewTime'">
						{{
							row.FiccLastViewTime 
							? `ficc： ${row.FiccLastViewTime}` 
							:row.RaiLastViewTime?
							 `权益： ${row.RaiLastViewTime}`:'--'
						}}
					</span>

					<span v-else-if="item.key === 'EndDate'">
						<!-- 正常的时间显示 -->
						<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>

          <span v-else-if="item.key==='CollectNum'" @click="showCollectDetail(row)" class=" editsty">
            {{row.CollectNum}}
          </span>
					<span v-else>{{ row[item.key]}}</span>
				</template>
			</el-table-column>
			<el-table-column
				:prop="title.includes('正式') ? 'formalTime' : 'createTime'"
				:label="title.includes('正式') ? '转正时间' : '创建时间'"
				sortable="custom"
				align="center" 
				min-width="120"
			>
				<template #default="scope">
					<span>
						<template v-if="title.includes('正式')">
							{{formatTime(scope.row.FormalTime)}}
						</template>
						<template v-else>
							{{formatTime(scope.row.CreatedTime)}}
						</template>
					</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"
        :pageSize="pageSize"
				@handleCurrentChange="handleCurrentChange"
			/>
		</div>
    <!-- 研报/视频收藏统计 -->
    <collect-detail 
      :isCollectDetailShow="isCollectDetailShow"
      :customItem="customItem"
      :StartDate="StartDate"
      :EndDate="EndDate"
      :customStatus="$route.query.CompanyStatus"
      :SellerIds="$route.query.SellerIds"
      @cancel="isCollectDetailShow=false"
    />
    <!-- 图收藏统计 -->
    <collect-list 
      :isCollectListShow="isCollectListShow"
      :customItem="customItem"
      :StartDate="StartDate"
      :EndDate="EndDate"
      :customStatus="$route.query.CompanyStatus"
      :SellerIds="$route.query.SellerIds"
      @cancel="isCollectListShow=false"
    />
	</div>
</template>

<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;
	.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;
	}
	.bottom {
		height: 40px;
	}
}
</style>
