<template>
	<div class="updateServer_container">
		<div class="card_cont">
			<div class="btn_top">
				<span style="fontSize:14px;color:#409EFF;cursor:pointer" @click="previewHistory">历史签约</span>
			</div>
			<div class="info">
				<h3 class="tit">客户信息</h3>
				<ul class="info_list">
					<li>
						客户名称：{{companyInfo.CompanyName}}
					</li>
					<li>
						社会信用码：{{companyInfo.CreditCode}}
					</li>
					<li>
						地址：{{companyInfo.Address||''}}
					</li>
					<li>
						客户类型：{{companyInfo.CompanyType}}
					</li>
					<li>
						客户状态：{{companyInfo.Status}}
					</li>
					<li>
						客户来源：{{companyInfo.Source}}
					</li>
					<li>
						行业：{{companyInfo.IndustryName}}
					</li>
					<li>
						所属销售：{{companyInfo.SellerName}}
					</li>
					<li>
						备注：{{companyInfo.Reasons}}
					</li>
				</ul>
			</div>
		</div>
		<div class="card_cont">
			<div class="apply_info">
				<h3 style="fontSize:16px;">{{$route.path=='/updateCustom'?'续约申请':'补充协议'}}</h3>
				<div class="info_cont">
					<el-form 
					@submit.native.prevent 
					inline 
					:model="dataForm" 
					:rules="formRule"
					hide-required-asterisk
					ref="dataForm" 
					label-width="100px"
					class="demo-ruleForm">
						<el-form-item label="选择合同类型" prop="contract_type" style="width:70%;padding-left:25px;" v-if="!isRaiSellerShow">
							<!-- <i style="color:#f00;fontSize:20px;position:absolute;left:-114px;top:10%;">*</i> -->
							<el-radio label="续约合同" v-model="dataForm.contract_type" v-if="$route.path=='/updateCustom'">续约合同</el-radio>
							<el-radio label="补充协议" v-model="dataForm.contract_type" v-else>补充协议</el-radio>
						</el-form-item>
						<el-form-item label-width="140px" label="请输入合同编号" style="width:100%" prop="CreditCode" v-if="isRaiSellerShow"
						 :rules="{required: true, message: '请输入合同编号', trigger: 'blur'}">
						   <i style="color:#f00;fontSize:20px;position:absolute;left:-128px;top:10%;">*</i>
						   <el-autocomplete
						   	style="width:360px;"
						   	v-model="dataForm.CreditCode"
						   	:fetch-suggestions="querySearchCreditCode"
						   	placeholder="请复制申请用印时生成的合同编号"
						   	@select="handleSelectCreditCode"
						></el-autocomplete>
						</el-form-item>
						<el-form-item label="合同期限" prop="term" style="marginRight:60px;">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
							<el-date-picker
							:disabled="timeDisable || isRaiSellerShow"
							v-model="dataForm.term"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							@change="dateChange"
							value-format="yyyy-MM-dd"
							:picker-options="pickerOptions"
							style="width:400px;">
							</el-date-picker>
						</el-form-item>
						<el-form-item label="合同金额" prop="amount" style="marginRight:60px;">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
							<el-input 
							v-model.number="dataForm.amount"
							:disabled="isRaiSellerShow"
							placeholder="请输入金额"
							style="width:400px"
							clearable></el-input>
							<span style="color:#666;">元</span>
						</el-form-item>
						<el-form-item label="付款方式" prop="payway" style="marginRight:60px;">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
							<el-select v-model="dataForm.payway" placeholder="请选择付款方式" style="width:400px;" clearable>
								<el-option
								v-for="item in ['月付','季付','半年付','年付','两年付','三年付']"
								:key="item"
								:label="item"
								:value="item">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="付款渠道" prop="payfrom">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
							<el-input 
							v-model="dataForm.payfrom"
							placeholder="填写代支付的渠道名称，没有可以填无"
							style="width:400px"
							clearable></el-input>
						</el-form-item>
						<el-form-item label="套餐类型" prop="setmeal"  style="display:block;" :rules="{ required: true, message: '请选择套餐',trigger: 'change' }" v-if="companyInfo.CompanyType=='ficc' || isRoleType== 'ficc'">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
							 <el-radio-group v-model="dataForm.setmeal" @change="setmealChange">
								<el-radio :label="1">大套餐</el-radio>
								<el-radio :label="2">小套餐</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item class="textarea_item" style="width:97%;paddingLeft:26px;" prop="CheckList">
							<label style="display:block;marginBottom:10px;fontSize:16px;position:relative;color:#666;">
								<i style="color:#f00;fontSize:20px;position:absolute;left:-15px;top:10%;">*</i>
								权限设置
							</label>
							<template  v-if="companyInfo.CompanyType=='权益' || isRoleType== '权益'">
								<raiPermissionbox  ref="raiPermissionboxRef" v-for="item in authList" :key="item.ClassifyName" :allData="item.Items" :formData.sync="dataForm" :raiCheckList.sync="raiCheckList"></raiPermissionbox>
							</template>
							<ul v-else class="menu_lists" style="width:100%">
								<li v-for="item in authList" :key="item.ClassifyName" class="menu_item">
									<el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" :disabled="setSelectPerDisabled(item)" @change="handleCheckAll(item,'auth')" style="marginRight:30px;fontWeight:bold;minWidth:90px;">{{item.ClassifyName+':'}}</el-checkbox>
									<el-checkbox-group v-model="item.CheckList" @change="handleChecked(item)">
										<el-checkbox v-for="list in item.Items" :label="list.ChartPermissionId" :key="list.ChartPermissionId" class="list_item" :disabled="list.disabled||($route.path=='/updateCustom'&&list.IsPublic==1)">{{list.PermissionName}}</el-checkbox>
									</el-checkbox-group>
								</li>
							</ul>
						</el-form-item>
						<el-form-item prop="imglist" style="width:97%;paddingLeft:26px;" class="textarea_item">
							<label style="display:block;marginBottom:10px;fontSize:16px;position:relative;color:#666;">
								<i style="color:#f00;fontSize:20px;position:absolute;left:-15px;top:10%;">*</i>
								上传合同附件<span style="fontSize:12px;color:#f00;">（建议上传盖章后的合同，支持png、jpg、pdf格式）</span>
								<input type="file" name="file" @change="fileSelected()" id="file" class="true-file" style="display:none;">	
								<el-button type="primary" size="medium" @click.native="clickinput('')" style="marginLeft:20px;">点击上传</el-button>
							</label>
							<ul class="img_cont">
								<li v-for="(img,index) in dataForm.imglist" :key="img" class="img_item">
									<!-- <el-image :src="img" alt="" style="background:#aaa;width:240px;height:180px;" :preview-src-list="dataForm.imglist" :id="'img'+index"/> -->
									<pdf ref="pdf" :src="img" style="width:240px;height:180px;overflow:hidden" v-if="img.indexOf('.pdf')!=-1" @click.native="preview('img'+index,index,img)"></pdf>
									<el-image :src="img" alt="" style="background:#aaa;width:240px;height:180px;" :id="'img'+index" v-else @click.native="preview('img'+index,index,img)"/>
									<i class="el-icon-zoom-in" style="position:absolute;right:12px;top:12px;color:#fff;" @click="preview('img'+index,index,img)"></i>
									<span style="position:absolute;right:12px;bottom:12px;color:#409EFF;fontSize:16px;cursor:pointer;" @click.stop="clickinput(index+1)">重新上传</span>
								</li>
							</ul>
						</el-form-item>
					</el-form>
				</div>
			</div>
			<div class="bot_cont">
				<div style="display:flex;justify-content:center;margin:80px 0 30px;">
					<el-button type="primary" style="width:80px;marginRight:24px;" @click="saveHandle">提交</el-button>
					<el-button type="primary" plain style="width:80px;" @click="cancelHandle">取消</el-button>
				</div>
			</div>
		</div>
		<!-- 历史签约弹窗 -->
		<el-dialog
		:visible.sync="isPreview"
		:modal-append-to-body='false'
		:show-close="false"
		custom-class="update_dialog"
		center
		top="7vh"
		width="60%">
			<div slot="title" style="display:flex;alignItems:center;">
				<span style="fontSize:16px;color:#333;fontWeight:bold;">历史签约</span>
			</div>
			<template v-if="dealList.length">
				<div v-for="(item,index) in dealList" :key="index" class="history_item">
					<el-tag style="margin-bottom:30px;" size="small">合同编号：{{item.ContractCode}}</el-tag>
					<ul class="detail_item">
						<li>
							<span style="min-width:300px;marginRight:260px;display:inline-block;">合同期限：{{item.StartDate+'-'+item.EndDate}}</span>
							<span>合同金额：{{item.Money}}元</span>
						</li>
						<li>
							<span style="min-width:300px;marginRight:260px;display:inline-block;">付款方式：{{item.PayMethod}}</span>
							<span>付款渠道：{{item.PayChannel}}</span>
						</li>
						<li class="textarea_item" style="width:97%;">
							<label style="display:block;marginBottom:20px;fontSize:16px;position:relative;">
								权限设置
							</label>	
							<ul class="menu_lists">
								<li v-for="auth in item.PermissionList" :key="auth.ClassifyName" class="menu_item">
									<el-checkbox :indeterminate="auth.CheckList.length>0&&auth.CheckList.length<auth.Items.length" v-model="auth.CheckAll" disabled @change="handleCheckAll(item)" style="marginRight:30px;fontWeight:bold;">{{auth.ClassifyName+':'}}</el-checkbox>
									<el-checkbox-group v-model="auth.CheckList" @change="handleChecked(item)" disabled>
										<el-checkbox v-for="list in auth.Items" :label="list.ChartPermissionId" :key="list.ChartPermissionId" class="list_item">{{list.PermissionName}}</el-checkbox>
									</el-checkbox-group>
								</li>
							</ul>	
						</li>
					</ul>
				</div>
			</template>
			<span v-else>暂无历史合同</span>
		</el-dialog>
		<!-- 图片预览 -->
		<imgPreview
		:isShowToggle="isShowToggle"
		:isPreview="isPreviewimg" 
		:arr="dataForm.imglist" 
		:actIndex="preAct"
		@close="closePreview"
		@togglePre="togglePre"></imgPreview>	
	</div>
