<template>
	<div class="customList_container" ref="cusContainer">
		<div class="customList_bot_top">
			<div>
				<div v-if="Role!='finance'">
				<el-button type="primary" @click="addCustom" style="marginRight:10px;width:80px;" v-if="AddCompanyBtn">新增</el-button>
				<!-- <a :href="exportUrlDl" download>
					<el-button type="primary" plain style="width:100px;marginRight:10px;">导出客户</el-button>
				</a>
				<a :href="exportUserDl" download>
					<el-button type="primary" plain style="width:110px;">导出联系人</el-button>
				</a> -->
				</div>
			</div>
			<el-input
			placeholder="客户名称/社会信用码/手机号码/邮箱"
			v-model="search_txt"
			style="max-width:520px"
			@input="searchHandle"
			clearable>
				<i slot="prefix" class="el-input__icon el-icon-search"></i>
			</el-input>
		</div>
		<div class="customList_bot">
			<div class="customList_top">
				<el-row :span="24">
					<el-select v-model="fromArea" placeholder="请选择所属区域" style="width:200px;marginRight:10px;marginBottom:8px;" clearable @change="changeFromArea">
						<el-option
							v-for="item in areaArr"
							:key="item"
							:label="item.name"
							:value="item.name">
						</el-option>
					</el-select>
					<el-select v-model="type" placeholder="请选择客户类型" style="width:200px;marginRight:10px;marginBottom:8px;" clearable v-if="Role=='finance'||Role=='admin'" @change="changeType">
						<el-option
							v-for="item in typeArr"
							:key="item"
							:label="item.name"
							:value="item.name">
						</el-option>
					</el-select>
					<el-select v-model="trade" placeholder="请选择行业" style="width:200px;marginRight:10px;marginBottom:8px;" clearable @change="changeTrade">
						<el-option
							v-for="item in tradeArr"
							:key="item.IndustryId"
							:label="item.IndustryName"
							:value="item.IndustryId">
						</el-option>
					</el-select>
					<el-cascader
						v-if="this.act_status=='流失' ||(Role=='finance'||Role=='admin'||Role=='ficc_admin'||Role=='rai_admin'||ManageType!=0)"
						v-model="sales"
						placeholder="请选择销售"
						style="width:200px;marginRight:10px;marginBottom:8px;"
						:options="salesArr"
						:props="defaultSalesProps"
						:show-all-levels="false"
						:key="modifySales"
						collapse-tags
						clearable
						filterable
						@change="changeSales">
					</el-cascader>
					<el-select v-model="setmealSelect" placeholder="请选择套餐类型" style="width:200px;marginRight:10px;marginBottom:8px;" clearable @change="changeTrade">
						<el-option
							v-for="item in setmealArr"
							:key="item.id"
							:label="item.name"
							:value="item.id">
						</el-option>
					</el-select>
					<el-cascader
						v-model="variety"
						placeholder="请选择已购品种"
						style="width:200px;marginRight:10px;marginBottom:8px;"
						:options="varietyArr"
						:props="defaultprops"
						:show-all-levels="false"
						collapse-tags
						clearable
						filterable
						@change="changeVariety">
					</el-cascader>
                    <el-cascader
						v-model="variety_red"
						placeholder="请选择阅读权限"
						style="width:200px;marginRight:10px;marginBottom:8px;"
						:options="varietyArr"
						:props="defaultprops"
						:show-all-levels="false"
						collapse-tags
						clearable
						filterable
						@change="changeVariety">
					</el-cascader>
					<el-cascader v-model="valueLocation" collapse-tags :props="locationProps" clearable :options="locationOptions"  @change="handleChangeLocation" 
            placeholder="请选择客户地址" style="width:200px;marginRight:10px;marginBottom:8px;">
          </el-cascader>
					<date-picker 
						v-model="date" 
						type="date" 
						range
						value-type="format"
						placeholder="服务日期" 
						@change="dateChange" 
						style="width:200px;marginRight:10px;marginBottom:8px;">
					</date-picker>
					<date-picker 
					v-model="createdate" 
					type="date" 
					range
					value-type="format"
					placeholder="创建时间" 

					@change="dateChange2" style="width:200px;marginRight:10px;marginBottom:8px;">
					</date-picker>
					<el-select v-model="todoType" placeholder="请选择任务状态" clearable @change="changeTodoType" style="width:200px;marginRight:10px;marginBottom:8px;">
						<el-option
							v-for="item in todoTypeArr"
							:key="item.id"
							:label="item.name"
							:value="item.name">
						</el-option>
					</el-select>
				</el-row>
			</div>
			<ul class="tabs_cont">
				<li :class="['tab',{'act':act_status === item.Status}]" v-for="(item,index) in tabs" :key="index" @click="changeStatus(item,index)">
					{{item.Status+'('+item.Count+')'}}
				</li>
			</ul>
			<ul class="tabs_cont trial-ul" v-if="act_status === '试用'">
				<li :class="['trial-item',{'act':act_trialTag === item.TryStage}]" v-for="item in trialTagArr" :key="item.TryStage" @click="changeTagStatus(item)">
					{{item.TryStageStr+'('+item.Count+')'}}
				</li>
			</ul>
			<div class="bot_cont">
				<el-table
				ref="userTable"
				:data="tableData"
				v-loading="isShowloadding"
				element-loading-text="数据加载中..."
				@sort-change="sortChangeHandle"
				border>
					<el-table-column
					prop="CompanyName"
					label="客户名称"
					align="center"
					min-width="7.14%"
					>
						<template slot-scope="scope"
						:class="{'isShared':scope.row.IsShared}"
						> 
						  <el-tooltip effect="dark" placement="top-start" :disabled="!((RoleType == 'admin' || RoleType === '权益') && scope.row.IsUserMaker == -1  && scope.row.CompanyType == '权益')" content="过去4周，kp均未覆盖服务">
							<span 
							v-if="scope.row.IsSuspend ===1 || scope.row.Status=='潜在'"
							@click="goDetail(scope.row)"
							class="mouse-enter"
							:class="{'color-red':(act_status==='正式'&&scope.row.Status.includes('正式')&&scope.row.WeekViewActive===0)||scope.row.IsUserMaker == -1}"
							:style="scope.row.Status=='潜在'?'':'color:#bbb;cursor:pointer'">
								{{scope.row.CompanyName}}
							</span>
							<span v-else style="color:#409EFF;cursor:pointer;" @click="goDetail(scope.row)" class="customName"
							:class="{'isShared':scope.row.IsShared,'color-red':(act_status==='正式'&&scope.row.Status.includes('正式')&&scope.row.WeekViewActive===0)||scope.row.IsUserMaker == -1}"
							>{{scope.row.CompanyName}}</span>
						  </el-tooltip>
							<img width="15" src="../../../assets/img/icons/remark.png" alt="" v-if="scope.row.RenewalReason||(scope.row.Status==='冻结'&&scope.row.FreezeReason)">
							<el-tooltip content="此客户存在长期且反复申请试用，但从未签约的情况，请谨慎领取" placement="top" :open-delay="500" 
							v-if="RaiSellerRole && scope.row.IsScrounge == 1">
								<img width="16" style="cursor: pointer;" src="../../../assets/img/icons/warning_triangle_yellow.png" />
							</el-tooltip>
						</template>
					</el-table-column>
					<el-table-column label="To-Do" prop="todo" align="center" min-width="5.14%" sortable="custom">
						<template slot="header" slot-scope="{}">
							<div class="todolabel" :class="{sort:SortByTodo}" style="display:inline-block;">
								<span>To-Do</span><!-- <img :src="todoSrc" style="margin-left:3px;width:16px;height:16px;padding:3px;"/> -->
							</div>
						</template>
						<template slot-scope="scope">
							<div class="todo-btn">
								<p class="hint" :style="`background-color:${getTodoBtnColor(scope.row.TodoButtonColor)}`"></p>
								<div class="btnwrap">
									<span class="item" 
									v-for="item in getToDoBtn(scope.row)" 
									:key="item.key"
									:style="item.style"
									@click="!item.disable&&handleToDoBtnClick(scope.row,item.key)"
									>{{item.label}}</span>
								</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="DL" prop="deadline" align="center" min-width="5%" sortable="custom">
						<template slot="header" slot-scope="{}">
							<div class="todolabel" :class="{sort:sort_param==='deadline'}" style="display:inline-block;">
								<span>DL</span>
								<el-tooltip 
									effect="dark" 
									placement="top-start"
									content="未完成To Do任务的截止日期-当前日期"
								>
									<i class="el-icon-info"/>
								</el-tooltip>
								<!-- <img :src="todoSrc" style="margin-left:3px;width:16px;height:16px;padding:3px;"/> -->
							</div>
						</template>
						 <template slot-scope="{row}">
							<span>{{row.Deadline||'--'}}</span>
      					</template>
					</el-table-column>
					<el-table-column
					prop="CompanyType"
					label="类型"
					align="center"
					min-width="4.14%"
					>
						<template slot-scope="{row}"> 
							<!-- <p :style="scope.row.IsSuspend===1?'color:#bbb':''">{{scope.row.CompanyType}}</p> 
							<span v-if="scope.row.FiccPackageType"  class="ficc-package">{{scope.row.FiccPackageType == 1 ? '大套餐': '小套餐'}}</span> -->
							<template v-if="row.CompanyType.indexOf('/')!==-1">
								<span :style="row.IsSuspend===1?'color:#bbb':''">{{row.CompanyType.split('/')[0]}}</span><br/>
								<span v-if="row.FiccPackageType"  class="ficc-package">{{row.FiccPackageType == 1 ? '大套餐': '小套餐'}}</span>
								<br   v-if="row.FiccPackageType"/>
								<span :style="row.IsSuspend===1?'color:#bbb':''">{{row.CompanyType.split('/')[1]}}</span>
							</template>
							<template v-else>
								<span :style="row.IsSuspend===1?'color:#bbb':''">{{row.CompanyType}}</span>
								<span v-if="row.FiccPackageType&&row.CompanyType.includes('ficc')"  class="ficc-package">{{row.FiccPackageType == 1 ? '大套餐': '小套餐'}}</span>
							</template>
						</template>
					</el-table-column>
					<el-table-column
					prop="IndustryName"
					label="所属行业"
					min-width="6.14%"
					align="center">
						<template slot-scope="scope"> 
							<!-- <span :style="scope.row.IsSuspend===1?'color:#bbb':''">{{scope.row.IndustryName}}</span>  -->
							<div :style="scope.row.IsSuspend===1?'color:#bbb':''">
								<p :style="scope.row.IsSuspend===1?'color:#bbb':''" v-for="item in scope.row.IndustryName.split('/')" :key="item">{{item}}</p>
							</div> 
						</template>
					</el-table-column>
					<el-table-column
					prop="City"
					label="客户地址"
					min-width="6.14%"
					align="center">
						<template slot-scope="scope">
						<!--  <span v-if="scope.row.Province && scope.row.City" :style="scope.row.IsSuspend===1?'color:#bbb':''">{{scope.row.Province+'/'+scope.row.City}}</span> --> 
						 <span v-if="scope.row.Province && scope.row.City" :style="scope.row.IsSuspend===1?'color:#bbb':''">{{scope.row.Province}}<br/>{{scope.row.City}}</span> 
						 <span v-else :style="scope.row.IsSuspend===1?'color:#bbb':''">{{scope.row.RegionType}}</span> 
						 </template>
					</el-table-column>
					<el-table-column
					prop="SellerName"
					label="销售"
					min-width="6.14%"
					align="center">
						<template slot-scope="scope"> 
							<!-- <span :style="scope.row.IsSuspend===1?'color:#bbb':''">{{scope.row.SellerName}}</span>  -->
							<p :style="scope.row.IsSuspend===1?'color:#bbb':''" v-for="item in scope.row.SellerName.split('/')" :key="item">{{item}}</p>
						</template>
					</el-table-column>
					<el-table-column
					prop="Status"
					label="状态"
					min-width="7.14%"
					align="center" :sortable="act_status==='试用'&&act_trialTag===0?'custom':false" style="background:red">
					<template slot="header" slot-scope="{}">
							<div class="todolabel" :class="{sort:sort_param==='tryStage'}" style="display:inline-block;">
								<span>状态</span><!-- <img :src="require('@/assets/img/icons/todo.png')" v-if="act_status==='试用'&&act_trialTag===0" style="margin-left:5px;width:22px;height:22px;"/> -->
							</div>
					</template>
					<template slot-scope="scope"> 
						<!-- <span :style="scope.row.IsSuspend===1?'color:#bbb':''">{{scope.row.Status+(scope.row.ApproveStatus?'('+scope.row.ApproveStatus+')':'')}}</span>  -->
						<p :style="scope.row.IsSuspend===1?'color:#bbb;margin:3px 0':'margin:3px 0'" v-for="(item,index) in scope.row.Status.split('/')" :key="item">
							{{ item }}
							<template v-if="item === '试用' && scope.row.TryStageSlice">
								<el-select 
									v-model="scope.row.TryStageSlice[index].TryStage" 
									v-if="scope.row.Status === '试用/试用'"
									:disabled="!scope.row.TryStageSlice[index].HasPermission"
									size="mini" 
									style="width: 50px" 
									placeholder=""
									@change="changeTrialHandle(scope.row,scope.row.TryStageSlice[index])"
								>
									<el-option
										v-for="item in trialTags"
										:key="item.value"
										:label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
								<el-select 
									v-model="scope.row.TryStageSlice[0].TryStage"
									:disabled="!scope.row.TryStageSlice[0].HasPermission"
									v-else
									size="mini" 
									style="width: 50px" 
									placeholder=""
									@change="changeTrialHandle(scope.row,scope.row.TryStageSlice[0])"
								>
									<el-option
										v-for="item in trialTags"
										:key="item.value"
										:label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</template>
						</p>
						<!-- 共享客户显示咨询组销售 -->
						<span v-if="scope.row.IsShare==1 && scope.row.ShareSeller">{{ scope.row.ShareSeller }}</span>
					</template>
					</el-table-column>
          <el-table-column
					label="累计试用天数"
					align="center"
					min-width="5.14%"
					prop="tryOutDay"
					sortable="custom">
						<template slot-scope="{row}">
							<el-tooltip :disabled="row.IsSuspend===1||(row.FiccTryOutDay+row.RaiTryOutDay===0)">
								<div slot="content">
                  <p v-if="row.FiccTryOutDay">FICC累计试用天数：{{row.FiccTryOutDay}}</p>
                  <p v-if="row.RaiTryOutDay">权益累计试用天数：{{row.RaiTryOutDay}}</p>
                </div>
								<span :style="row.IsSuspend===1?'color:#bbb':'color:#409EFF;cursor:pointer;'" @click="handleTotalDayClick(row)">
									{{row.FiccTryOutDay+row.RaiTryOutDay}}
								</span>
							</el-tooltip>
						</template>
					</el-table-column>
					<el-table-column
					label="阅读"
					align="center"
					min-width="5.14%"
					prop="viewTotal"
					sortable="custom">
						<template slot-scope="{row}">
							<el-tooltip :disabled="row.IsSuspend===1 || (row.FiccView+row.RaiView)===0">
								<div slot="content"><p v-if="row.FiccView">FICC报告阅读次数：{{row.FiccView}}</p><p v-if="row.RaiView">权益报告阅读次数：{{row.RaiView}}</p></div>
								<span :style="row.IsSuspend===1?'color:#bbb':'color:#409EFF;cursor:pointer;'">
									<!-- {{row.FiccView+row.RaiView}} -->
									<!-- 阅读次数拆分 -->
									{{row.AllViewTotal}}
								</span>
							</el-tooltip>
						</template>
					</el-table-column>
					<el-table-column
					label="路演"
					align="center"
					min-width="5.14%"
					prop="roadShowTotal"
					sortable="custom">
						<template slot-scope="scope">
							<span :style="scope.row.IsSuspend===1?'color:#bbb':''" @click="accumulativeFrequencyClick(scope)" class="editsty" v-if="scope.row.RoadShowTotal > 0">{{scope.row.RoadShowTotal}}</span>
							<span  :style="scope.row.IsSuspend===1?'color:#bbb':''" v-else>{{scope.row.RoadShowTotal}}</span>
						</template>
					</el-table-column>
					<el-table-column
					label="最近阅读"
					min-width="8.14%"
					align="center"
					prop="viewTime"
					sortable="custom">
						<template slot-scope="scope">
						 <p v-if="scope.row.FiccLastViewTime" :style="scope.row.IsSuspend===1?'color:#bbb':''">ficc： {{$moment(scope.row.FiccLastViewTime).format('YYYY.MM.DD')}}</p> 
						 <p v-else-if="scope.row.RaiLastViewTime" :style="scope.row.IsSuspend===1?'color:#bbb':''">权益： {{$moment(scope.row.RaiLastViewTime).format('YYYY.MM.DD')}}</p>
						 <p v-else :style="scope.row.IsSuspend===1?'color:#bbb':''">--</p> 
						 </template>
					</el-table-column>
					<el-table-column
					prop="EndDate"
					:label="act_status=='冻结'?'冻结期限':'服务期限'"
					align="center"
					min-width="6.14%">
						<template slot-scope="scope">
							<span :style="scope.row.IsSuspend===1?'color:#bbb':''">
								<!-- 正常的时间显示 -->
								<template v-if="scope.row.StartDate.indexOf('/')==-1">
									<template v-if="act_status=='流失'">
										创建时间：{{scope.row.CreatedTime|formatTime}}
									</template>
									<template v-else-if="scope.row.Status == '永续'">
										永久
									</template>
									<template v-else-if="act_status == '冻结'">
										{{scope.row.FreezeStartDate}}~{{scope.row.FreezeEndDate}}
									</template>
									<template v-else>
										{{scope.row.StartDate}}~{{scope.row.EndDate}}
									</template>
								</template>
								<!-- 公用客户的时间显示 -->
								<template v-else>
									{{scope.row.StartDate.substr(0,10)}}~{{scope.row.EndDate.substr(0,10)}}/{{scope.row.StartDate.substr(11)}}~{{scope.row.EndDate.substr(11)}}
								</template>
							</span>
						</template>
					</el-table-column>
					<el-table-column
					prop="expireDay"
					:label="act_status=='冻结'?'解冻':'到期'"
					align="center"
					min-width="5.14%"
					sortable="custom">
						<template slot-scope="scope">
							<span :style="scope.row.IsSuspend===1?'color:#bbb':''">
								<template v-if="act_status=='冻结'">
									{{scope.row.FreezeExpireDays||'--'}}
								</template>
								<template v-else>
								 	{{scope.row.ExpireDay||'--'}}
								</template>
							</span> 
						</template>
					</el-table-column>
					<el-table-column
					prop="createTime"
					:label="
						act_status=='冻结'?'冻结时间'
						:act_status=='正式'?'转正时间'
						:act_status=='流失'?'流失时间'
						:act_status=='关闭'?'关闭时间':'创建时间'"
					sortable="custom"
					align="center" min-width="6.14%">
						<template slot-scope="scope">
							<span :style="scope.row.IsSuspend===1?'color:#bbb':''">
								<template v-if="act_status=='冻结'">
									{{$moment(scope.row.FreezeTime).format('YYYY.MM.DD')}}
								</template>
								<template v-else-if="act_status=='正式'">
									{{$moment(scope.row.FormalTime).format('YYYY.MM.DD')}}
								</template>
								<template v-else-if="act_status=='流失'">
									<!-- {{scope.row.LossTime?$moment(scope.row.LossTime.replaceAll('.','-')).format('YYYY.MM.DD'):''}} -->
                                    {{scope.row.LossTime
                                        ?(`${scope.row.LossTime.split('/')[0].substr(0,10)}`)
                                        :''}}
                                    {{scope.row.LossTime&&scope.row.IsShared&&scope.row.LossTime.split('/')[1]
                                        ? `/${scope.row.LossTime.split('/')[1].substr(0,10)}`
                                        :''}}
								</template>
								<template v-else-if="act_status=='关闭'">
									{{$moment(scope.row.CloseTime).format('YYYY.MM.DD')}}
								</template>
								<template v-else>
									{{$moment(scope.row.CreatedTime).format('YYYY.MM.DD')}}
								</template>
							</span> 
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" min-width="7.14%">
						<template slot-scope="scope" v-if="!scope.row.ApproveStatus">
							<!-- 新操作栏 -->
							<div style="color:#4099ef; font-size:24px;display:flex;align-content: center;justify-content: center;align-items: center;">
								<div class="tool" style="display: flex;flex-direction: column;">
									<span :class="item==='BtnDelete'?'deletesty':'editsty'" style="margin: 0 5px;" @click.stop="itemclickHandle({type:btnName(item,scope.row),data:scope.row})"
								v-for="item,index in btnList(scope.row.BtnItem,'front')" :key="index">{{btnName(item,scope.row)}}</span>
								</div>
								<el-dropdown size="medium" placement="bottom-start" @command="itemclickHandle"
								v-if="btnList(scope.row.BtnItem,'back').length" style="height: 16px;">
									<span class="el-dropdown-link">
										<i class="el-icon-more el-icon--right"></i>
										<el-dropdown-menu slot="dropdown">
											<el-dropdown-item :command="{type:btnName(item,scope.row),data:scope.row}" 
											v-for="item,index in btnList(scope.row.BtnItem,'back')" :key="index">
												<span>{{btnName(item,scope.row)}}</span>
											</el-dropdown-item>
										</el-dropdown-menu>
									</span>
								</el-dropdown>
							</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">
					<el-pagination 
					layout="total,prev,pager,next,jumper" 
					background
					:current-page="page_no"
					@current-change="handleCurrentChange"
					:page-size="pageSize" 
					@size-change="handleSizeChange" 
					:total="total"
					style="float:right;">
					</el-pagination>
				</el-col> -->
				<div class="toolbar fixedbar">
					<el-pagination 
					layout="prev,pager,next" 
					background
					:current-page="page_no"
					@current-change="handleCurrentChange"
					:page-size="pageSize" 
					@size-change="handleSizeChange" 
					:total="total"
					style="float:right;">
					</el-pagination>
				</div>
			</div>
		</div>
		<!-- 申请弹窗 -->
		<Capplydia
		:isApply="isApply"
		:title="applyTit"
		:formdata="applyForm"
		:contactFormData="contactFormData"
		@cancelHandle="cancelHandle">
		</Capplydia>
		<!-- 查看权限弹窗 -->
		<permissionView :isLook.sync="isLook" :lookTitle="lookTitle" :lookAuthList="lookAuthList" :lookAuthListEquity="lookAuthListEquity"
     @closeDia="closeDia"></permissionView>
		<!-- 增开试用弹窗 -->
		<el-dialog
		:visible.sync="isAddTrial"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="isAddTrial=false"
		width="800px"
		v-dialogDrag
		center>
			<div slot="title" style="display:flex;alignItems:center;">
				<!-- <img :src="$icons.auth" style="color:#fff;width:16px;height:16px;marginRight:5px;"> -->
				<span style="fontSize:16px;">增开试用（默认两个月）</span>
			</div>
			<Cauthlist
			:autharr="authList"
			:id="addTryId"
			@addOver="addTryOver"
			@close="isAddTrial=false"/>
		</el-dialog>
		<!-- 修改销售弹窗 -->
		<el-dialog
		v-dialogDrag
		:visible.sync="isMove"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelMove"
		center
		width="30%">
			<div slot="title" style="display:flex;alignItems:center;">
				<img :src="$icons.edit" style="color:#fff;width:16px;height:16px;marginRight:5px;">
				<span style="fontSize:16px;">修改销售</span>
			</div>
			<el-form :model="moveform" :rules="moveRule" ref="moveform" label-width="100px" style="marginTop:15px;">
				<el-form-item label="客户名称" prop="name">
					<span style="fontSize:16px;">{{moveform.companyName}}</span>
				</el-form-item>
				<el-form-item label="当前销售" prop="name">
					<span style="fontSize:16px;">{{moveform.sellerName}}</span>
				</el-form-item>
				<el-form-item label="移至销售" prop="sale">
					<!-- <el-select 
					v-model="moveform.sale"
					filterable
					placeholder="请选择修改的销售"
					style="width: 70%">
						<el-option
							v-for="item in modifysalesArr"
							:key="item.AdminId"
							:label="item.RealName"
							:value="item.AdminId">
						</el-option>
					</el-select> -->
					<el-cascader
						v-model="moveform.sale"
						placeholder="请选择修改的销售"
						style="width: 70%"
						:options="modifysalesArr"
						:props="{multiple: false,label:'RealName',children:'ChildrenList',value:'AdminId'}"
						:show-all-levels="false"
						clearable
						filterable>
					</el-cascader>
				</el-form-item>
			</el-form>	
			<div style="display:flex;justify-content:center;margin:75px 0 26px;">
				<el-button type="primary" style="width:80px;marginRight:24px;" @click="saveMove">保存</el-button>
				<el-button  style="width:80px;" @click="cancelMove">取消</el-button>
			</div>
		</el-dialog>
		<!-- 添加联系人弹窗 -->
		<Contactdia
		:id="addCompanyId"
		:title="'新增联系人'"
		:userForm="diaform"
		:custom_name="moveform.companyName"
		:needCard="true"
		:isShowclose="isShowclose"
		:isPickLoss="isPickLoss"
		:isPickSelf="isPickSelf"
		:regionType="regionType"
		:isAddContact="isAddContact"
		@cancel="cancelConcatdia"
		@addContactNext="addContactNext">
		</Contactdia>

		<!-- 冻结理由弹窗 -->
		<el-dialog
		:visible.sync="isFreezeReason"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="closeFreezeReason"
		width="800px"
		v-dialogDrag
		center>
			<div slot="title" style="display:flex;alignItems:center;">
				<img src="../../../assets/img/freeze-icon.png" alt="" width="16" style="margin-right:10px">
				<span style="fontSize:16px;">冻结</span>
			</div>
			<el-input
				type="textarea"
				:rows="6"
				placeholder="请输入冻结理由"
				v-model="freezeData.reason">
			</el-input>
			<div style="text-align:center;margin:30px 0;">
				<el-button type="primary" @click="handleConfirmFreeze">确定</el-button>
				<el-button type="primary" plain @click="closeFreezeReason">取消</el-button>
			</div>
		</el-dialog>

		<!-- 补全信息弹窗 -->
		<CompleteInfo
			:form="completeForm"
			@cancel="cancelCompleteInfo($event)"
		></CompleteInfo>

		<!-- 申请转正、续约申请、补充协议选择申请合同模式弹窗 -->
		<el-dialog
			:visible.sync="contractModel.show"
			:modal-append-to-body='false'
			width="800px"
			class="self-dialog"
			v-dialogDrag
		>
			<div style="text-align:center;margin:30px 0 100px 0">
				<img width="191" src="../../../assets/img/cus_m/bzht.png" @click="handleContractModel('标准')" style="margin-right:80px;cursor: pointer;">
				<img width="191" src="../../../assets/img/cus_m/fbzht.png" @click="handleContractModel('非标准')" style="cursor: pointer;">
				<p style="font-size:15px;color:#333;text-align:left;padding-left:100px;margin-top:30px">
					注：<br>
					系统生成合同请选择标准合同入口<br>
					非系统生成合同请选择非标准合同入口(包含已走完邮件流程的标准合同)</p>
			</div>
		</el-dialog>
		<!-- 申请转正、续约申请、补充协议标准合同模式下 合同信息弹窗 -->
		<ContractInfo 
			:initData="contractDialog" 
			@contractInfoDialogClose="contractInfoDialogClose"
		></ContractInfo>

		<!-- 查看备注弹窗 -->
		<el-dialog
		:visible.sync="isRemarkLook"
		:close-on-click-modal="false"
		:modal-append-to-body="true"
		:append-to-body="true"
		@close="closeDia"
		width="800px"
		v-dialogDrag
		center>
			<div slot="title" style="display:flex;alignItems:center;">
				<img :src="$icons.auth" style="color:#fff;width:16px;height:16px;marginRight:5px;">
				<span style="fontSize:16px;">{{lookRemarkTitle}}</span>
			</div>
			<template>
				<div v-if="(RoleIdentity == 'rai_seller' || RoleIdentity == 'ficc_seller') || (SellerAdminId == lookRemarkItem.SellerId)">
					<el-input
						type="textarea"
						:rows="3"
						placeholder="请输入文字"
						v-model="lookRemarkTextarea">
					</el-input>
					<div class="look-remark-commit" @click="lookRemarkAdd">保存</div>
				</div>
				<el-table
			:data="lookRemarkList"
			border
			max-height="300"
			style="width: 100%; margin-top: 20px;margin-bottom: 20px">
				<el-table-column label="备注内容"  key="Remark"  align="center">
					<template slot-scope="scope">{{scope.row.Remark}}</template>
				</el-table-column>
				<el-table-column label="客户类型" align="center" key="ProductName" v-if="lookRemarkItem.IsShared && (RoleIdentity != 'rai_seller' && RoleIdentity != 'ficc_seller')">
					<template slot-scope="scope">{{scope.row.ProductName}}</template>
				</el-table-column>
				<el-table-column label="创建时间"  key="CreateTime" align="center">
					<template slot-scope="scope">{{scope.row.CreateTime}}</template>
				</el-table-column>
				<el-table-column label="操作" align="center">
					<template slot-scope="{row}">
						<el-button type="text" size="small" style="color:red;" v-if="row.ButtonDel"
							@click="lookRemarkDelete(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			</template>
			<div style="padding:20px 0;"></div>
		</el-dialog>
		<!-- 查看备注弹窗 -->
		<accumulative-frequency-dlg :accumulativeFrequencyDlg.sync="accumulativeFrequencyDlg" :accumulativeFrequencyItem.sync="accumulativeFrequencyItem" />
		<!-- 新建/编辑销售To Do的弹窗 -->
		<Modify-to-do-dialog 
			:todoInfo.sync="todoInfo" 
			:type="modifyToDoType"
			:isModifyDialogShow.sync="isModifyDialogShow"
			@modify="handleModifyToDo"
		></Modify-to-do-dialog>
		<check-to-do-dialog 
			:todoInfo.sync="todoInfo" 
			:ischeckToDoDialogShow.sync="ischeckToDoDialogShow"
			@check="handleApprove"
		></check-to-do-dialog>
		<history-to-do-dialog :todoInfo.sync="todoInfo" :isHistoryDialogShow.sync="isHistoryDialogShow"></history-to-do-dialog>
    <!-- 累计试用天数弹窗 -->
    <total-day-dialog 
      :isTotalDayDialogShow.sync="isTotalDayDialogShow"
      :customInfo.sync="customInfo"
    />
		<!-- 服务记录弹窗 -->
		<share-list-dialog 
			:isShareRecodeDialogShow="isShareRecodeDialogShow"
			:customInfo="customInfo"
			:allowEdit="false"
			@close="isShareRecodeDialogShow=false"/>
		<!-- 关闭客户弹窗 -->
		<el-dialog
		:visible.sync="isCloseCustomDialogShow"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		title="关闭"
		@close="isCloseCustomDialogShow=false"
		width="800px"
		v-dialogDrag
		center>
			<div class="close-custom-dialog">
				<p>是否确认将试用客户【{{customInfo.CompanyName}}】转为关闭客户？若关闭，请填写关闭理由！</p>
				<textarea  rows="6" v-model="closeReason" placeholder="关闭理由描述"></textarea>
				<div class="btn-list">
					<el-button type="primary" plain @click="isCloseCustomDialogShow=false">取消</el-button>
					<el-button type="primary" @click="closeCustom">确定</el-button>
				</div>
				
			</div>
		</el-dialog>
    <historical-notes-dlg :historicalNotesDlgVisible.sync="historicalNotesDlgVisible" :CompanyId.sync="historicalNotesId" />
	
	</div>
