<template>
	<div class="dataReport-container" id="dataReport-container">
		<div class="dataReport-top">
			<a :href="exportExcel" download>
				<button class="button-sty act">导出EXCEL</button>
			</a>
			<button 
			:class="['button-sty',{'act':filterObj.month===item.label}]"
			v-for="item in monthLabel"
			@click="toggleMonth(item.label)"
			:key="item.label">
				{{item.label}}
			</button>
			<date-picker
			v-model="filterObj.date" 
			type="date" 
			range
			value-type="format"
			placeholder="自定义时间段"
			:clearable="false"
			:editable="false"
			@change="dateChange"/>
			<el-input
			placeholder="请输入客户名称"
			v-model="searchVal"
			style="maxWidth:400px;margin-left:auto"
			@input="handleSearch"
			clearable>
				<i slot="prefix" class="el-input__icon el-icon-search"></i>
			</el-input>
		</div>
		<div class="dataReport-main">
			<div class="main-top">
				<!-- <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>
			</div>
			<div class="main-section">
				<el-row :gutter="36">
					<el-col 
					:span="6" 
					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 === '新签客户'
									? '新签合同的起始日期包含在所选时间段内的客户'
									: item.label === '续约客户'
									? '续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户'	
									: '筛选时间段内有过正式转试用记录，且当前为非正式、非永续状态的客户'" 
									placement="top">
										<i class="el-icon-info"></i>
									</el-tooltip>
								</span>
							</div>
							<div class="card-cont">
								{{
									item.label === '新增试用客户' 
									? TrialTotal
									: item.label === '新签客户' 
									? NewCompanyTotal
									: item.label === '续约客户' 
									? RenewalCompanyTotal
									: item.label === '未续约客户' 
									? NotRenewalCompanyTotal
									:""
								}}
							</div>
						</el-card>
					</el-col>	
				</el-row>
			</div>
			<div class="tabs-box" v-if="filterObj.data_type=='未续约客户'">
				<el-radio-group v-model="isNotRenewedConfirm" class="tabs-box-confirm" @change="notRenewedConfirmChange">
					<el-radio-button :label="1">已确认</el-radio-button>
					<div class="center-line"></div>
					<el-radio-button :label="0">待确认</el-radio-button>
				</el-radio-group>
				<div class="tabs-box-status" v-show="isNotRenewedConfirm">
					<el-select v-model="noRenewalReasonId" placeholder="请选择不续约归因"
					clearable @change="getTableData" style="width: 240px;margin-right: 50px;">
						<el-option :label="item.AscribeContent" :value="item.CompanyAscribeId"
						v-for="item in noRenewalReasonList" :key="item.reasonId"></el-option>
					</el-select>
					<span @click="tabsHandler(item)" :class="tabsActiveName===item.value ? 'active':''" 
					v-for="item in tabsList" :key="item">
						{{item.name}}({{item.name==='试用'?NotRenewalTryOut:NotRenewalNotTryOut}})
					</span>
				</div>
			</div>
			<el-table
				:data="tableData"
				border
				style="margin-top: 20px;min-height:400px"
				v-loading="isShowloadding"
				element-loading-text="数据加载中..."
			>
			<template v-for="item in incrementTableColums">
				<el-table-column 
				:key="item.label" 
				:label="item.label"
				:width="item.widthsty"
				align="center"
				v-if="controlTableColumnShow(item)">
					<template slot-scope="scope">
						<span 
							:style="item.textsty" 
							@click="jumpHandle(scope.row,item)" 
							v-if="item.key==='CreateTime'||item.key==='StartDate'||item.key==='EndDate'">
							{{
								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>
							<span class="operation-button" v-show="canConfirmNotRenewed && (!isNotRenewedConfirm)"
							 style="margin-right: 0;" @click="addRemarkFun(scope.row)">添加</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>
			<el-table-column label="操作" width="180px" align="center"
			v-if="canConfirmNotRenewed && (!isNotRenewedConfirm) && filterObj.data_type =='未续约客户'" >
				<template slot-scope="scope">
					<div class="operation-row">
						<span class="operation-button" @click="confirmedNoRenewalFun(scope.row)">确认不续约</span>
					</div>
				</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>
			<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"/>
		<!-- 添加备注弹窗 -->
		<addRemark :isShow.sync="isAddRemarkShow" @saveRemark="saveRemark"  />
		<!-- 历史备注弹窗 -->
		<viewRemark :isShow.sync="isViewRemarkShow" :tableData="historyRemarkList" />
		<!-- 确认不续约弹窗 -->
		<confirmedNoRenewal :isShow.sync="isConfirmNoRenewalShow" :dataForm="confirmNoRenewalForm" 
			:noRenewalReasonList="noRenewalReasonList" @refreshReasonList="getNORenewalReasonList" @saveLabel="saveLabel" />
	</div>
</template>

<script>
import { incrementTableColums } from './configdata.js'
import { dataMainInterface,customInterence } from '@/api/api.js'
import mPage from '@/components/mPage.vue'
import renewalListDia from './components/renewalListDia.vue'
import addRemark from './components/noRenewalReasonDia/addRemark.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,addRemark,viewRemark,confirmedNoRenewal},
	computed: {
		exportExcel() {
			let baseUrl = process.env.API_ROOT + "/statistic_report/incremental_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 = {
				CompanyType: this.filterObj.type,
				AdminId: salesArr.join(','),
				RegionType: this.filterObj.area,
				EndDate: this.end_date,
				StartDate: this.start_date,
				DataType: this.filterObj.data_type == '新增试用客户' ? '新增试用' : 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}`;
		},

		incrementTableColums() {
			return incrementTableColums;
		},
		Role() {
			let role = localStorage.getItem('Role') || '';
			return role;
		},
		//管理权限
		ManageType() {
			return localStorage.getItem('ManageType') || '';
		},
		//确认未续约权限
		canConfirmNotRenewed(){
			return ['admin','rai_admin'].includes(this.Role)
		}
	},
	data () {
		return {
			searchVal:sessionStorage.getItem('incrementBack')?JSON.parse(sessionStorage.getItem('incrementBack')).searchVal:'',
			tableData:[],
			isShowloadding:false,
			start_date:'',
			end_date:'',
			/* 筛选条件 */
			filterObj: {
				month:'近1个月',
				date:[],
				type:'',
				sale: '',
				area: '',
				data_type:'新增试用客户'
			},
			monthLabel: [
				{
					label: "近1个月"
				},
				{
					label: "近2个月"
				},
				{
					label: "近3个月"
				}
			],
			salesArr:[],//销售列表
			defaultSalesProps:{
				multiple: true,
				label:'RealName',
				children:'ChildrenList',
				value:'AdminId'
			},//销售级联配置
			typeArr:[
				{
					name:'ficc'
				},{
					name:'权益'
				}
			],//类型
			areaArr:['国内','海外'],
			pageSize:10,
			page_no:sessionStorage.getItem('incrementBack')?JSON.parse(sessionStorage.getItem('incrementBack')).page_no:1,
			total:0,
			data_typeArr:[
				{
					label:'新增试用客户'
				},
				{
					label:'新签客户'
				},
				{
					label:'续约客户'
				},
				{
					label:'未续约客户'
				},
			],//数据类型
			TrialTotal:0,//新增试用数
			NewCompanyTotal:0,//新签客户数
			NotRenewalCompanyTotal:0,//未续约客户数
			RenewalCompanyTotal:0,//续约客户数
			isRenewalShow:false,	//未续约说明列表弹框是否显示
			rowInfo:null,	// 未续约说明更多行信息
			tabsList:[{name:'试用',value:'试用'},{name:'冻结/流失',value:'非试用'}],
			tabsActiveName:'试用',
			NotRenewalNotTryOut:0,//冻结流失的人数
			NotRenewalTryOut:0,//试用的人数
			isNotRenewedConfirm:1,//未续约的是否已确认
			noRenewalReasonList:[],
			noRenewalReasonId:'',
			selectItemRow:{},// 当前选中的row
			// 添加备注
			isAddRemarkShow:false,
			//历史备注
			isViewRemarkShow:false,
			historyRemarkList:[],
			//确认不续约
			isConfirmNoRenewalShow:false,
			confirmNoRenewalForm:{
				reason:"",
				detailReason:""
			}
		};
	},
	/* 页面跳转前记录参数 */
	beforeRouteLeave(to, form, next) {
		let backData = {
			page_no: this.page_no,
			end_date: this.end_date,
			start_date: this.start_date,
			filterObj: this.filterObj
		}
		sessionStorage.setItem('incrementBack',JSON.stringify(backData))
		next()
	},
	/* 页面进入前是否清除参数 */
	beforeRouteEnter(to,from,next) {
		if(from.path!='/customDetail') {
			sessionStorage.removeItem('incrementBack')
		}
		next()
	},
	methods: {
		controlTableColumnShow(item){
			return !item.dataType || 
							(item.dataType === this.filterObj.data_type && 
							(!item.notRenewedConfirm || item.notRenewedConfirm==this.isNotRenewedConfirm)) // 已确认和待确认
		},
		// 搜索
		handleSearch(){
			if(!this.searchVal){
				this.page_no=1
				this.filterObj= {
					month:'近1个月',
					date:[],
					type:'',
					sale: '',
					area: '',
					data_type:this.filterObj.data_type
				}
				let date_before = moment().subtract(1,'M').format("YYYY-MM-DD");
				let date_now = moment().format("YYYY-MM-DD");
				let date = [date_before,date_now]
				this.start_date = date_before;
				this.end_date = date_now;
				this.filterObj.date = date;
				this.getTableData()
				return
			}
			this.page_no=1
			this.filterObj= {
				month:'',
				date:[],
				type:'',
				sale: '',
				area: '',
				data_type:this.filterObj.data_type
			}
			this.start_date = '';
			this.end_date = '';
			this.getTableData()
		},
		//tabs 的点击事件
		tabsHandler(item) {
			this.tabsActiveName = item.value;
			this.noRenewalReasonId=''
			this.page_no = 1;
			this.getTableData()
		},
		notRenewedConfirmChange(){
			this.tabsActiveName = '试用'
			this.noRenewalReasonId=''
			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 = {
				Keyword:this.searchVal,
				PageSize:this.pageSize,
				CurrentIndex:this.page_no,
				CompanyType: this.filterObj.type,
				AdminId: salesArr.join(','),
				RegionType: this.filterObj.area,
				EndDate: this.end_date,
				StartDate: this.start_date,
				DataType: this.filterObj.data_type == '新增试用客户' ? '新增试用' : this.filterObj.data_type,
				TryOutType:this.filterObj.data_type=='未续约客户' && this.isNotRenewedConfirm==1? this.tabsActiveName : '',
				IsConfirm:this.filterObj.data_type=='未续约客户'?this.isNotRenewedConfirm:-1,
				CompanyAscribeId:this.noRenewalReasonId
			}
			dataMainInterface.incrementalList(params).then(res => {
				if(res.Ret === 200) {
					this.tableData = res.Data.List || [];
					this.total = res.Data.Paging.Totals;
					this.TrialTotal = res.Data.TrialTotal;
					this.NewCompanyTotal = res.Data.NewCompanyTotal;
					this.RenewalCompanyTotal = res.Data.RenewalCompanyTotal;
					this.NotRenewalCompanyTotal = res.Data.NotRenewalCompanyTotal;
					this.NotRenewalTryOut = res.Data.NotRenewalTryOut
					this.NotRenewalNotTryOut = res.Data.NotRenewalNotTryOut
					this.isShowloadding = false;
				}
			})
		},
		/* 获取销售 */
		getSale() {
			customInterence.getSale().then(res => {
				if(res.Ret === 200) {
					this.salesArr = res.Data.List;
				}
			})
		},
		/* 切换月份 */
		toggleMonth(label) {
			this.filterObj.month = label;
			let days = label=='近1个月' ? 1 : label=='近2个月' ? 2 : label=='近3个月' ? 3 : 0;
			this.filterDate(days)
		},
		/* 选择服务日期 */
		dateChange(e) {
			if(e[0]) {
				this.start_date = e[0];
				this.end_date = e[1];
			}else {
				this.start_date = '';
				this.end_date = '';
			}
			this.filterObj.month = '';
			this.page_no = 1;
			this.searchVal=''
			this.getTableData();
		},
		/* 切换数据类型 */
		toggleType(label) {
			this.filterObj.data_type = label;
			this.noRenewalReasonId=''
			if(label == "未续约客户"){
				this.getNORenewalReasonList()
			}
			this.tabsActiveName = '试用';
			this.page_no = 1;
			this.getTableData()
		},
		/* 筛选改变时 */
		changeFilter() {
			this.page_no = 1;
			this.searchVal=''
			this.getTableData()
		},
		/* 切换页码 */
		handleCurrentChange(page) {
			this.page_no = page;
			this.getTableData()
		},
		/* 获取近几个月的日期范围 */
		filterDate(month) {
			if(month) {
				let date_before = moment().subtract(month,'M').format("YYYY-MM-DD");
				let date_now = moment().format("YYYY-MM-DD");
				let date = [date_before,date_now]
				this.start_date = date_before;
				this.end_date = date_now;
				this.filterObj.date = date;
				this.page_no = 1;
				this.searchVal=''
				this.getTableData();
			}
		},
		/* 跳转 */
		jumpHandle(row,item) {
			if(item.link) {
				this.$router.push({
					path: '/customDetail',
					query: {
						id:row.CompanyId
					}
				})
			}
		},
		getNORenewalReasonList(){
			dataMainInterface.getAscribList().then(res=>{
				if(res.Ret == 200){
					this.noRenewalReasonList=res.Data.List||[]
				}
			})			
		},
		// 未续约说明更多按钮
		renewalReasonMore(row){
			this.rowInfo={
				CompanyId:row.CompanyId,
				ProductId:row.ProductId
			}
			this.isRenewalShow=true
		},
		// 添加备注
		addRemarkFun(row){
			this.selectItemRow=row
			this.isAddRemarkShow=true
		},
		// 添加备注 保存
		saveRemark(remark){
			// console.log(remark);
			let params={
				CompanyId:this.selectItemRow.CompanyId,
				ProductId:this.selectItemRow.ProductId,
				Content:remark
			}
			dataMainInterface.addNotRenewedRemark(params).then(res=>{
				if(res.Ret == 200){
					this.$message.success("添加成功")
					this.getTableData()
					this.isAddRemarkShow=false
					this.selectItemRow={}
				}
			})
		},
		// 查看历史备注
		viewHistoryRemarkFun(row){
			dataMainInterface.getNotRenewedRemarkList({CompanyId:row.CompanyId,ProductId:row.ProductId})
			.then(res=>{
				if(res.Ret == 200){
					this.historyRemarkList=res.Data.List || []
					this.isViewRemarkShow=true
				}
			})
		},
		confirmedNoRenewalFun(row){
			this.confirmNoRenewalForm.reason = ""
			this.confirmNoRenewalForm.detailReason = ""
			this.selectItemRow = row
			this.isConfirmNoRenewalShow=true
		},
		editReasonLabel(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){
			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('incrementBack')) {
			let backData = JSON.parse(sessionStorage.getItem('incrementBack'));
			this.page_no = backData.page_no
			this.end_date = backData.end_date
			this.start_date = backData.start_date
			this.filterObj = backData.filterObj
			this.searchVal=backData.searchVal
		}
		/* 默认选中近1个月 */
		this.filterDate(this.filterObj.month === '近1个月' ? 1 : this.filterObj.month ==='近2个月' ? 2 : this.filterObj.month ==='近3个月' ? 3 : 0);
	
	},
}
</script>
<style lang='scss' scoped>
@import './index.scss';
.tabs-box{
	flex-direction: column;
	.tabs-box-confirm{
		display: flex;
		align-items: center;
		margin-bottom: 20px;
		.center-line{
			width: 1px;
			height: 21px;
			background-color: #333333;
			margin: 0 20px;
		}
	}

}
.operation-button{
		color:#409EFF;
		cursor: pointer;
		font-size: 14px;
		margin-right: 10px;
	}
.remark-row{
	display: flex;
	justify-content: center;
	.remark-text{
		width:18px ;
		height: 18px;
		margin-right: 8px;
		font-size: 18px;
		color: #409EFF;
		cursor: pointer;
	}
}
.operation-row{
	display: flex;
	align-items: center;
	justify-content: center;
	flex-wrap: wrap;
	.operation-button{
		&:last-child{
			margin-right:0;
		}
	}
}

</style>
<style lang="scss">
#dataReport-container{
	.tabs-box{
		.el-radio-button{
			margin-right: 0;
		}
		.el-radio-button .el-radio-button__inner{
			border: none;
			width: 120px;
			height: 40px;
			border-radius: 4px;
		}
	}
}


</style>