<template>
	<div class="dataReport-container">
		<div class="dataReport-main first">
			<div class="main-top" style="display:flex;align-items: center;">
				<a :href="exportExcel" download>
					<el-button type="primary" style="marginRight:10px;marginBottom:8px;">导出EXCEL</el-button>
				</a>
				<!-- <el-select 
				v-model="filterObj.sale" 
				placeholder="请选择销售" 
				style="width:150px;marginRight:10px;marginBottom:8px;" 
				v-if="Role=='admin'||Role=='ficc_admin'||Role=='rai_admin'||ManageType!=0" 
				clearable  
				@change="changeFilter" 
				filterable>
					<el-option
						v-for="item in salesArr"
						:key="item"
						:label="item.RealName"
						:value="item.AdminId">
					</el-option>
				</el-select> -->
				<el-cascader
					v-if="Role=='finance'||Role=='admin'||Role=='ficc_admin'||Role=='rai_admin'||ManageType!=0"
					v-model="filterObj.sale"
					placeholder="请选择销售"
					style="min-width:250px;marginRight:10px;marginBottom:8px;"
					:options="salesArr"
					:props="defaultSalesProps"
					:show-all-levels="false"
					collapse-tags
					clearable
					filterable
					@change="changeFilter">
				</el-cascader>

				<el-select 
				v-model="filterObj.type" 
				placeholder="请选择客户类型" 
				style="width:150px;marginRight:10px;marginBottom:8px;" 
				v-if="Role=='finance'||Role=='admin'"
				clearable
				@change="changeFilter">
					<el-option
						v-for="item in typeArr"
						:key="item"
						:label="item.name"
						:value="item.name">
					</el-option>
				</el-select>
				<el-select 
				v-model="filterObj.area" 
				placeholder="请选择所属区域" 
				style="width:150px;marginRight:10px;marginBottom:8px;" 
				clearable
				@change="changeFilter">
					<el-option
						v-for="item in areaArr"
						:key="item"
						:label="item"
						:value="item">
					</el-option>
				</el-select>
				<date-picker
				style="marginBottom:8px;"
				v-model="filterObj.date" 
				type="date" 
				value-type="format"
				placeholder="请选择日期"
				:clearable="false"
				:editable="false"
				@change="changeFilter"/>
				<el-input
				placeholder="请输入客户名称"
				v-model="searchVal"
				style="maxWidth:400px;margin-left:auto;marginBottom:8px;"
				@input="handleSearch"
				clearable>
					<i slot="prefix" class="el-input__icon el-icon-search"></i>
				</el-input>
			</div>
			<div class="main-section">
				<el-row :gutter="36">
					<el-col 
					:span="8" 
					v-for="item in data_typeArr"
					:key="item.label"
					>
						<el-card 
						:class="['base-card',{'main-card':filterObj.data_type===item.label}]" shadow="hover"
						@click.native="toggleType(item.label)">
							<div slot="header" class="clearfix">
								<span>
									{{item.label}}数
									<el-tooltip
									class="item" 
									effect="dark"
									:content="item.label === '新签客户' 
									? '当前为正式状态，且处于新签合同存续期内的客户'
									: item.label === '续约客户'
									? '当前为正式状态，且处于续约合同存续期内的非新签客户（在新签合同和续约合同的重叠存续期内，该客户仍定义为新签客户）'	
									: '历史上有过正式转试用记录，且查询时间点为非正式、非永续状态的客户'" 
									placement="top">
										<i class="el-icon-info"></i>
									</el-tooltip>
								</span>
							</div>
							<div class="card-cont">
								{{
									item.label === '新签客户' 
									? NewCompanyTotal
									: item.label === '续约客户' 
									? RenewalCompanyTotal
									: item.label === '未续约客户' 
									? NotRenewalCompanyTotal
									:""
								}}
							</div>
						</el-card>
					</el-col>	
				</el-row>
			</div>
			<el-select v-model="noRenewalReasonId" placeholder="请选择不续约归因" v-show="filterObj.data_type=='未续约客户'"
			clearable @change="getTableData" style="width: 240px;margin-top: 40px;">
				<el-option :label="item.AscribeContent" :value="item.CompanyAscribeId"
				v-for="item in noRenewalReasonList" :key="item.reasonId"></el-option>
			</el-select>
			<div class="tabs-box" v-if="filterObj.data_type=='未续约客户'">
				<span @click="tabsHandler(item)" :class="tabsActiveName===item.value ? 'active':''" v-for="item in tabsList" :key="item">{{item.name}}({{item.name==='试用'?NotRenewalTryOut:NotRenewalNotTryOut}})</span>
			</div>
			<el-table
				:data="tableData"
				border
				v-loading="isShowloadding"
				element-loading-text="数据加载中..."
				style="margin-top: 20px;min-height:400px"
			>
			<template v-for="item in stockTableColums">
				<el-table-column 
				:key="item.label"
				:label="item.label"
				:width="item.widthsty"
				align="center"
				v-if="!item.dataType || item.dataType.split(',').includes(filterObj.data_type)">
					<template slot-scope="scope">
						<span 
							:style="item.textsty" 
							@click="jumpHandle(scope.row,item)"
							v-if="item.label=='服务期限'||item.label=='最近合同到期时间'">
							{{
								item.label=='服务期限'&&scope.row.StartDate.indexOf('/')==-1
								? scope.row.StartDate+'~'+scope.row.EndDate 
								:item.label=='服务期限'&&scope.row.StartDate.indexOf('/')!=-1
								?scope.row.StartDate.substr(0,10)+'~'+scope.row.EndDate.substr(0,10)+'/'+scope.row.StartDate.substr(11)+'~'+scope.row.EndDate.substr(11)
								:scope.row[item.key] |formatTime
							}}
						</span>
						<span v-else-if="item.label=='未续约说明'">
							<span style="display:block" v-if="scope.row[item.key]">最新情况：{{scope.row[item.key]}}</span>
							<span v-if="scope.row.RenewalTodo">To Do 事项：{{scope.row.RenewalTodo}}</span>
							<span v-if="scope.row[item.key]||scope.row.RenewalTodo" style="color:#409EFF;cursor:pointer;" @click="renewalReasonMore(scope.row)">&emsp;更多>></span>
						</span>
						<div v-else-if="item.key=='CompanyName'" style="padding:4px 0">
							<span 
								:style="item.textsty" 
								@click="jumpHandle(scope.row,item)" >
								{{
									scope.row[item.key]
								}}
							</span>
							<div class="package-difference" v-if="scope.row.PackageDifference">
								{{scope.row.PackageDifference}}
							</div>
						</div>
						<div v-else-if="item.key==='Remark' " class="remark-row">
							<span class="remark-text" @click="viewHistoryRemarkFun(scope.row)" v-if="scope.row.IsShowNoRenewedNote">...</span>
						</div>
						<div v-else-if="item.key=='AscribeContent'">
							<span style="color: #409EFF;cursor: pointer;"
								@click="editReasonLabel(scope.row)" >
								{{scope.row[item.key]}}
							</span>
						</div>
						<span 
							v-else
							:style="item.textsty" 
							@click="jumpHandle(scope.row,item)">
								{{scope.row[item.key]}}
							</span>
					</template>
				</el-table-column>
			</template>
				<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>
			<el-col :span="24" class="toolbar" v-if="total">
				<m-page
				:total="total"
				:page_no="page_no"
				@handleCurrentChange="handleCurrentChange"/>
			</el-col>
		</div>
		<!-- 未续约说明列表弹窗 -->
		<renewalListDia :isShow.sync="isRenewalShow" :rowInfo="rowInfo"/>
		<!-- 历史备注弹窗 -->
		<viewRemark :isShow.sync="isViewRemarkShow" :tableData="historyRemarkList" />
		<!-- 确认不续约弹窗 -->
		<confirmedNoRenewal :isShow.sync="isConfirmNoRenewalShow" :dataForm="confirmNoRenewalForm" 
			:noRenewalReasonList="noRenewalReasonList" @refreshReasonList="getNORenewalReasonList" @saveLabel="saveLabel" />
	</div>