</template>

<script>
import Capplydia from '../compontents/Capplydialog.vue'
import { customInterence } from '@/api/api.js'
import Contactdia from '../compontents/Contactdialog'
import Cauthlist from '../compontents/CauthList.vue'
import CompleteInfo from '../compontents/CompleteInfo.vue'
import ContractInfo from '../compontents/ContractInfo.vue'
import {locationOptions} from "./location"
import AccumulativeFrequencyDlg from '../compontents/accumulativeFrequencyDlg.vue'
import ModifyToDoDialog from '../compontents/ModifyToDoDialog.vue'
import CheckToDoDialog from '../compontents/CheckToDoDialog.vue'
import HistoryToDoDialog from '../compontents/HistoryToDoDialog.vue'
import permissionView from './components/permissionView.vue'

import mixin from './mixins/customlistMixin';
import TotalDayDialog from '../compontents/TotalDayDialog.vue'
import ShareListDialog from './components/shareListDialog.vue'

import HistoricalNotesDlg from "@/components/historicalNotesDlg.vue";
export default {
	name:'',
	mixins: [ mixin ],
	components: {Capplydia,Contactdia,Cauthlist,CompleteInfo,ContractInfo, AccumulativeFrequencyDlg, 
		ModifyToDoDialog, CheckToDoDialog,HistoryToDoDialog,TotalDayDialog,permissionView,
ShareListDialog, HistoricalNotesDlg},
	computed:{
		Role() {
			let role = localStorage.getItem('Role') || '';
			return role;
		},
		RoleType() {
			let type = localStorage.getItem('RoleType') || '';
			return type;
		},
		RaiSellerRole(){
			return ['rai_seller','rai_admin','admin'].includes(this.Role)
		},
		SellerAdminId() {
			let type = localStorage.getItem('AdminId') || '';
			return type;
		},
		//管理权限
		ManageType() {
			return localStorage.getItem('ManageType') || '';
		},
		RoleIdentity(){
			let role = localStorage.getItem('RoleIdentity') || '';
			return role;
		},
		/* 导出客户地址 */
		exportUrlDl() {
			let url = this.exportUrl;
			/* 处理品种结构 */
			let param_arr = [];
            let param_arr_red = []
            //已购权限
			if(this.variety.length) {
				param_arr = this.variety.map(item => {
					return item[1];
				})
			}
            //阅读权限
            if(this.variety_red.length){
                param_arr_red = this.variety_red.map(item => {
                    return item[1]
                })
            }
			let param_token = localStorage.getItem('auth')||'';
			let param_variety = param_arr.join(',');
            let param_variety_red = param_arr_red.join(',')
			// let param_sale = this.sales.length?this.sales.join(','):'';
			let param_saleArr = this.sales.length? this.sales.map(item=>{
					return item[item.length-1]
				}):[];
			let param_sale = param_saleArr.length ? param_saleArr.join(',') : ''
			let param_trade = this.trade?Number(this.trade):'';
			let param_package = this.setmealSelect ? Number(this.setmealSelect) : 0
			return `${url}?Status=${this.act_status}`+
                `&CompanyType=${this.type}`+
                `&PackageType=${param_package}`+
                `&IndustryId=${param_trade}`+
                `&AdminId=${param_sale}`+
                `&Province=${this.provinceValue}`+
                `&City=${this.cityValue}`+
                `&ChartPermissionIds=${param_variety_red}`+
                `&ContractPermissionIds=${param_variety}`+
                `&StartDate=${this.start_date}`+
                `&EndDate=${this.end_date}`+
                `&CreateStartDate=${this.createdate.length ? this.createdate[0]:''}`+
                `&CreateEndDate=${this.createdate.length ? this.createdate[1]:''}`+
                `&KeyWord=${this.search_txt}&${param_token}`
		},
		/* 导出联系人地址 */
		exportUserDl() {
			let url = this.exportUser;
			/* 处理品种结构 */
			let param_arr = [];
            let param_arr_red = []
            //已购品种
			if(this.variety.length) {
				param_arr = this.variety.map(item => {
					return item[1];
				})
			}
            //阅读权限
            if(this.variety_red.length){
                param_arr_red = this.variety_red.map(item => {
                    return item[1]
                })
            }
			let param_token = localStorage.getItem('auth')||'';
			let param_variety = param_arr.join(',');
            let param_variety_red = param_arr_red.join(',')
			// let param_sale = this.sales.length?this.sales.join(','):'';
			let param_saleArr = this.sales.length? this.sales.map(item=>{
					return item[item.length-1]
				}):[];
			let param_sale = param_saleArr.length ? param_saleArr.join(',') : ''
			let param_trade = this.trade?Number(this.trade):'';
			let param_package = this.setmealSelect ? Number(this.setmealSelect) : 0
			return `${url}?Status=${this.act_status}`+
                `&CompanyType=${this.type}`+
                `&Province=${this.provinceValue}`+
                `&City=${this.cityValue}`+
                `&PackageType=${param_package}`+
                `&IndustryId=${param_trade}`+
                `&AdminId=${param_sale}`+
                `&ChartPermissionIds=${param_variety_red}`+
                `&ContractPermissionIds=${param_variety}`+
                `&StartDate=${this.start_date}`+
                `&EndDate=${this.end_date}`+
                `&CreateStartDate=${this.createdate.length ? this.createdate[0]:''}`+
                `&CreateEndDate=${this.createdate.length ? this.createdate[1]:''}`+
                `&KeyWord=${this.search_txt}&${param_token}`
		}
	},
	data () {
		return {
			contractModel:{
				show:false,
				data:null,//客户信息（列表用户数据）
				type:'',//类型 申请转正、续约申请、补充协议
			},// 申请转正、续约申请、补充协议 选择合同类型弹窗 
			contractDialog:{
				show:false,
				type:'',//类型 申请转正、续约申请、补充协议
				cusdata:null,//客户信息（列表用户数据）
			},//申请转正、续约申请、补充协议 合同信息弹窗

			exportUrl:process.env.API_ROOT+'/custom/export',//导出数据
			exportUser:process.env.API_ROOT+'/custom/user/export',//导出联系人
			defaultprops:{
				multiple: true,
				label:'ClassifyName',
				children:'Items',
				value:'ChartPermissionId'
			},//块级选择器配置
			tabs:[],
			act_status:this.$route.query.act_status||'全部',//状态
			type:'',//类型
			typeArr:[
				{
					name:'ficc'
				},{
					name:'权益'
				}
			],//类型
			setmealArr:[
				{
					name:'大套餐',
					id:1
				},{
					name:'小套餐',
					id:2
				}
			],
			setmealSelect:'',//套餐的选择
			trade:'',
			tradeArr:[],//行业
			sales:'',
			salesArr:[],//销售
			defaultSalesProps:{
				multiple: true,
				label:'RealName',
				children:'ChildrenList',
				value:'AdminId'
			},//销售级联配置
			modifysalesArr:[],//修改销售选择列表（不存在不可选的销售）
			modifysalesArrtem:[],//从后台获取的修改销售时选择的列表(包括不可选的销售)
			variety:[],//已购品种
            variety_red:[],//阅读权限
			varietyArr:[],
			date:'',
			start_date:'',//开始日期
			end_date:'',//结束日期
			createdate:'',//创建日期
			tableData:[],
			isShowloadding:false,
			search_txt:'',
			total:1,
			page_no:sessionStorage.getItem('customListBack')?JSON.parse(sessionStorage.getItem('customListBack')).page_no:1,
			// page_no:1,
			pageSize:10,
			isApply:false,
			applyTit:'',
			applyForm: {},//申请弹窗客户信息
			isLook:false,//权限弹窗
			lookTitle:'',//权限弹窗标题
			lookAuthList:[],//查看的权限
			lookAuthListEquity:[],//权益
			authList:[],//现有权限列表
			citiesListEquity:[],//权益//现有权限列表
			citiesListpitchOn:[],//权益//现有权限列表
			citiesEquity:[],//权益//现有权限列表
			isMove:false,//修改销售
			moveform:{
				companyType:'',
				companyId:'',//客户id
				companyName:'',
				sale:'',//修改的销售
				sellerName:''
			},
			moveRule:{
				sale:[
					{ required: true, message: '所属销售不能为空', trigger: 'blur' },
				]
			},
			addCompanyId:'',//新增联系人的公司id
			diaform:{
				name:'',
				sex:1,
				telCode:'86',
				tel1:'',
				tel2:'',
				mail:'',
				post:'',
				desiger:'',
				depart:'',
				carte:'',
				Source:'pick_custom'
			},
			isAddContact:false,//是否添加联系人
			isShowclose:false,//是否显示取消
			isPickLoss:false,//联系人弹窗时记录是否是领取流失客户
			isPickSelf:false,//是否为领取自己的流失客户
			isAddTrial:false,//增加试用弹窗
			addTryId:'',//增开试用的id
			regionType:'',
			sort_type:'',//自定义排序方式
			sort_param:'',//自定义排序方式的哪一个
			isFreezeReason:false,//冻结理由弹窗
			freezeData:{
				reason:"",//冻结理由
				CompanyId:'',
				CompanyType:""
			},

			completeForm:{
				show:false,
			},//补全信息弹窗

			contactFormData:{},//领取自己的流失客户新增联系人填写的表单数据
			locationOptions,
			valueLocation:[],
			// locationValue:'',
			provinceValue:'',
			cityValue:'',
			locationProps:{multiple: true,value:'name',children:'city',label:'name'},
			btnCommandList:{
				BtnAddAgreement: '补充协议',
				BtnApplyReceive: '申请领取',
				BtnDelay: '申请延期',
				BtnDelete: '删除',
				BtnDetail: '',
				BtnEdit: '编辑',
				BtnFreeze: '冻结',
				BtnModifySeller: '修改销售',
				BtnReceive: '领取客户',
				BtnReceiveOther: '领取',
				BtnSuspend: '启用/暂停',
				BtnThaw: '申请解冻',
				BtnTryOut: '增开试用',
				BtnTurnPositive: '申请转正',
				BtnUpdate: '续约申请',
				BtnView: '查看权限',
				// BtnRemarkEdit: '编辑备注',
				BtnRemarkView: '备注',
				BtnShare:'设置共享',
				BtnCancelShare:'取消共享',
				BtnServiceRecord:'沟通记录',
				BtnClose:'关闭',
				BtnLoss:'转流失',
				BtnRemarkViewHistory:'历史备注'
			},	// 按钮命令列表
			lookRemarkTitle:'',//查看备注标题
			lookRemarkList:[],//查看备注列表
			lookRemarkTextarea:'',//备注的文本框
			isRemarkLook:false ,////查看备注弹窗
			lookRemarkItem:{},////查看备注的item项
			accumulativeFrequencyDlg:false,//路演业阅读的弹框
			accumulativeFrequencyItem:{},////
			todoBtnType:[
				{
					label:'新建',
					key:'add'
				},
				{
					label:'编辑',
					key:'edit'
				},
				{
					label:'完成',
					key:'confirm'
				},
				{
					label:'历史',
					key:'history'
				}
			],//销售To-Do的按钮
			todoInfo:null,//
			isModifyDialogShow:false,//是否显示销售To-Do新建/编辑的弹窗
			ischeckToDoDialogShow:false,//是否显示销售To-Do的确认完成弹窗
			isHistoryDialogShow:false,//是否显示销售To-Do的历史记录弹窗
			modifyToDoType:'add',//新增or编辑
			todoType:'',
			todoTypeArr:[
				{
					id:1,
					name:'未完成'
				},
				{	id:2,
					name:'已完成'
				},
				{	id:3,
					name:'无任务'
				}
			],
			todoSrc:require('@/assets/img/icons/todo2.png'),
			SortByTodo:false,
			cusCon:null,
			isFixed:false,
			modifySales:0,//用于重新渲染选择销售级联选择窗
			AddCompanyBtn:false,//控制新增客户按钮是否显示

			historicalNotesDlgVisible: false, //历史备注的弹框
			historicalNotesId: 0,
		};
	},
	watch: {
		'type': {
			handler(newval) {
				this.getIndustry();
				this.getVariety();
			}
		},
	},
	/* 页面跳转前记录参数 */
	beforeRouteLeave(to, form, next) {
		let backData = {
			page_no:this.page_no,
			act_status:this.act_status,
			type:this.type,
			trade:this.trade,
			sales:this.sales,
			variety:this.variety,
			date:this.date,
			start_date:this.start_date,
			end_date:this.end_date,
			createdate:this.createdate,
			keyword:this.search_txt,
			setmealSelect:this.setmealSelect,
			valueLocation:JSON.stringify(this.valueLocation),
			todoStatus:this.todoType  
		}
		sessionStorage.setItem('customListBack',JSON.stringify(backData))
		next()
	},
	/* 页面进入前是否清除参数 */
	beforeRouteEnter(to,from,next) {
		if(from.path!='/editCustom'&&from.path!='/turnCustom'&&from.path!='/updateCustom'&&from.path!='/customDetail') {
			sessionStorage.removeItem('customListBack')
		}
		next()
	},
	methods: {
		handleChangeLocation(){
			// const arr =[]
			const provinceArr = []
			const cityArr = []
			this.valueLocation.forEach(item=>{
					// arr.push(item.join(''))
					// 省
					provinceArr.push(item[0])
					// 市
					cityArr.push(item[1])
			})
			// this.locationValue=arr.join(',')
      //provinceArr需要去重
			this.provinceValue = [...new Set(provinceArr)].join(',')
			this.cityValue = cityArr.join(',')
			this.page_no = 1;
			this.getTableData();
		},
		contractInfoDialogClose(e){
			this.contractDialog={
				show:false,
				type:'',//类型 申请转正、续约申请、补充协议
				cusdata:null,//客户信息（列表用户数据）
			}
			if(e==='updateList'){
				this.getTableData();
			}
		},

		// 申请转正、续约申请、补充协议点击合同类型
		handleContractModel(e){
			this.contractModel.show=false
			if(e==='非标准'){
				if(this.contractModel.type==='申请转正'){
					sessionStorage.setItem('companyInfo',JSON.stringify(this.contractModel.data))
					/* this.$router.push({
						path:'/turnCustom',
					}) */
					const { href } = this.$router.resolve({path:'/turnCustom',});
      				window.open(href, '_blank');
				}else if(this.contractModel.type==='续约申请'){
					sessionStorage.setItem('companyInfo',JSON.stringify(this.contractModel.data))
					/* this.$router.push({
						path:'/updateCustom',
					}) */
					const { href } = this.$router.resolve({path:'/updateCustom',});
      				window.open(href, '_blank');
				}else if(this.contractModel.type==='补充协议'){
					sessionStorage.setItem('companyInfo',JSON.stringify(this.contractModel.data))
					/* this.$router.push({
						path:'/addAgreement',
					}) */
					const { href } = this.$router.resolve({path:'/addAgreement',});
      				window.open(href, '_blank');
				}
				return
			}
			// 标准合同
			this.contractDialog.show=true
			this.contractDialog.type=this.contractModel.type
			this.contractDialog.cusdata=this.contractModel.data
		},
		/* 修改销售时选择列表 */
		getmodifySale() {
			customInterence.getSale({AllSeller:true}).then(res => {
				if(res.Ret === 200) {
					this.modifysalesArrtem = res.Data.List;
				}
			})
		},

		// 领取自己的流失客户下一步申请操作
		addContactNext({formData}){
			this.contactFormData=formData
			this.isAddContact=false
			this.isApply=true
		},

		//关闭冻结理由弹窗
		closeFreezeReason(){
			this.isFreezeReason=false
			this.freezeData={
				reason:"",
				CompanyId:'',
				CompanyType:""
			}
		},

		//确认冻结
		async handleConfirmFreeze(){
			if(!this.freezeData.reason){
				this.$message.error('请填写冻结理由')
				return
			}
			let res=await customInterence.Freez({
				CompanyId:Number(this.freezeData.CompanyId),
				CompanyType:this.freezeData.CompanyType,
				Remark:this.freezeData.reason
			})
			if(res.Ret===200){
				this.$message.success('冻结成功');
				this.closeFreezeReason()
				this.getTableData();
			}
		},

		/* 获取表格 */
		getTableData() {
			this.isShowloadding = true;
			/* 处理品种结构 和 阅读权限 */
			let param_arr = [];
            let variety_red_arr = []
			if(this.variety.length) {
				param_arr = this.variety.map(item => {
					return item[1];
				})
			}
            if(this.variety_red.length){
                variety_red_arr = this.variety_red.map(item => {
                    return item[1];
                })
            }
			// 处理销售筛选
			let salesArr=[]
			if(this.sales.length){
				salesArr=this.sales.map(item=>{
					return item[item.length-1]
				})
			}

			let params = {
				SortParam:this.sort_param,//自定义排序字段
				SortType:this.sort_type,//排序方式
				PageSize:this.pageSize,
				CurrentIndex:this.page_no,
				Status:this.act_status,
				CompanyType:this.type,
				IndustryId:this.trade?Number(this.trade):'',
				// AdminId:this.sales?String(this.sales):'',
				AdminId:salesArr.join(','),
				ChartPermissionIds:variety_red_arr.join(','),//阅读权限
                ContractPermissionIds:param_arr.join(','),//已购权限
				StartDate:this.start_date,
				EndDate:this.end_date,
				CreateStartDate:this.createdate[0]?this.createdate[0]:'',
				CreateEndDate:this.createdate[0]?this.createdate[1]:'',
				KeyWord:this.search_txt,
				// Address:this.locationValue,
				Province:this.provinceValue,
				City:this.cityValue,
				PackageType: this.setmealSelect ? Number(this.setmealSelect) : 0,
				TodoStatus:this.todoType,
				SortByTodo:this.SortByTodo,
				TryStage: this.act_trialTag,
				RegionType:this.fromArea
			}
			customInterence.customList(params).then(res => {
				if(res.Ret === 200) {
				
					res.Data.List&&res.Data.List.forEach(item => {
						item.StartDate = item.StartDate.replace(/-/g,'.');
						item.EndDate = item.EndDate.replace(/-/g,'.');
						item.FreezeStartDate = item.FreezeStartDate?item.FreezeStartDate.replace(/-/g,'.'):'';
						item.FreezeEndDate = item.FreezeEndDate?item.FreezeEndDate.replace(/-/g,'.'):'';
						item.LossTime = item.LossTime?item.LossTime.replace(/-/g,'.'):'';
						item.ApproveStatus = item.ApproveStatus=='待审批'?'待审批':''
					})
					this.tabs = res.Data.StatusCount;
					console.log(this.tabs);
					this.total = res.Data.Paging.Totals;
					
					this.trialTagArr = res.Data.TryStageCount ? res.Data.TryStageCount.sort((x,y) => x.TryStage-y.TryStage ) : []
					if(this.trialTagArr.length) {
						const [ x, y, ...res] = this.trialTagArr;
						this.trialTagArr = [ x,...res,y ];
					}

					this.tableData = res.Data.List || [];
					this.AddCompanyBtn = res.Data.AddCompanyBtn	
					this.isShowloadding = false;
				}
			})
		},
		/* 获取品种信息 */
		getVariety() {
			customInterence.getvariety({
				CompanyType:this.type
			}).then(res => {
			
				if(res.Ret === 200) {
					this.varietyArr = res.Data.List;
				}
			})
		},
		/* 根据类型获取行业 */
		getIndustry() {
			customInterence.getindustry({
				Classify:this.type
			}).then(res => {
				if(res.Ret === 200) {
					this.tradeArr = res.Data.List || [];
				}
			})
		},
		/* 获取销售 */
		getSale() {
			let status=0;
			if(this.act_status=='流失'){
				status=1;
			}
			customInterence.getSale({"Status":status}).then(res => {
				if(res.Ret === 200) {
					this.salesArr = res.Data.List;
				}
			})
		},
		/* 新增客户 */
		addCustom() {
			this.$router.push({path:'/addCustom'});
		},
		/* 前往详情页 */
		goDetail(item) {
			this.regionType=item.RegionType
			/* this.$router.push({
				path:'/customDetail',
				query:{
					id:item.CompanyId,
				}
			}) */
			const { href } = this.$router.resolve({
				path:'/customDetail',
				query:{
					id:item.CompanyId,
				}});
      		window.open(href, '_blank');
		},
		/* 搜索客户 重置筛选条件 */
		searchHandle() {
			this.init();
			this.getTableData();
		},
		/* 重置 */
		init() {
			this.act_status = '全部';
			if(this.Role == 'admin'||this.Role=='finance') {
				this.type = '';
			}
			this.trade = '';
			this.sales = '';
			this.variety = '';
			this.date = '';
			this.valueLocation=[]
			// this.locationValue='';
			this.provinceValue=''
			this.cityValue=''
			this.start_date = '';//开始日期
			this.end_date = '';//结束日期
			this.page_no = 1;
		},
		/* 选择类型时 */
		changeType() {
			this.trade = '';
			//this.variety= this.type=='ficc'?[[100,1]]:[];
            this.variety=[]
			this.page_no = 1;
			this.getTableData()
		},
		/* 选择行业 */
		changeTrade() {
			this.page_no = 1;
			this.getTableData();
		},
		/* 选择销售时 */
		changeSales() {
			this.page_no = 1;
			this.getTableData();
		},
		/* 选择品种 */
		changeVariety() {
			this.page_no = 1;
			this.getTableData();
		},
		/* 选择服务日期 */
		dateChange(e) {
			if(e[0]) {
				this.start_date = e[0];
				this.end_date = e[1];
			}else {
				this.start_date = '';
				this.end_date = '';
			}
			this.page_no = 1;
			this.getTableData();
		},
		/* 选择日期 */
		dateChange2(e) {
			// console.log(e[0]);
			if(!e[0]) {
				this.createdate =[]
			}
			this.page_no = 1;
			this.getTableData();
		},
		/* 切换状态 表格重置 */
		changeStatus(item,index) {
			this.act_status = item.Status;
			this.act_trialTag = 0;
			this.$refs.userTable.clearSort()
			this.sort_type =  '';
			this.sort_param = '';
			this.SortByTodo = false
			this.page_no = 1;
			this.getTableData()
			/* this.sales=''; */
			//重新获取销售信息
			this.getSale();
		},

		//关闭补全信息弹窗
		cancelCompleteInfo(refresh){
			// 刷新列表
			if(refresh){
				this.getTableData()
			}
			this.completeForm={
				show:false
			}
		},

		// 获取客户详情判断基本信息是否完整 id 客户
		async getCustomerDetail(id){
			let res=await customInterence.customDetail({
				CompanyId:id
			})
			if(res.Ret!=200) return

			let RoleType=localStorage.getItem('RoleType')
			let IndustryId='',Source=';'
			if(RoleType=='ficc'){
				IndustryId=res.Data.FiccItem.IndustryId
				Source=res.Data.FiccItem.Source
			}else if(RoleType=='权益'){
				IndustryId=res.Data.RaiItem.IndustryId
				Source=res.Data.RaiItem.Source
			}

			// let IndustryId=res.Data.CreateAuth == 1?res.Data.FiccItem.IndustryId:res.Data.RaiItem.IndustryId
			// let Source=res.Data.CreateAuth == 1?res.Data.FiccItem.Source:res.Data.RaiItem.Source
			if((res.Data.Item.RegionType!='海外'&&!res.Data.Item.Province&&!res.Data.Item.City)||!res.Data.Item.CreditCode||!IndustryId||!Source){
				this.completeForm={
					nameDisable:res.Data.Item.CompanyName!='',
					CityDisable:res.Data.Item.City!='',
					CreditCodeDisable:res.Data.Item.CreditCode!='',
					IndustryIdDisable:IndustryId!=' ',
					SourceDisable:Source!='',		
					CompanyId:id,
					name:res.Data.Item.CompanyName,
					Province:res.Data.Item.Province,
					RegionType:res.Data.Item.RegionType,
					City:res.Data.Item.City,
					CreditCode:res.Data.Item.CreditCode,
					IndustryId:IndustryId?IndustryId:'',
					Source:Source,
					flag:false,//是否为跨部门
					show:true
				}
			}else{
				this.completeForm.show=false
			}
			return new Promise((resolve,reject)=>{
				resolve(this.completeForm.show)
			})
		},

		/* 下拉菜单操作 */
		async itemclickHandle(query) {
			if(query.type == '申请转正') {
				//判断是否需要补全信息
				let flag=await this.getCustomerDetail(query.data.CompanyId)
				if(flag) return
				this.contractModel={
					show:true,
					data:query.data,
					type:'申请转正'
				}
				// sessionStorage.setItem('companyInfo',JSON.stringify(query.data))
				// this.$router.push({
				// 	path:'/turnCustom',
				// })
			}else if(query.type == '申请延期') {
				//判断是否需要补全信息
				let flag=await this.getCustomerDetail(query.data.CompanyId)
				if(flag) return

				this.applyTit = query.type;
				this.applyForm = query.data;
				this.isApply = true;
			}else if(query.type == '修改销售') {
				this.updateSale(query.data)
			}else if(query.type == '启用' || query.type == '暂停') {
				customInterence.Suspend({
					CompanyId:query.data.CompanyId
				}).then(res => {
					if(res.Ret === 200) {
						this.$message.success(res.Msg);
						query.data.IsSuspend = query.data.IsSuspend === 1 ? 0 : 1;
					}
				})
			}else if(query.type == '冻结') {
				this.isFreezeReason=true 
				this.freezeData.CompanyId=query.data.CompanyId
				// this.freezeData.CompanyType=query.data.CompanyType
				let RoleType=localStorage.getItem('RoleType')
				this.freezeData.CompanyType=RoleType
				// this.$confirm('确认冻结该客户?','提示',{
				// 	type:'warning'
				// }).then(() => {
				// 	customInterence.Freez({
				// 		CompanyId:query.data.CompanyId,
				// 		CompanyType:query.data.CompanyType
				// 	}).then(res => {
				// 		if(res.Ret === 200) {
				// 			this.$message.success('冻结成功');
				// 			this.getTableData();
				// 		}
				// 	})
				// }).catch(() => {});
			}else if(query.type == '增开试用') {
				this.addTrialHandle(query.data)
			}else if(query.type=='编辑'){
				this.editHandle(query.data)
			}else if(query.type=='删除'){
				this.delHandle(query.data)
			}else if(query.type=='查看权限'){
				this.lookHandle(query.data)
			}else if(query.type=='续约申请'){
				this.updateHandle(query.data)
			}else if(query.type=='补充协议'){
				this.addAgreement(query.data)
			}else if(query.type=='申请解冻'){
				this.applyPick(query.data,'申请解冻')
			}else if(query.type=='申请领取'){
				if(this.RaiSellerRole && query.data.IsScrounge == 1){
					this.$confirm('此客户存在长期且反复申请试用，但从未签约的情况，确定要领取吗？','申请领取',{
						type:'warning'
					}).then(() => {
						this.applyPick(query.data,'申请领取')
					}).catch(() => {});
				}else{
					this.applyPick(query.data,'申请领取')
				}
			}else if(query.type=='领取客户'){
				if(this.RaiSellerRole && query.data.IsScrounge == 1){
					this.$confirm('此客户存在长期且反复申请试用，但从未签约的情况，确定要领取吗？','领取客户',{
						type:'warning'
					}).then(() => {
						this.pickHandle(query.data)
					}).catch(() => {})
				}else{
					this.pickHandle(query.data)
				}
			}else if(query.type=='备注'){
				this.lookRemarkHandle(query.data)
			}else if(query.type=='设置共享' || query.type=='取消共享'){
				this.shareSetting(query.data)
			}else if(query.type=='沟通记录'){
				this.handleShowShareRecode(query.data)
			}else if(query.type=='关闭'){
				this.openCloseReasonDialog(query.data)
			}else if(query.type=='转流失'){
				this.turnLose(query.data)
			}else if(query.type=='历史备注'){
				this.historicalNotesClickHandler(query.data)
			}

		},
		/* 续约申请操作 */
		async updateHandle(item) {
			//判断是否需要补全信息
			let flag=await this.getCustomerDetail(item.CompanyId)
			if(flag) return
			this.contractModel={
				show:true,
				data:item,
				type:'续约申请'
			}
			// sessionStorage.setItem('companyInfo',JSON.stringify(item))
			// this.$router.push({
			// 	path:'/updateCustom',
			// })
		},
		// 补充协议
		async addAgreement(item) {
			//判断是否需要补全信息
			let flag=await this.getCustomerDetail(item.CompanyId)
			if(flag) return
			this.contractModel={
				show:true,
				data:item,
				type:'补充协议'
			}
			// sessionStorage.setItem('companyInfo',JSON.stringify(item))
			// this.$router.push({
			// 	path:'/addAgreement',
			// })
		},
		/* 申请领取/解冻操作 */
		async applyPick(item,type) {
			//判断是否需要补全信息
			let flag=await this.getCustomerDetail(item.CompanyId)
			if(flag) return
			this.applyTit = type;
			this.applyForm = item;
			// 如果是申请领取（即领取自己流失客户）先添加联系人再进行申请操作
			if(type=='申请领取'&& (item.SellerId != localStorage.getItem("AdminId"))){
				this.isPickLoss = true;
				this.isPickSelf=true
				this.regionType = item.RegionType;
				this.addCompanyId = item.CompanyId;
				this.diaform={
					name:'',
					sex:1,
					telCode:'86',
					tel1:'',
					tel2:'',
					mail:'',
					post:'',
					desiger:'',
					depart:'',
					carte:'',
					Source:'pick_custom'
				},
				this.isAddContact = true;
			}else{
				this.isApply = true;
			}
			
		},
		/* 領取流失客戶操作 */
		async pickHandle(item) {
			//判断是否需要补全信息
			let flag=await this.getCustomerDetail(item.CompanyId)
			if(flag) return

			if(this.RaiSellerRole && item.IsScrounge == 1){
				// 已经弹过二次确认弹窗 避免再一次的弹窗
				this.isPickLoss = true;
				this.regionType = item.RegionType;
				this.addCompanyId = item.CompanyId;
				this.diaform.telCode='86'
				this.isAddContact = true;
				return 
			}

			this.$confirm('是否确认领取该客户?','提示',{
				type:'warning'
			}).then(() => {
				// /* 如果是权益领取，需要添加联系人 */
				// if(this.RoleType == '权益') {
					this.isPickLoss = true;
					this.regionType = item.RegionType;
					this.addCompanyId = item.CompanyId;
					this.diaform.telCode='86'
					this.isAddContact = true;
				// }else {
				// 	customInterence.Pick({
				// 		CompanyId:item.CompanyId,
				// 	}).then(res => {
				// 		if(res.Ret === 200) {
				// 			this.$message.success(res.Msg);
				// 			this.getTableData();
				// 		}
				// 	})
				// }
			}).catch(() => {});
		},
		/* 修改销售操作 */
		updateSale(item) {
			this.moveform = {
				companyType:item.CompanyType,
				companyName:item.CompanyName,
				companyId:item.CompanyId,
				sale:'',
				sellerName:item.SellerName,
			}
			this.handleModifysalesArr(item.SellerIds)
			this.isMove = true;
		},
		/* 查看权限 */
		lookHandle(item) {
			this.lookTitle = item.CompanyName;
			customInterence.lookauth({
				CompanyId:item.CompanyId
			}).then(res => {
				if(res.Ret === 200) {
					this.isLook = true;
					let auth = [];			
					res.Data.List ?	res.Data.List.forEach(item=> { 
						auth.push(item.Items)
					}):''
					this.lookAuthList = auth.flat(Infinity);
					let authEquity =[] //权益
					res.Data.ListRai ?	res.Data.ListRai.forEach(item=> {//权益
						// 过滤没有权限的套餐
						let check_Auth = item.Items.filter(it => item.CheckList.includes(it.ChartPermissionId))
						check_Auth.map(item =>{
						// 排序 以防合并问题
							if(item.PermissionType==1){
								//主观 找客观
								authEquity.push(item)
								let ob = check_Auth.find(it => it.PermissionName == item.PermissionName && it.PermissionType!=1)
								ob && authEquity.push(ob)
							}else if(item.PermissionType==0){
								authEquity.push(item)
							}else{
								// 客观
								if(!authEquity.find(t => t.ChartPermissionId == item.ChartPermissionId)){
									authEquity.push(item)
								}
							}
						})
					}):''

					this.lookAuthListEquity = authEquity.flat(Infinity) //权益
				}
			})
		},
		/* 编辑客户 */
		editHandle(item) {
			/* this.$router.push({
				path:'/editCustom',
				query:{
					id:item.CompanyId
				}
			}) */
			this.regionType=item.RegionType
			const { href } = this.$router.resolve({
				path:'/editCustom',
				query:{
					id:item.CompanyId,
				}});
      		window.open(href, '_blank');
		},
		/* 删除客户 */
		delHandle(item) {
			this.$confirm('删除后客户将不能查阅报告，确定删除吗?','提示',{
				type:'warning'
			}).then(() => {
				customInterence.customDel({
					CompanyId:item.CompanyId
				}).then(res => {
					if(res.Ret === 200) {
						this.$message.success(res.Msg)
						this.getTableData()
						// let index = this.tableData.indexOf(item);
						// this.tableData.splice(index,1)
					}
				})
			}).catch(() => {});
		},
		/* 页码改变 */
		handleCurrentChange(page) {
			this.page_no = page;
			this.getTableData();
		},	
		/* 关闭查看权限弹窗 */
		closeDia() {
			this.lookTitle = '';
			this.lookRemarkTextarea = '';
			this.lookRemarkList = []
			this.resetEquity()
			this.isLook = false;
		},
		/* 关闭弹框后重置 */
		resetEquity(){
			this.lookAuthList = [];
			this.lookAuthListEquity = []
		},
		/* 取消申请弹窗 */
		cancelHandle(type) {
			this.isApply = false;
			this.isPickSelf=false
			this.diaform={}
			this.contactFormData={}
			if(type == 1) {
				this.getTableData();
			}
		},
		/* 移动客户所属销售 */
		saveMove() {
			this.$refs.moveform.validate((valid) => {
				if (valid) {
					customInterence.moveSale({
						CompanyType:this.moveform.companyType,
						CompanyId:this.moveform.companyId,
						SellsId:Number(this.moveform.sale[1]) || Number(this.moveform.sale[2])
					}).then(res => {
						if(res.Ret === 200) {
							this.$message.success(res.Msg);
							this.getTableData();
							this.isMove = false;
						}
					})
				}
			})		
		},
		/* 取消移动客户 */
		cancelMove() {
			this.$refs.moveform.resetFields();
			this.isMove = false;
		},
		/* 领取流失添加联系人后再领取 */
		cancelConcatdia(type) {
			this.isAddContact = false;
			this.isPickSelf=false
			this.diaform = {
				name:'',
				sex:1,
				telCode:'86',
				tel1:'',
				tel2:'',
				mail:'',
				post:'',
				desiger:'',
				depart:'',
				carte:'',
				Source:'pick_custom'
			};
			if(type == 1) {
				customInterence.Pick({
					CompanyId:this.addCompanyId,
				}).then(res => {
					if(res.Ret === 200) {
						this.$message.success(res.Msg);
						this.getTableData();
					}
				})
			}else {
				this.$message.warning('领取失败')
			}
		},
		/* 增加试用 */
		addTrialHandle(item) {
			this.authList = [];
			customInterence.lookauth({
				CompanyId:item.CompanyId,
				LookType:1
			}).then(res => {
				if(res.Ret === 200) {
					let auth = [];
					// res.Data.List 有值为 ficc
					// res.Data.ListRai 有值为 权益
					res.Data.List ? res.Data.List.forEach(item=> {
						item.Items=item.Items||[]
						item.CheckList=item.CheckList||[]
						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,
							defaultAuth:item.CheckList,
							customType:'ficc',
							...item,
						}
						auth.push(obj)
					}):
					// 权益 RaiMerge 0不管 1合并 2拆分 所传入的数据结构不一样
					/**权益权限ID
					 * 科技-主观(20)-客观(37)
					 * 消费-主观(21)-客观(38)
					 * 医药-主观(22)-客观(39)
					 * 智造-主观(19)-客观(36)
					 * 策略(23)
					 * 专家(29)
					 * 固收(53)
					 * 调研(54)
					 * 路演服务(30)
					 * 研选订阅(31)
					 * 研选扣点包(52)
					 */
					res.Data.ListRai[0].RaiMerge==1?res.Data.ListRai.forEach(item=> { // 合并
						let checkedLen = item.Items.filter(it => item.CheckList && item.CheckList.includes(it.ChartPermissionId)).length
						let obj = {
							checkAll:checkedLen === item.Items.length,
							isIndeterminate:checkedLen > 0 && checkedLen < item.Items.length,
							defaultAuth:item.CheckList,
							...item,
						}
						auth.push(obj)
					}): res.Data.ListRai.forEach(item=> { // 拆分
						let obj = {
							defaultAuth:item.CheckList,
							customType:'权益',
							...item,
						}	
						// 组合所需的数据格式
						let subjectivityIds=item.Items.filter(it => it.PermissionType==1).map(it => it.ChartPermissionId)//主观的ids
						let subjectivityLength=subjectivityIds.length//有几个主观的id
						let subjectivityCheckedLen = item.CheckList.filter(id => subjectivityIds.includes(id)).length//选中的有几个主观的id
						let objectivityIds=item.Items.filter(it => it.PermissionType==2).map(it => it.ChartPermissionId)//客观的ids
						let objectivityCheckedLen = item.CheckList.filter(id => objectivityIds.includes(id)).length//有几个客观的id
						let objectivityLength=objectivityIds.length//选中的有几个客观的id
						let arr = [{PermissionTypeName:''},
											{PermissionTypeName:{
												value:'主观',
												isIndeterminate:subjectivityCheckedLen>0 && subjectivityCheckedLen<subjectivityLength,
												isCheckAll:subjectivityCheckedLen == subjectivityLength,
												isDisabled:subjectivityCheckedLen == subjectivityLength,
												ids:subjectivityIds
											}},
											{PermissionTypeName:{
												value:'客观',
												isIndeterminate:objectivityCheckedLen > 0 && objectivityCheckedLen < objectivityLength,
												isCheckAll:objectivityCheckedLen == objectivityLength,
												isDisabled:objectivityCheckedLen == objectivityLength,
												ids:objectivityIds
											}}]
						item.Items.map(cp =>{
							if(cp.PermissionType==0){
								// 没有主客观的权限
								arr[0][cp.PermissionName]={
									value:cp.PermissionName,
									width:cp.PermissionName=='研选扣点包'?'100px':'',
									merge:true
								}
								arr[1][cp.PermissionName]={
									value:cp.ChartPermissionId,
									isDisabled:item.CheckList.includes(cp.ChartPermissionId),
									merge:true
								}
								arr[2][cp.PermissionName]={
									value:cp.ChartPermissionId,
									isDisabled:item.CheckList.includes(cp.ChartPermissionId),
									merge:true
								}
							}else if(cp.PermissionType==1){
								// 找出对应的客观Id
								let objectivity = item.Items.find(it => it.PermissionName == cp.PermissionName && it.PermissionType==2)
								arr[0][cp.PermissionName]={
									value:cp.PermissionName,
									isIndeterminate:item.CheckList.filter(id => [cp.ChartPermissionId,objectivity?objectivity.ChartPermissionId:0].includes(id)).length ==1,
									isCheckAll:item.CheckList.filter(id => [cp.ChartPermissionId,objectivity?objectivity.ChartPermissionId:0].includes(id)).length == 2,
									isDisabled:item.CheckList.filter(id => [cp.ChartPermissionId,objectivity?objectivity.ChartPermissionId:0].includes(id)).length ==2,
									bothIds:[cp.ChartPermissionId,objectivity?objectivity.ChartPermissionId:0]
								}
								arr[1][cp.PermissionName]={
									value:cp.ChartPermissionId,
									isDisabled:item.CheckList.includes(cp.ChartPermissionId)
								}
							}else{
								// 分主客观的客观
								arr[2][cp.PermissionName]={
									value:cp.ChartPermissionId,
									isDisabled:item.CheckList.includes(cp.ChartPermissionId)
								}
							}
						})
						obj.dataList=arr
						auth.push(obj)
					})
					this.authList = auth;
				}
			})
			this.addTryId = item.CompanyId;
			this.isAddTrial = true;
		},
		/* 增加试用完成 */
		addTryOver() {
			this.isAddTrial = false;
			this.getTableData();
		},
		/* 到期天数排序发生变化 全局排序 */
		sortChangeHandle(item) {
				if(item.column.label==='To-Do'){
					this.SortByTodo = !this.SortByTodo
					this.sort_type=''
					this.sort_param=''
				}else if(item.prop==='Status'){
					this.SortByTodo = false
					this.sort_type='asc'
					this.sort_param = this.sort_param==='tryStage'?'':'tryStage'
				}else if(item.prop==='deadline'){
					this.SortByTodo = false
					this.sort_type='asc'
					this.sort_param = this.sort_param==='deadline'?'':'deadline'
				}else{
					this.SortByTodo = false
					this.sort_type = item.order === 'ascending' ? 'asc':item.order === 'descending' ? 'desc' : '';
					this.sort_param = item.column.label=='转正时间'?'formalTime'
									:item.column.label=='冻结时间'?'freezeTime'
									:item.column.label=='流失时间'?'lossTime'
									:item.column.label=='关闭时间'?'closeTime':item.prop;
				}
				this.page_no = 1;
				this.getTableData();
		},

		// 处理修改销售数据 不可以修改到已存在销售
		handleModifysalesArr(ids){
			let idsArr=ids.split('/')
			let arr = _.cloneDeep(this.modifysalesArrtem)
			this.modifysalesArr=arr.map(item=>{
				if(item.ChildrenList){
					item.ChildrenList=item.ChildrenList.filter(e=>{
						return  !idsArr.includes(e.AdminId)
					})
				}
				return item
			})
		},

		// 按钮列表
		btnList(btnItem,part){
			const allBtnList=[]
			for (const key in btnItem) {
				btnItem[key] && allBtnList.push(key)
			}
			if(part==='front'){
				// 返回前三个按钮
				return allBtnList.slice(0,3)
			}else{
				// 返回三个后按钮
				return allBtnList.slice(3)
			}
		},
		// 用于返回按钮名称
		btnName(btnItem,row){
			if(btnItem!=='BtnSuspend' && btnItem!=='BtnShare') return this.btnCommandList[btnItem]
			if(btnItem=='BtnSuspend') return row.IsSuspend===1?'启用':'暂停'
			if(btnItem=='BtnShare') return row.IsShare===1?'取消共享':'设置共享'
		},
		// 设置/取消 共享
		shareSetting(row){
			customInterence.setCustomShare({CompanyId:row.CompanyId,IsShare:row.IsShare==0?1:0}).then(res=>{
				if(res.Ret==200){
					this.$message.success(row.IsShare==0?'设置共享成功':'取消共享成功')
					this.getTableData()
				}
			})
		},
		/* 查看备注 */
		lookRemarkHandle(item) {
			/*
			lookRemarkTitle:'',//查看备注标题
			lookRemarkList:[],//查看备注列表
			*/
			this.lookRemarkTitle = "备注";
			this.lookAuthList = [];
			this.lookRemarkItem = item;
			customInterence.lookRemarkAuth({
				CompanyId:item.CompanyId
			}).then(res => {
				if(res.Ret === 200) {
					this.lookRemarkList=res.Data;
				}
			})
			this.isRemarkLook = true;
		},
		//新增备注
		async lookRemarkAdd(){
			if(!this.lookRemarkTextarea) return this.$message.error("请输入文本内容")
			const res = await customInterence.lookRemarkAuthAdd({
				CompanyId:this.lookRemarkItem.CompanyId,
				Remark:this.lookRemarkTextarea
			})
			if(res.Ret===200) {
				this.$message.success('保存成功')
				this.lookRemarkList = []
				this.lookRemarkTextarea =''
				customInterence.lookRemarkAuth({
				CompanyId:this.lookRemarkItem.CompanyId
				}).then(res => {
				if(res.Ret === 200) {
					this.lookRemarkList=res.Data;
				}
				})
			}
		},
		//删除备注
		async lookRemarkDelete(data){
			this.$confirm('备注删除后不可恢复，确认删除吗？','提示',{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type:'warning',
				appendToBody:false
			}).then(async()=>{
				const res = await customInterence.deleteRemark({
					RemarkId:data.RemarkId
				})
				if(res.Ret!==200) return 
				this.$message.success("删除成功")
				customInterence.lookRemarkAuth({
					CompanyId:this.lookRemarkItem.CompanyId
				}).then(res => {
					if(res.Ret === 200) {
						this.lookRemarkList=res.Data;
					}
				})
			})
		},
		accumulativeFrequencyClick(item){
			this.accumulativeFrequencyDlg = true
			this.accumulativeFrequencyItem = item.row
		},
		//销售To-Do的按钮,根据每一行的信息决定显示哪些按钮,必须返回一个数组
		getToDoBtn(row){
			let todoBtn = []
			//该字段为true说明已有任务,隐藏新建按钮
			if(row.TodoStatus){
				todoBtn = this.todoBtnType.filter(i=>i.key!=='add')
			}else{
				todoBtn =  this.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()
			}
			//console.log('?',todoBtn)
			return todoBtn
		},
		//销售To-Do的点击事件
		handleToDoBtnClick(row,type){
			this.todoInfo = row
			//打开新建/编辑弹窗
			if(['add','edit'].includes(type)){
				this.modifyToDoType = type
				this.isModifyDialogShow = true
				this.ischeckToDoDialogShow = false
				this.isHistoryDialogShow=false
			}
			//打开审核记录弹窗
			if(type==='confirm'){
				this.ischeckToDoDialogShow=true
				this.isModifyDialogShow=false
				this.isHistoryDialogShow=false
			}
			//打开历史记录弹窗
			if(type==='history'){
				this.isHistoryDialogShow=true
				this.isModifyDialogShow=false
				this.ischeckToDoDialogShow=false
			}
		},
		//处理销售ToDo
		//新建\编辑弹窗的确认事件
		async handleModifyToDo({type,Description,ProductId,CompanyId,Id,EndTime}){
			console.log(type,Description,ProductId,CompanyId,Id,EndTime)
			let res
			if(type==='add'){
				res = await customInterence.addToDoItem({Description,ProductId,CompanyId,EndTime})
			}else{
				res = await customInterence.editToDoItem({Description,Id,EndTime})
			}
			if(res.Ret===200){
					this.isModifyDialogShow=false
					this.$message.success(`${type==='add'?'提交':'保存'}成功`);
					this.getTableData()
				}			
		},
		handleApprove({Id,Remark}){
			customInterence.checkToDo({Id,Remark}).then(res=>{
				if(res.Ret===200){
					this.ischeckToDoDialogShow=false
					this.$message.success(`审核完成`);
					this.getTableData()
				}
			})
		},
		getTodoBtnColor(colorName){
			if(colorName==='red'){
				return '#D1433A'
			}else if(colorName==='green'){
				return '#61D13A'
			}else{
				return '#999999'
			}
		},
		changeTodoType(){
			this.page_no = 1;
			this.getTableData()
		},
		changeSort(){
			this.SortByTodo = !this.SortByTodo
			this.page_no = 1;
			//自定义排序规则互斥,把其他的排序设置成默认值
			this.sort_type=''
			this.getTableData()
		},
		//根据AdminId生成sales:[]替换this.sales,并请求数据
		async getSaleByAdminId(){
			let temp = [["department_2","group_2","46"],["department_2","group_2","63"]]
			let salesArr = []
			const {adminId} = this.$route.query
			//从/todoTask来的AdminId只会有一个
			const getSale = (list,AdminId)=>{
        		for (let i in list) {
            		if(list[i].AdminId==AdminId){
            			return [list[i]]
          			}
          			if(list[i].ChildrenList){
            			let node=getSale(list[i].ChildrenList,AdminId);
            			if(node!==undefined){
                			return node.concat(list[i])
               			}
          			}
        		}        
    		}
			const res = await customInterence.getSale()
			if(res.Ret === 200) {
				salesArr = res.Data.List;
			}
			temp = getSale(salesArr,adminId)
			this.sales = [temp.map(i=>i.AdminId).reverse()]
			this.modifySales++
			this.act_status = '试用'
			this.getTableData();
		},
		// 点击了历史留言
		historicalNotesClickHandler(item) {
		this.historicalNotesDlgVisible = true;
		this.historicalNotesId = item.CompanyId;
		},
	},
	created() {
		/* 除admin账号 客户类型默认 */
		if(!(this.Role == 'admin'||this.Role=='finance')) {
			this.type = this.RoleType;
		}
		this.variety = this.type=='ficc'?[[100,1]]:[]
	},
	 mounted() {
		if(sessionStorage.getItem('customListBack')) {
			let backData = JSON.parse(sessionStorage.getItem('customListBack'));
			this.search_txt = backData.keyword;
			this.page_no = backData.page_no,
			this.act_status = backData.act_status,
			this.type = backData.type,
			this.trade = backData.trade,
			this.sales = backData.sales,
			this.variety = backData.variety,
			this.date = backData.date,
			this.start_date = backData.start_date,
			this.end_date = backData.end_date,
			this.createdate = backData.createdate,
			this.search_txt = backData.keyword,
			this.setmealSelect =backData.setmealSelect,
			this.valueLocation=JSON.parse(backData.valueLocation)
			this.todoType = backData.todoStatus  
			// const arr =[]
			// this.valueLocation.forEach(item=>{
			// 		arr.push(item.join(''))
			// })
			// this.locationValue=arr.join(',')
			this.handleChangeLocation()
		}
		this.getSale();
		//this.getTableData();
		//获取从/todoTask传来的参数,如果有
		// console.log(this.$route);
		// 从客户区域统计列表过来的参数
		this.act_status=this.$route.params.Status ? this.$route.params.Status : this.act_status
		this.type = this.$route.params.CompanyType ? this.$route.params.CompanyType : this.type
		this.act_trialTag = this.$route.params.TryStage ? this.$route.params.TryStage : this.act_trialTag
		this.valueLocation = this.$route.params.valueLocation ? 
		JSON.parse(sessionStorage.getItem('regionData')) || [] :[]

		if(this.$route.query.adminId){
			this.isShowloadding = true
			this.getSaleByAdminId();
		}else if(this.valueLocation.length>0){
			this.handleChangeLocation()
			sessionStorage.removeItem('regionData')
		}else{
			this.getTableData();
		}
		this.getmodifySale();
	},
}
</script>