</template>

<script>
import { customInterence } from '@/api/api.js'
import imgPreview from '@/components/imgPreview.vue'
// import JurisdictionCheck from '../compontents/jurisdictionCheck.vue';
import raiPermissionbox from './components/raiPermissionbox'
import pdf from 'vue-pdf'
export default {
	name:'',
	components: {imgPreview , pdf,raiPermissionbox},
	data () {
		return {
			temContractData:{},// 最后一份有效合同详情数据
			pickerOptions: {}, 
			companyInfo:JSON.parse(sessionStorage.getItem('companyInfo')) || {},//客户基本信息
			isRoleType:localStorage.getItem('RoleType'),
			authList2:[],
			dealList:[],//合同列表
			isPreview:false,//合同弹窗
			dataForm:{
				contract_type:this.$route.path=='/updateCustom'?'续约合同':'补充协议',
				term:'',
				amount:'',
				payway:'',
				payfrom:'',
				imglist:[],
				setmeal:'',
				qyBigServeCheck:0,
				CreditCode:'',
			},
			formRule:{
				// contract_type:[
				// 	{ required: true, message: '合同类型不能为空', trigger: 'blur' },
				// ],
				term:[
					{ required: true, message: '合同期限不能为空', trigger: 'blur' },
				],
				amount:[
					{ required: true, message: '合同金额不能为空', trigger: 'blur' },
					{ type: 'number', message: '合同金额必须为数字'}
				],
				payway:[
					{ required: true, message: '付款方式不能为空', trigger: 'change' },
				],
				payfrom:[
					{ required: true, message: '付款渠道不能为空', trigger: 'blur' },
				],
				imglist:[
					{ required: true, message: '合同附件不能为空', trigger: 'change' },
				]
			},
			authList:[],//权限列表
			img_replace:'',//重新上传的img
			isPreviewimg:false,
			preAct:"",
			isShowToggle:false,//是否显示切换
			timeDisable:false,//是否能选择日期 补充协议不可选择日期
			equityCheckData:[], //权益复选框
			citiesEquity:[], //
			citiesListEquity:[], //
			citiesListpitchOn:[],
			
			raiCheckList:[], //权益复选框
		};
	},
	// 补充协议 最大截至日期 为权限中最大的
	// 续约 ficc 起始时间 为权限中最大的 
	// 权益 
	methods: {
		/* 获取客户大于今天的最后一份有效合同详情 */
		async getLastedContractInfo(){
			let res=await customInterence.lastContractInfo({CompanyId:this.companyInfo.CompanyId})
			if(res.Ret!=200) return
			this.temContractData=res.Data
			// 续约申请 
			if(this.$route.path=='/updateCustom'){
				this.initUpdateTypeData()
			}

			// 补充协议
			if(this.$route.path=='/addAgreement'){
				let today=this.formatDate(new Date())

				// 找出权限中最晚截止的那个作为截至日期
				let timearr=this.temContractData.map(item=> item.EndDate)
				let maxTime=Math.max.apply(null, timearr.map(item => (new Date(item)).getTime()));
				
				let endDate=this.formatDate(new Date(maxTime))
				this.dataForm.term=[today,endDate]
				this.timeDisable=true
			}
			
		},

		// 格式化时间
		formatDate(date){
			let year=date.getFullYear()
			let month=date.getMonth()+1
			let day=date.getDate()
			return `${year}-${month<10?'0'+month:month}-${day<10?'0'+day:day}`
		},

		// 续约申请处理数据
		initUpdateTypeData(){
			let RoleType=this.companyInfo.CompanyType
			if(RoleType=='ficc'){
				// FICC:续约合同的起始日期需要在权限中最大的时间
				// 找出权限中最晚截止的那个作为截至日期
				let timearr=this.temContractData.map(item=> item.EndDate)
				let maxTime=Math.max.apply(null, timearr.map(item => (new Date(item)).getTime()));
				let endDate=this.formatDate(new Date(maxTime))
				this.pickerOptions={
					disabledDate(time) {
						return time.getTime() < new Date(endDate).getTime();
					}
				}
			}
		},

		//选择时间 权益：续约合同期限与上一份合同期限有重叠时，不能勾选同一行业.
		// 选择的时间和temContractData 中的时间比较 然后格式化权限选择列表
		dateChange(){
			if(parseInt((new Date() - new Date(this.dataForm.term[1]))/(1000*3600*24)) > 0) {
				this.$message.error('结束日期不能小于今天！')
				this.dataForm.term = []
				return
			}
			// if(this.companyInfo.CompanyType!='权益') return
			// if(!this.dataForm.term) return

			// let time1=new Date(this.dataForm.term[0]).getTime() //选择的开始时间
			// let time2=new Date(this.dataForm.term[1]).getTime() //选择的结束时间
			// let time3=new Date(this.temContractData.StartDate).getTime()// 上份合同的开始时间
			// let time4=new Date(this.temContractData.EndDate).getTime()// 上份合同的结束时间
			// if(time1>time4||time2<time3){
			// 	//没有重叠
			// 	console.log('时间无重叠');

			// }else{
			// 	//时间有重叠
			// 	console.log('时间有重叠');
			// 	this.$message.warning('合同期限内行业重复')
			// 	let arr=[]
			// 	this.temContractData.PermissionList.forEach(item=>{
			// 		arr=[...arr,...item.CheckList]
			// 	})
			// 	this.authList=this.authList.map(item=>{
			// 		item.CheckList=[]
			// 		item.isIndeterminate=false
			// 		item.Items.forEach(item2=>{
			// 			if(arr.indexOf(item2.ChartPermissionId)!=-1){
			// 				item2.disabled=true
			// 			}
			// 		})
			// 		return item
			// 	})
			// }
		},

		// /* 重新申请获取上次申请的合同信息并回显 */
		// getLastContract() {
		// 	customInterence.reapplyDetail({
		// 		CompanyApprovalId:parseInt(this.companyInfo.CompanyApprovalId)
		// 	}).then(res => {
		// 		if(res.Ret === 200) {
		// 			/* 处理日期 */
		// 			let date_arr = [];
		// 			date_arr.push(res.Data.Item.StartDate);
		// 			date_arr.push(res.Data.Item.EndDate);
		// 			this.dataForm = {
		// 				term:date_arr,
		// 				contract_type: res.Data.Item.ContractType,
		// 				amount:res.Data.Item.Money,
		// 				payway:res.Data.Item.PayMethod,
		// 				payfrom:res.Data.Item.PayChannel,
		// 				imglist:res.Data.Item.ImgUrl.split('#'),//合同列表图片
		// 				setmeal:res.Data.Item.PackageType 
		// 			}
		// 			if(this.companyInfo.CompanyType == '权益' || this.isRoleType== '权益') {
		// 				let newData =res.Data.Item.PermissionList.length ? res.Data.Item.PermissionList[0] : []
		// 				this.citiesEquity =  newData.ItemsType || []
        // 				this.citiesListEquity  = newData.Items || []
		// 				this.citiesListpitchOn = newData.CheckList || []
		// 			}else {
		// 			/* 处理权限列表 */
		// 			let newArr = [];
		// 			res.Data.Item.PermissionList.forEach(item => {
		// 				item.Items=item.Items.map(item2=>{
		// 					return{
		// 						...item2,
		// 						disabled:false
		// 					}
		// 				})
		// 				let obj = {
		// 					checkAll:item.CheckList&&item.CheckList.length===item.Items.length?true:false,
		// 					isIndeterminate:item.CheckList&&item.CheckList.length>0 && item.CheckList.length<item.Items.length,
		// 					...item,
		// 				}
		// 				newArr.push(obj)
		// 			})
		// 			this.authList = newArr;
		// 			this.dataForm.setmeal == 1  && this.setmealChange()
		// 			}
		// 		}
		// 	})
		// },
		getLastContract() {
			customInterence.reapplyDetail({
				CompanyApprovalId:parseInt(this.companyInfo.CompanyApprovalId)
			}).then(res => {
				if(res.Ret === 200) {
					/* 处理日期 */
					let date_arr = [];
					date_arr.push(res.Data.Item.StartDate);
					date_arr.push(res.Data.Item.EndDate);
					this.dataForm = {
						term:date_arr,
						contract_type: res.Data.Item.ContractType,
						amount:res.Data.Item.Money,
						payway:res.Data.Item.PayMethod,
						payfrom:res.Data.Item.PayChannel,
						imglist:res.Data.Item.ImgUrl.split('#'),//合同列表图片
						qyBigServeCheck:res.Data.Item.RaiPackageType
					}
					/* 处理权限列表 */
					let newArr = [];
					if(this.companyInfo.CompanyType == '权益' || this.isRoleType== '权益') {
						res.Data.Item.PermissionList.length&&res.Data.Item.PermissionList.forEach(item => {
							this.raiCheckList = item.CheckList || []
							newArr.push(item)
						})
					} else {
						res.Data.Item.PermissionList.forEach(item => {
							item.Items=item.Items.map(item2=>{
								return{
									...item2,
									disabled:false
								}
							})
							let obj = {
								checkAll:item.CheckList&&item.CheckList.length===item.Items.length?true:false,
								isIndeterminate:item.CheckList&&item.CheckList.length>0 && item.CheckList.length<item.Items.length,
								...item,
							}
							newArr.push(obj)
						})
					}
					this.authList = newArr;
				}
			})
		},
		/* 获取基本权限信息 */
		// getAuthBasic() {
		// 	customInterence.authList().then(res => {
		// 		if(res.Ret === 200) {
		// 			// if(this.companyInfo.CompanyType == '权益'|| this.isRoleType== '权益') {
		// 			// 	this.citiesEquity = res.Data.ListType ? res.Data.ListType[0].Items : [];
        // 			// 	this.citiesListEquity  = res.Data.List ? res.Data.List[0].Items : [];
		// 			// }else {
		// 				let newArr = [];
		// 				res.Data.List.length&&res.Data.List.forEach(item => {
		// 				item.Items=item.Items.map(item2=>{
		// 					return{
		// 						...item2,
		// 						disabled:false
		// 					}
		// 				})
		// 				let obj = {
		// 					checkAll:false,
		// 					isIndeterminate:item.ClassifyName === '宏观经济'?true:false,
		// 					...item,
		// 				}
		// 				newArr.push(obj)
		// 				this.authList = newArr;
		// 			})
		// 			this.authList = newArr;
		// 		// }
		// 		}
		// 	})
		// },
		/* 获取基本权限信息 */
		getAuthBasic() {
			customInterence.authList({
				IsShowYanXuanKouDian:true,
			}).then(res => {
				if(res.Ret === 200) {
					let newArr = [];
					if(this.companyInfo.CompanyType == '权益' || this.isRoleType== '权益') {
						res.Data.List.length&&res.Data.List.forEach(item => {
							newArr.push(item)
						})
					}else {
					res.Data.List.length&&res.Data.List.forEach(item => {
						item.Items=item.Items||[]
						const temarr=item.Items?item.Items.filter(_e=>_e.IsPublic==1):[]
						item.Items=item.Items.map(item2=>{
							return{
								...item2,
								disabled:false
							}
						})
						let obj = {
							checkAll:item.Items.length>0?temarr.length==item.Items.length:false,
							isIndeterminate:item.Items.length>0?temarr.length==item.Items.length?false:item.Items.some(_e=>_e.IsPublic==1):false,
							...item,
						}
						newArr.push(obj)
					})
					}
					this.authList = newArr;
				}
			})
		},
		setSelectPerDisabled(data){
			const arr=data.Items?data.Items.filter(_e=>_e.IsPublic==1):[]
			return (this.$route.path=='/updateCustom'&&arr.length==data.Items.length) || data.disabled
			//($route.path=='/updateCustom'&&item.IsPublic==1) || item.disabled
		},
		/* 获取历史签约 */
		getDealList() {
			customInterence.historydeal({
				CompanyId:this.companyInfo.CompanyId,
				CompanyType:this.companyInfo.CompanyType
			}).then(res => {
				if(res.Ret === 200) {
					let auth = [];
					res.Data.List&&res.Data.List.forEach(item=> {
						item.StartDate = item.StartDate.replace(/-/g,'.')
						item.EndDate = item.EndDate.replace(/-/g,'.')
						item.PermissionList.forEach(auth => {
							auth.CheckAll = auth.CheckList&&auth.CheckList.length===auth.Items.length?true:false
						})
					})
					this.dealList = res.Data.List || []
				}
			})
		},
		/* 查看历史签约 */
		previewHistory() {
			this.isPreview = true
		},

		// 权益 续约合同判断
		// 1、勾选同行业，判断选择的期限，是否与已存在的合同期限重叠：
		// 有重叠则提示：同行业有重叠的合同期限，请核实后再提交
		// 没有重叠，则提交成功，两份合同独立执行
		// 2、勾选不同行业，直接提交成功，提交成功后，
		// 若期限有重叠，新开新的行业，使用期限按照合同期限，列表中的服务期限按照合同期限加总
		// 若期限无重叠，两份合同独立执行，列表中的服务期限按照执行时的合同期限
		// 2023-02-21 修改只需判断勾选行业的服务期限与本行业是否有重叠，无需判断勾选行业与其余行业是否有期限重叠
		handleValidate(e){
			let validate=true
			const newtemContractData=[]//把所有的都加上升级 id加100000
			this.temContractData.forEach(item=>{
				newtemContractData.push(item)
				newtemContractData.push({...item,ChartPermissionId:100000+item.ChartPermissionId,PermissionName:item.PermissionName+'(升级)'})
			})
			const time1=new Date(this.dataForm.term[0]).getTime() //选择的开始时间
			const time2=new Date(this.dataForm.term[1]).getTime() //选择的结束时间
			if(this.companyInfo.CompanyType=='权益' &&this.$route.path=='/updateCustom'){
				let count=0
				newtemContractData.forEach(item=>{
					let flag=e.indexOf(item.ChartPermissionId)
					if(flag!=-1){
						const time3=new Date(item.StartDate).getTime()// 上份合同的开始时间
						const time4=new Date(item.EndDate).getTime()// 上份合同的结束时间
						if(time1>time4||time2<time3){
							console.log(item.ChartPermissionId,'没重叠');
						}else{
							count++
						}
					}
				})
				if(count>0){
					validate=false
				}
				// 勾选了同行业
				// if(count>0){
				// 	let tag=0
				// 	let time1=new Date(this.dataForm.term[0]).getTime() //选择的开始时间
				// 	let time2=new Date(this.dataForm.term[1]).getTime() //选择的结束时间
				// 	this.temContractData.forEach(item=>{
				// 		let time3=new Date(item.StartDate).getTime()// 上份合同的开始时间
				// 		let time4=new Date(item.EndDate).getTime()// 上份合同的结束时间
				// 		if(time1>time4||time2<time3){
				// 			// 没有重叠
				// 			console.log(item.ChartPermissionId,'没重叠');
				// 		}else{
				// 			// 重叠了
				// 			tag++
				// 		}
				// 	})
				// 	if(tag>0) {
				// 		validate=false
				// 	}
				// }
			}
			return validate
		},

		// /* 提交 */
		// saveHandle() {
		// 	if(!this.dataForm.contract_type) {
		// 		this.$message.warning('合同类型不能为空！')
		// 	}else {
		// 		this.$refs.dataForm.validate((valid) => {
		// 			if (valid) {
		// 				/* 处理权限列表 */
		// 				let checkArr = [];
		// 				this.authList.forEach(item => {
		// 				if(item.CheckList.length) {checkArr.push(item.CheckList)}})
		// 				// if(this.companyInfo.CompanyType==='权益' || this.isRoleType== '权益'){
		// 				// this.$refs.childrenCheck.cities.forEach(item=>{
		// 				// item.Items.forEach(key => {
		// 				// 	if(key.Checked) {
		// 				// 	checkArr.push(key.ChartPermissionId)
		// 				// 	}
		// 				// 	})
		// 				// })
		// 				// this.$refs.childrenCheck.citiesList.forEach(item=>{
		// 				// 	if(item.Checked) {
		// 				// 		checkArr.push(item.ChartPermissionId)
		// 				// 	}
		// 				// })
		// 				// }else {
		// 				// 	this.authList.forEach(item => {
		// 				// 		if(item.CheckList.length) {
		// 				// 			checkArr.push(item.CheckList)
		// 				// 		}
		// 				// 	})
		// 				// }
		// 				if(!checkArr.length && this.companyInfo.CompanyType === '权益') {
		// 					this.$message.warning('请选择权限！');
		// 					return
		// 				}
		// 				// 判断
		// 				let flag=this.handleValidate(checkArr.flat(2))
		// 				if(!flag){
		// 					this.$message.warning('同行业有重叠的合同期限，请核实后再提交')
		// 					return false
		// 				}
		// 				let PermissionIds = checkArr.flat(2).join(',');
		// 				// let PermissionIds = (this.companyInfo.CompanyType === '权益'|| this.isRoleType== '权益') ? checkArr.join(',') : [... new Set(checkArr.flat(2))].join(',');
		// 				let params = {
		// 					CompanyId:this.companyInfo.CompanyId,
		// 					CompanyApprovalId:this.companyInfo.CompanyApprovalId?parseInt(this.companyInfo.CompanyApprovalId):0,
		// 					CompanyType:this.companyInfo.CompanyType,
		// 					ContractType: this.dataForm.contract_type,
		// 					StartDate:this.dataForm.term[0],
		// 					EndDate:this.dataForm.term[1],
		// 					ImgUrl:this.dataForm.imglist.join('#'),
		// 					Money:Number(this.dataForm.amount),
		// 					PayChannel:this.dataForm.payfrom,
		// 					PayMethod:this.dataForm.payway,
		// 					PermissionIds:PermissionIds,
		// 					PackageType:this.dataForm.setmeal ? this.dataForm.setmeal : 0
		// 				}

		// 				console.log(params);
					
		// 				customInterence.Update(params).then(res => {
		// 					if(res.Ret === 200) {
		// 						this.$message.success('更新成功！')
		// 						this.$router.go(-1)
		// 					}
		// 				})
		// 			}
		// 		})
		// 	}
		// },
				/* 提交 */
		saveHandle() {
			if(!this.dataForm.contract_type) {
				this.$message.warning('合同类型不能为空！')
			}else {
				this.$refs.dataForm.validate((valid) => {
					if (valid) {
						/* 处理权限列表 */
						let checkArr = [];
						let PointsArr = []
						let isPoints = true;
						this.authList.forEach(item => {
							if(item.CheckList.length) {
								checkArr.push(item.CheckList)
							}
						})
							
						if((this.companyInfo.CompanyType === '权益' || this.isRoleType == '权益') && !this.isXClassCustom){
							checkArr = this.raiCheckList
							this.authList.forEach(item => {
								item.Items.forEach(key => {
									if (checkArr.includes(key.ChartPermissionId) && key.ShowInput) {
										if (!key.Points) return isPoints = false;
										PointsArr.push({
											ChartPermissionId: key.ChartPermissionId,
											Points: key.Points-0,
										});
									}
								})
								
							})
						}
						// 判断
						let flag=this.handleValidate(checkArr.flat(2))
						if(!flag){
							this.$message.warning('同行业有重叠的合同期限，请核实后再提交')
							return false
						}
						// 判断是否有选着了权限没有输入点数
						if(!isPoints) return this.$message.warning('请输入点数！')
						if(!checkArr.length && this.companyInfo.CompanyType === '权益') return this.$message.warning('请选择权限！');

						let PermissionIds = checkArr.flat(2).join(',');
						let params = {
							CompanyId:this.companyInfo.CompanyId,
							CompanyApprovalId:this.companyInfo.CompanyApprovalId?parseInt(this.companyInfo.CompanyApprovalId):0,
							CompanyType:this.companyInfo.CompanyType,
							ContractType: this.dataForm.contract_type,
							StartDate:this.dataForm.term[0],
							EndDate:this.dataForm.term[1],
							ImgUrl:this.dataForm.imglist.join('#'),
							Money:Number(this.dataForm.amount),
							PayChannel:this.dataForm.payfrom,
							PayMethod:this.dataForm.payway,
							PermissionIds:PermissionIds,
							PackageType:Number(this.dataForm.setmeal),
							RaiPackageType:this.dataForm.qyBigServeCheck||0,
							PointsArr
						}

						console.log(params);
					
						customInterence.Update(params).then(res => {
							if(res.Ret === 200) {
								this.$message.success('更新成功！')
								//this.$router.go(-1)
								this.$router.push({path:`/${this.$route.meta.pathFrom}`})
							}
						})
					}
				})
			}
		},
		/* 取消返回 */
		cancelHandle() {
			//this.$router.go(-1);
			this.$router.push({path:`/${this.$route.meta.pathFrom}`})
		},
		/* 选择全选或取消全选 */
		handleCheckAll(item,type) {
			if(type=='auth'){
				//获取公有的id合集
				let publicIds=[]

				
				let ids = item.Items.map(item =>{
					if(item.IsPublic==1){
						publicIds.push(item.ChartPermissionId)
					}
					return item.ChartPermissionId
				})
				item.CheckList = item.checkAll ? ids : publicIds;	
				item.isIndeterminate = publicIds.length>0&&!item.checkAll?true:false;
				return
			}
			// 取到所有的子菜单id
			let ids = item.Items.map(item =>{
				return item.ChartPermissionId
			})
			item.CheckList = item.checkAll ? ids : [];	
        	item.isIndeterminate = false;
		},
		/* 复选框組选中时 */
		handleChecked(item) {
			let len = item.CheckList.length;
			if(this.companyInfo.CompanyType == '权益' || this.isRoleType== '权益') {
				/* 获取大套餐行业并且判断 value里面有没有包含 大套餐的全部id*/
				let isCheckAllTrue = item.Items.filter(key=> ![31,29].includes(key.ChartPermissionId)&& !key.PermissionName.includes('升级')).every(val => item.CheckList.includes(val.ChartPermissionId)) 
				item.checkAll = isCheckAllTrue;
				item.isIndeterminate = len > 0 && !isCheckAllTrue
			}else{
			item.checkAll = len === item.Items.length;
			item.isIndeterminate = len > 0 && len < item.Items.length;
			}
		},
		/* 预览 */
		preview(id,index,img) {
			// $('#'+id).click()
			if(img.indexOf('.pdf') == -1) {
				this.preAct = index;
				/* 是否显示左右切换 */
				let bol = this.dataForm.imglist.some(item => {
					return item.indexOf('.pdf') != -1
				})
				// 有pdf或图片只有一张
				if(bol || this.dataForm.imglist.length<=1) {
					this.isShowToggle = false
				}else {
					this.isShowToggle = true
				}
				this.isPreviewimg = true;
			}else {
				window.open(img)
			}
		},
		clickinput(index){  //上传模拟点击
			this.img_replace = '';
			if(index) {
				this.img_replace = index
			}
			$("#file").click();
		},
		fileSelected(){  //选择文件上传
		   if( document.getElementById('file').files[0] ){
				  let hostfile = document.getElementById('file').files[0];
				
		        let size = Math.floor(hostfile.size / 1024 / 1024);
		      if( size>200 ){
		            this.$message.error('上传文件大小不能大于200M！');
		            hostfile = {};
		            return false
		      }
		      if( hostfile.name.toLowerCase().includes('.png') || hostfile.name.toLowerCase().includes('.jpg') || hostfile.name.toLowerCase().includes('.jpeg') || hostfile.name.toLowerCase().includes('.pdf') ){
		        	let form = new FormData();
		        	form.append('file',hostfile);  //hostfile.name
					this.uploadloading=true;
					customInterence.upload(form).then((res) => {
						if( res.Ret === 200 ){
							/* 是替换还是新增 */
							if(this.img_replace) {
								this.dataForm.imglist.splice(this.img_replace-1,1,res.Data.ResourceUrl)
							}else {
								if(this.dataForm.imglist.length >= 4) {
									this.$message.warning('最多上传4张')
								}else {
									this.dataForm.imglist.push(res.Data.ResourceUrl)
								}
							}
						}
						this.uploadloading=false;
						$("#file").val('');
						hostfile = {};
					});
				}else{
					this.$message.error('上传文件格式不正确！');
		        }
		    } 
		},
		closePreview() {
			this.isPreviewimg = false;
		},
		togglePre(type) {
			if(type==1) {
				this.preAct--;
				if(this.preAct < 0) {
					this.preAct = this.dataForm.imglist.length-1;
				}
			}else {
				this.preAct++;
				if(this.preAct > this.dataForm.imglist.length-1) {
					this.preAct = 0;
				}
			}
		},
		//套餐的选择
		setmealChange(){
			if(this.dataForm.setmeal == '1'){
				this.authList.forEach(item => {
					if(!['市场策略','固定收益'].includes(item.ClassifyName)) {
						item.Items.forEach(key => {
							item.CheckList.push(key.ChartPermissionId)
							key.Checked = true
							key.disabled = true
						})
						item.isIndeterminate = false
						item.checkAll = true
						item.disabled = true	
					}
				})
			} else {
				console.log(this.authList);
				// 根据是否为公共品种来设置选中态
				this.authList.forEach(item=>{
					const publicIds=[]
					item.Items.forEach(_item=>{
						if(_item.IsPublic===1){
							publicIds.push(_item.ChartPermissionId)
						}
						_item.Checked = false
						_item.disabled = false
					})
					item.CheckList=publicIds
					item.disabled = false
					item.isIndeterminate = item.CheckList.length===item.Items.length||item.CheckList.length===0?false:true
					item.checkAll = item.CheckList.length===item.Items.length?true:false
				})
				//  this.authList.forEach(item => {
				// 	 if(item.ClassifyName == '宏观经济') {
				// 		 item.CheckList = [1]
				// 		 item.isIndeterminate = true
				// 		 item.disabled=false
				// 		 item.Items[1].disabled=false
				// 		 item.Items[0].disabled=false
				// 	 }else {
				// 		 item.Items.forEach(key => {		
				// 			item.CheckList = []
				// 			key.Checked = false
				// 			key.disabled = false
				// 		})
				// 		item.isIndeterminate = false
				// 		item.checkAll = false
				// 		item.disabled = false	
				// 	 }
				// })
				this.$message.warning('请勾选品种')
			}
		},
		// 获取合同编号
		async querySearchCreditCode(queryString, cb) {
			cb([])
			if(queryString) {
			  const res = await customInterence.searchSealcodeSeal({
				KeyWord:queryString
			  })
			  if(res.Ret === 200) {
				if(res.Data.List.length) {
				  const data = res.Data.List.map(item => {
					return {
					  value: item.Code,
					  ...item
					}
				  })
				  cb(data)
				}
			  }
			}
		},
		// 选择合同编号
		handleSelectCreditCode(item) {
			this.dataForm.term = [item.StartDate,item.EndDate]
			this.dataForm.amount = item.Money
		}
	},
	created() {},
	mounted() {
		this.getDealList();
		this.getLastedContractInfo()
		if(this.$route.query.isReapply) {
			this.getLastContract();
		}else {
			this.getAuthBasic();
		}
	},
	computed: {
		isRaiSellerShow() {
			return localStorage.getItem('Role') === 'rai_seller';
		},
	}
}
</script>
<style lang='scss'>
.updateServer_container {
	min-width: 1570px;
	*{
		box-sizing: border-box;
	}
	/* reset */
	.el-collapse {
		border: none;
	}
	.el-collapse-item__header {
		display: block;
		border: none;
		font-size: 16px;
		color: #333;
		font-weight: bold;
		position: relative;
	}
	.el-collapse-item__content {
		padding-left: 30px;
	}
	.el-collapse-item__wrap {
		border: none;
		margin-top: 20px;
	}
	.el-form-item {
		margin-bottom: 30px;
	}
	.el-form-item .el-checkbox-group {
		height: 40px;
	}
	.textarea_item .el-form-item__content {
		width: 100%;
	}
	/*  */
	.card_cont {
		margin-bottom: 20px;
		border: 1px solid #ECECEC;
		padding: 30px;
		background: #fff;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
		.btn_top {
			display: flex;
			justify-content: flex-end;
		}
		.info {
			margin-top: 10px;
			font-size: 16px;
			color: #666;
			.tit {
				color: #333;
				font-size: 16px;
				margin-bottom: 30px;
			}
			.info_list {
				display: flex;
				flex-wrap: wrap;
				padding-left: 50px;
				padding-bottom: 20px;
				li {
					margin-right: 113px;
					margin-bottom: 20px;
					min-width: 250px;
				}
			}
		}
		.info_cont {
			padding-left: 30px;
			margin-top: 30px;
		}
		.img_cont {
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			.img_item {
				position: relative;
				margin-right: 23px;
				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
	.menu_lists {
		padding: 40px 18px;
		border: 1px dashed #AAB4CC;
		border-radius: 4px;
		.menu_item {
			display: flex;
			// align-items: center;
			margin-bottom: 40px;
			&:last-child {
				margin-bottom: 0;
			}
			.list_item {
				margin-right: 30px;
				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
	.update_dialog {
		max-height: 810px;
		min-height: 200px;
		// overflow: hidden;
		overflow-y: auto;
		.el-dialog__header {
			background: #fff;
		}
		.el-dialog__body {
			padding: 30px 50px !important;
		}
		.history_item {
			margin-bottom: 60px;
			.detail_item {
				font-size: 16px;
				color: #666;
				li {
					margin-bottom: 30px;
					&:last-child {
						margin-bottom: 0;
					}
				}
			}
		}
		.menu_lists {
			padding: 20px 18px;
			border: 1px dashed #AAB4CC;
			border-radius: 4px;
			.menu_item {
				display: flex;
				// align-items: center;
				margin-bottom: 20px;
				&:last-child {
					margin-bottom: 0;
				}
				.list_item {
					margin-right: 30px;
					margin-bottom: 5px;
					&:last-child {
						margin-right: 0;
					}
				}
			}
		}
	}
}
</style>