</template>

<script>
import { stockTableColums } from './configdata.js'
import { dataMainInterface,customInterence } from '@/api/api.js'
import mPage from '@/components/mPage.vue'
import renewalListDia from './components/renewalListDia.vue'
import viewRemark from './components/noRenewalReasonDia/viewRemark.vue'
import confirmedNoRenewal from './components/noRenewalReasonDia/confirmedNoRenewal.vue'

var moment = require('moment');
moment().format();
export default {
	name:'',
	components: {mPage,renewalListDia,viewRemark,confirmedNoRenewal},
	computed: {
		exportExcel() {
			let baseUrl = process.env.API_ROOT + "/statistic_report/stack_company_list";
			let token = localStorage.getItem("auth") || "";
			let paramStr = "";
			// 处理销售筛选
			let salesArr=[]
			if(this.filterObj.sale.length){
				salesArr=this.filterObj.sale.map(item=>{
					return item[item.length-1]
				})
			}
			let obj = {
				PageSize:this.pageSize,
				CurrentIndex:this.page_no,
				CompanyType: this.filterObj.type,
				AdminId: salesArr.join(','),
				RegionType: this.filterObj.area,
				Date: this.filterObj.date,
				DataType: this.filterObj.data_type,
				Keyword:this.searchVal,
				IsExport:true,
				IsConfirm:this.filterObj.data_type=='未续约客户'?1:-1,
				CompanyAscribeId:this.noRenewalReasonId,
			};
			for (let key in obj) {
				paramStr = `${paramStr}&${key}=${obj[key]}`;
			}
			return `${baseUrl}?${token}${paramStr}`;
		},

		stockTableColums() {
			return stockTableColums;
		},
		Role() {
			let role = localStorage.getItem('Role') || '';
			return role;
		},
		//管理权限
		ManageType() {
			return localStorage.getItem('ManageType') || '';
		}
	},
	data () {
		return {
			searchVal:sessionStorage.getItem('stockBack')?JSON.parse(sessionStorage.getItem('stockBack')).searchVal:'',

			tableData:[],
			isShowloadding:false,
			/* 筛选条件 */
			filterObj: {
				date:moment().format("YYYY-MM-DD"),
				type:'',
				sale: '',
				area: '',
				data_type:this.$route.query.type||'新签客户'
			},
			salesArr:[],//销售列表
			defaultSalesProps:{
				multiple: true,
				label:'RealName',
				children:'ChildrenList',
				value:'AdminId'
			},//销售级联配置
			typeArr:[
				{
					name:'ficc'
				},{
					name:'权益'
				}
			],//类型
			areaArr:['国内','海外'],
			pageSize:10,
			page_no:sessionStorage.getItem('stockBack')?JSON.parse(sessionStorage.getItem('stockBack')).page_no:1,
			total:0,
			data_typeArr:[
				{
					label:'新签客户'
				},
				{
					label:'续约客户'
				},
				{
					label:'未续约客户'
				},
			],//数据类型
			NewCompanyTotal:0,//新签客户数
			NotRenewalCompanyTotal:0,//未续约客户数
			RenewalCompanyTotal:0,//续约客户数
			isRenewalShow:false,	//未续约说明列表弹框是否显示
			rowInfo: null,	// 未续约说明更多行信息
			tabsList:[{name:'试用',value:'试用'},{name:'冻结/流失',value:'非试用'}],
			tabsActiveName:'试用',
			NotRenewalNotTryOut:0,//冻结流失的人数
			NotRenewalTryOut:0,//试用的人数
			noRenewalReasonList:[],
			noRenewalReasonId:'',
			selectItemRow:{},// 当前选中的row
			//历史备注
			isViewRemarkShow:false,
			historyRemarkList:[],
			//确认不续约
			isConfirmNoRenewalShow:false,
			confirmNoRenewalForm:{
				reason:"",
				detailReason:""
			}
		};
	},
	/* 页面跳转前记录参数 */
	beforeRouteLeave(to, form, next) {
		let backData = {
			page_no: this.page_no,
			filterObj: this.filterObj,
			searchVal:this.searchVal
		}
		sessionStorage.setItem('stockBack',JSON.stringify(backData))
		next()
	},
	/* 页面进入前是否清除参数 */
	beforeRouteEnter(to,from,next) {
		if(from.path!='/customDetail') {
			sessionStorage.removeItem('stockBack')
		}
		next()
	},
	methods: {
		// 搜索
		handleSearch(){
			this.page_no=1
			this.filterObj= {
				date:this.filterObj.date,
				type:'',
				sale: '',
				area: '',
				data_type:this.filterObj.data_type
			}
			this.getTableData()
		},
		//tabs 的点击事件
		tabsHandler(item) {
			this.tabsActiveName = item.value;
			this.page_no = 1;
			this.getTableData()
		},
		/* 获取表格 */
		getTableData() {
			this.isShowloadding = true;
			// 处理销售筛选
			let salesArr=[]
			if(this.filterObj.sale.length){
				salesArr=this.filterObj.sale.map(item=>{
					return item[item.length-1]
				})
			}
			let params = {
				PageSize:this.pageSize,
				CurrentIndex:this.page_no,
				CompanyType: this.filterObj.type,
				AdminId: salesArr.join(','),
				RegionType: this.filterObj.area,
				Date: this.filterObj.date,
				DataType: this.filterObj.data_type,
				Keyword:this.searchVal,
				TryOutType:this.filterObj.data_type=='未续约客户'? this.tabsActiveName : '',
				IsConfirm:-1,
				CompanyAscribeId:this.noRenewalReasonId,
			}
			dataMainInterface.stackList(params).then(res => {
				if(res.Ret === 200) {
					this.tableData = res.Data.List || [];
					this.total = res.Data.Paging.Totals;
					this.NewCompanyTotal = res.Data.NewCompanyTotal;
					this.RenewalCompanyTotal = res.Data.RenewalCompanyTotal;
					this.NotRenewalCompanyTotal = res.Data.NotRenewalCompanyTotal;
					this.NotRenewalTryOut = res.Data.NotRenewalTryOut||0
					this.NotRenewalNotTryOut = res.Data.NotRenewalNotTryOut||0
					this.isShowloadding = false;
				}
			})
		},
		/* 获取销售 */
		getSale() {
			customInterence.getSale().then(res => {
				if(res.Ret === 200) {
					this.salesArr = res.Data.List;
				}
			})
		},
		/* 切换数据类型 */
		toggleType(label) {
			this.filterObj.data_type = label;
			if(label == "未续约客户"){
				this.getNORenewalReasonList()
			}
			this.noRenewalReasonId=''
			this.tabsActiveName = '试用';
			this.page_no = 1;
			this.searchVal=''
			this.getTableData()
		},
		/* 筛选改变时 */
		changeFilter() {
			this.page_no = 1;
			this.searchVal=''
			this.getTableData()
		},
		/* 切换页码 */
		handleCurrentChange(page) {
			this.page_no = page;
			this.getTableData()
		},
		/* 跳转 */
		jumpHandle(row,item) {
			if(item.link) {
				this.$router.push({
					path: '/customDetail',
					query: {
						id:row.CompanyId
					}
				})
			}
		},

		// 未续约说明更多按钮
		renewalReasonMore(row){
			this.rowInfo={
				CompanyId:row.CompanyId,
				ProductId:row.ProductId
			}
			this.isRenewalShow=true
		},
		getNORenewalReasonList(){
			dataMainInterface.getAscribList().then(res=>{
				if(res.Ret == 200){
					this.noRenewalReasonList=res.Data.List||[]
				}
			})			
		},
		// 查看历史备注
		viewHistoryRemarkFun(row){
			// console.log(row);
			dataMainInterface.getNotRenewedRemarkList({CompanyId:row.CompanyId,ProductId:row.ProductId})
			.then(res=>{
				if(res.Ret == 200){
					this.historyRemarkList=res.Data.List || []
					this.isViewRemarkShow=true
				}
			})
		},
		editReasonLabel(row){
			// console.log(row);
			dataMainInterface.infoNoRenewedAscribe({CompanyId:row.CompanyId,ProductId:row.ProductId})
			.then(res=>{
				if(res.Ret == 200){
					this.confirmNoRenewalForm.reason = res.Data.Detail?res.Data.Detail.CompanyAscribeId||"":""
					this.confirmNoRenewalForm.detailReason = res.Data.Detail?res.Data.Detail.Content||"":""
					this.selectItemRow=row
					this.isConfirmNoRenewalShow=true
				}
			})
		},
		saveLabel(item){
			// console.log(item);
			let params={
				CompanyId:this.selectItemRow.CompanyId,
				ProductId:this.selectItemRow.ProductId,
				CompanyAscribeId:item.CompanyAscribeId,
				Content:item.Content
			}
			dataMainInterface.addNoRenewedAscribe(params).then(res=>{
				if(res.Ret == 200){
					this.$message.success("确认成功")
					this.isConfirmNoRenewalShow=false
					this.selectItemRow={}
					this.getTableData()
				}
			})
		}
	},
	created() {},
	mounted() {
		this.getSale();
		if(sessionStorage.getItem('stockBack')) {
			let backData = JSON.parse(sessionStorage.getItem('stockBack'));
			this.page_no = backData.page_no
			this.filterObj = backData.filterObj
			this.searchVal=backData.searchVal
		}
		this.getTableData();
	
	},
}
</script>
<style lang='scss' scoped>
@import './index.scss';
.remark-row{
	display: flex;
	justify-content: center;
	.remark-text{
		width:18px ;
		height: 18px;
		margin-right: 8px;
		font-size: 18px;
		color: #409EFF;
		cursor: pointer;
	}
}
</style>