<style lang='scss'>
	.self-dialog{
		width: 100% !important;
		max-width: 100% !important;
		.el-dialog__header{
			background-color: #fff;
			.el-dialog__close.el-icon.el-icon-close{
				color: #666;
			}
		}
	}
	.ficc-package {
		display: inline-block;
		font-size: 12px;
		padding:0 5px;
		border-radius: 5px;
		color: #3994fb;
		background-color: #dcecfc;
	}
  .color-red{
    color:red !important;
  }
	.isShared::after{
		content: '共享';
		font-size: 12px;
		// padding: 0px 0px 0px 2px;
		width: 30px;
		color: #3994fb;
		background-color: #dcecfc;
		position: absolute;
		left: 0;
		bottom: 0;
		border-top-right-radius: 5px;
	}
.customList_container {
	.mx-datepicker {
		width: 200px !important;
	}
	.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
		background-color: #409EFF !important;
		border-color: #409EFF;
	}
	.el-checkbox__input.is-disabled.is-indeterminate .el-checkbox__inner {
		background-color: #409EFF !important;
		border-color: #409EFF;
	}
	.customList_bot_top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 28px;
		padding: 20px 30px;
		background: #fff;
		border: 1px solid #ECECEC;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	}
	.customList_bot {
		min-height: calc(100vh - 324px);
		padding: 20px 30px 80px;
		background: #fff;
		position: relative;
		border: 1px solid #ECECEC;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
		.customList_top {
			padding: 20px 0 30px;
			background: #fff;
			.el-cascader__search-input{
				min-width: 30px;
			}
		}
		.tabs_cont {
			display: flex;
			align-items: center;
			color: #333;
			margin-bottom: 30px;
			&.trial-ul {
				padding: 0 30px;
			}
			
			.tab {
				width: 129px;
				height: 22px;
				line-height: 22px;
				text-align: center;
				font-size: 14px;
				border-right:1px solid #707070;
				cursor: pointer;
				transition-delay: 0.05s;
				&:hover {
					color: #409EFF;
				}
				&.act {
					// padding: 9px 24px;
					height: 40px;
					line-height: 40px;
					background: #409EFF;
					border-radius: 4px;
					color: #fff;
					border-color: #409EFF;
					transform: scale(1.014);
				}
				&:last-child {
					border: none;
				}
			}
			.trial-item {
				cursor: pointer;
				margin-right: 30px;
				&:hover {
					color: #409EFF;
				}
				&.act {
					color: #409EFF;
					position: relative;
					&::after {
						content: "";
						width: 100%;
						height: 2px;
						position: absolute;
						bottom: -10px;
						left: 50%;
						transform: translateX(-50%);
						background: #409EFF;
					}
				}
			}
		}
		.try_style {
			color: #BBBBBB;
		}
		.bot_cont{
			//padding-bottom: 20px;
			.fixedbar{
				position: fixed;
    			right: 45px;
    			bottom: 20px;
				background-color: transparent;
        z-index: 2;
			}
		}
		.todo-btn{
			display: flex;
			justify-content: space-around;
    		align-items: center;
			/* padding: 0 10px; */
			.hint{
				width: 8px;
				height: 8px;
				background-color: #D1433A;
				border-radius: 50%;
			}
			.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;
					}
				}
			}
			
			
		}
		.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;
				}
			}
		}
		.todolabel.hidden{
			&+span.caret-wrapper{
				display: none;
			}
		}
	}
	.menu_lists {
		padding: 40px 18px;
		border-radius: 4px;
		.menu_item {
			display: flex;
			// align-items: center;
			margin-bottom: 30px;
			&:last-child {
				margin-bottom: 0;
			}
			.list_item {
				margin-right: 20px;
				margin-bottom: 10px;
				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
	.mouse-enter {
		&:hover {
			text-decoration:underline;
		}
	}
	.close-custom-dialog{
		padding: 0 20px;
		p{
			font-weight: bold;
			font-size: 16px;
		}
		textarea{
			margin: 20px 0;
			width:100%;
			resize: none;
			border-radius: 4px;
			border:1px solid #DCDFE6;
			box-sizing: border-box;
			padding:15px;
		}
		.btn-list{
			text-align: center;
			margin: 25px 0;
		}
	}
}
</style>

<style lang="scss">
.customList_container {
	.el-input--mini {
		.el-input__inner{
			padding: 0 6px !important;
			height: 24px;
			line-height: 24px;
			color: #409EFF;
			background: #ECF5FF;
			border-color: #409EFF;
			text-align: center;
		}
		.el-input__suffix {
			right: -22px;
		}
		&.is-disabled {
			.el-input__inner {
				border-color: #E4E7ED;
			}
			.el-input__suffix {
				display: none;
			}
		}
	}
}
</style>
<style lang="scss">
.look-remark-commit{
	width: 426px;
	height: 41px;
	background: #409EFF;
	margin:  30px auto;
	text-align: center;
	line-height: 41px;
	color: #fff;
	box-shadow: 0px 2px 6px 1px rgba(64, 158, 255, 0.05);
	border-radius: 4px 4px 4px 4px;
	cursor: pointer;
	}
</style>