<template>
	<div class="editCustom_box" v-if="showData">
		<div class="editCustom_container" style="display:flex">
			<div style="flex:1;margin-right:100px">
				<div>
					<p class="page-title">基础信息</p>
					<el-form
						:model="basicform"
						:rules="basicformRule"
						ref="basicform"
						label-width="100px"
						style="display:flex;flex-wrap:wrap;"
						:disabled="!canEidtBtns.BaseInfoEdit"
					>
						<el-form-item label="客户名称" prop="CompanyName" style="width:40%;font-size:15px">
							<!-- <el-input 
								v-model="basicform.CompanyName" 
								placeholder="请输入客户名称"
								style="width:80%">
							</el-input> -->
								<autocomplete
									ref="auto"
									v-model="basicform.CompanyName"
									:fetch-suggestions="callbackHandle"
									@blur="checkCompany"
									@select="customNameSelect"
									@focus="checkCompanyfocus"
									:disabled="$route.query.id"
									placeholder="请输入公司全称"
									clearable
									value-key="value"
									style="width:80%"
									:popper-class="isCheck?'el-autocomplete-none':'el-autocomplete-suggestion-data-entry'"
									class="autocomplete-input"
									>
								<span v-if="basicform.CompanyName.length > 3" :style="{color:'#409EFF',cursor:$route.query.id ? 'not-allowed' : 'pointer'}" slot="suffix"  @click="$route.query.id ? ''  : $refs.auto.search(dataForm.custom_name)"> 查询</span>
								<template slot-scope="scope">
								<div  v-if="scope.item.KeyNo" >
									{{scope.item.Name}}
								</div>
								<div v-else style="text-align:center">暂无数据</div>		 
								</template>
							</autocomplete>
						</el-form-item>
						<el-form-item label="所属区域" prop="RegionType" style="width:26%">
							<span style="color:#333;font-size: 15px;">{{basicform.RegionType}}</span>
						</el-form-item>
						<el-form-item v-if="basicform.RegionType==='海外'" label="所属国家" prop="Nation" style="width:33%"
							:rules="[{required:true,message: '所属国家不能为空', trigger: 'change' }]">
							<el-select v-model="basicform.Nation" placeholder="请选择" filterable style="width:80%;">
								<el-option :label="item.cnName" :value="item.cnName" v-for="item in countryData" :key="item.code" >
									<div style="display: flex;justify-content: space-between;">
										<span>{{ item.cnName }}</span>
										<span style="color: #8492a6; font-size: 13px">{{ item.code }}</span>
									</div>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item v-else label="客户地址" prop="City" style="width:33%">
							<search-dist-picker 
								:provinceInfo="basicform.Province"
								:cityInfo="basicform.City"
								:disabled="!canEidtBtns.BaseInfoEdit"
								@selected="selectRegion"/>
						</el-form-item>
						<el-form-item label="社会信用码" prop="CreditCode" style="width:40%">
							<el-input 
								v-model="basicform.CreditCode" 
								placeholder="请输入社会信用码"
								@blur="checkCompany"
								@focus="checkCompanyfocus"
								:disabled="$route.query.id"
								style="width:80%">
							</el-input>
						</el-form-item>
						<el-form-item label="客户类型" style="width:26%">
							<span style="color:#333;font-size: 15px;">{{
								raiform&&ficcform?'FICC/权益':
								basicform.CreateAuth==1?'FICC':"权益"
								}}</span>
						</el-form-item>
					</el-form>
				</div>
				<!-- 权益模块 -->
				<div v-if="raiform">
					<p class="page-title">权益类型信息</p>
					<el-form
						:model="raiform"
						:rules="raiformRule"
						ref="raiform"
						label-width="100px"
						style="display:flex;flex-wrap:wrap;width:100%"
						:disabled="!canEidtBtns.RaiEdit"
					>
						<el-form-item label="客户状态" style="width:40%">
							<span style="color:#333;font-size: 15px;">{{raiform.Status}}</span>
						</el-form-item>
						<el-form-item label="所属销售" style="width:26%">
							<span style="color:#333;font-size: 15px;">{{raiform.SellerName}}</span>
						</el-form-item>
						<el-form-item label="所属行业" prop="IndustryId" style="width:33%">
							<el-select v-model="raiform.IndustryId" placeholder="请选择行业" style="width:80%;" @focus="slideTrade">
								<el-option
									v-for="item in tradeArr"
									:key="item"
									:label="item.IndustryName"
									:value="item.IndustryId">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="客户来源" prop="Source" style="width:40%">
							<el-select v-model="raiform.Source" placeholder="请选择客户来源" style="width:80%;" filterable>
								<el-option
									v-for="item in fromArr"
									:key="item.SourceId"
									:label="item.SourceName"
									:value="item.SourceName">
								</el-option>
							</el-select>
						</el-form-item>
						<!-- <el-form-item label="备注" prop="Reasons" style="width:58%">
							<el-input 
								v-model="raiform.Reasons" 
								placeholder="请输入备注"
								style="width:92%">
							</el-input>
						</el-form-item> -->
						<el-form-item prop="money" label="管理规模"   style="width:40%">
							<el-select v-model="raiform.Scale" style="width:80%;" clearable placeholder="请选择管理规模（选填）">
								<el-option
								v-for="item in optionsMoney"
								:key="item.value"
								:label="item.label"
								:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
						<div style="width:98%">
							<el-collapse v-model="raiCollapseOpen" accordion>
								<el-collapse-item name="1">
									<template slot="title">
										<p style="display:inline-block;font-size:15px;padding-left:32px">
											<span style="font-weight:bold">权限配置 </span>
											<span style="color:#1989FA;display:inline-block;margin-left:10px">{{raiCollapseOpen=='1'?'收起':'展开'}}</span>
										</p>
									</template>
									<CpessionTable fromType="edit" :authList="raiform.authList" :form="1" @selectAuthHandle="getAuthSelect"/>
										<!-- <CpessionTableEquity fromType="edit" :authList="raiform.authList" :form="1" @selectAuthHandle="getAuthSelect"/> -->
								</el-collapse-item>
							</el-collapse>
						</div>
					</el-form>
				</div>
				<!-- FICC模块 -->
				<div v-if="ficcform">
					<p class="page-title">FICC类型信息</p>
					<el-form
						:model="ficcform"
						:rules="ficcformRule"
						ref="ficcform"
						label-width="100px"
						style="display:flex;flex-wrap:wrap;width:100%"
						:disabled="!canEidtBtns.FiccEdit"
					>
						<el-form-item label="客户状态" style="width:40%">
							<span style="color:#333;font-size: 15px;">{{ficcform.Status}}</span>
						</el-form-item>
						<el-form-item label="所属销售" style="width:26%">
							<span style="color:#333;font-size: 15px;">{{ficcform.SellerName}}</span>
						</el-form-item>
						<el-form-item label="所属行业" prop="IndustryId" style="width:33%">
							<el-select v-model="ficcform.IndustryId" placeholder="请选择行业" style="width:80%;" @focus="slideTrade">
								<el-option
									v-for="item in tradeArr2"
									:key="item"
									:label="item.IndustryName"
									:value="item.IndustryId">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="客户来源" prop="Source" style="width:40%">
							<el-select v-model="ficcform.Source" placeholder="请选择客户来源" style="width:80%;" filterable>
								<el-option
									v-for="item in fromArr"
									:key="item.SourceId"
									:label="item.SourceName"
									:value="item.SourceName">
								</el-option>
							</el-select>
						</el-form-item>
						<!-- <el-form-item label="备注" prop="Reasons" style="width:58%">
							<el-input 
								v-model="ficcform.Reasons" 
								placeholder="请输入备注"
								style="width:92%">
							</el-input>
						</el-form-item> -->
						<div style="width:98%">
							<el-collapse v-model="ficcCollapseOpen"  accordion>
								<el-collapse-item name="1">
									<template slot="title">
										<p style="display:inline-block;font-size:15px;padding-left:32px">
											<span style="font-weight:bold">权限配置 </span>
											<span style="color:#1989FA;display:inline-block;margin-left:10px">{{ficcCollapseOpen=='1'?'收起':'展开'}}</span>
										</p>
									</template>
									<CpessionTable fromType="edit" :authList="ficcform.authList" :form="2" @selectAuthHandle2="getAuthSelect2"/>
								</el-collapse-item>
							</el-collapse>
						</div>
					</el-form>
				</div>

			</div>

			<div style="flex-shrink: 0;">
				<div style="display:flex;justify-content:flex-end;margin:0 0 30px;">
					<el-button type="primary" style="width:80px;marginRight:24px;" @click="saveHandle">保存</el-button>
					<el-button type="primary" plain style="width:80px;" @click="handleCancel">取消</el-button>
				</div>
				<Ctimeline :id="companyId"></Ctimeline>
			</div>
		</div>
		<!-- 联系人 -->
		<div class="editCustom_container" style="marginTop:20px;padding:30px 40px 80px 60px;">
			<div class="customList_bot_top">
				<div>
					<input type="file" size="small" name="file" @change="fileSelected()" id="fileImport" class="true-file" style="display:none;">
					<el-button type="primary" @click="addConcat">添加联系人</el-button>
					<el-button type="primary" @click="importHandle">批量导入</el-button>
					<!-- <span style="fontSize:16px;color:#AAB4CC;">（请至少添加一位联系人）</span> -->
					<a :href="downTemplate" download style="fontSize:14px;color:#409eff;margin-left:30px">下载导入模板</a>
				</div>
				<div style="display: flex">
					<template v-if="!isUserYanXuanButtonShow">
					  <el-select 
						  v-model="IsSubscribe"
						  placeholder="是否关注公众号" 
						  multiple
						  clearable
						  style="margin-right: 10px;width: 300px;" 
						  @change="changeSubscribe"
					  >
						  <el-option 
							  label="已关注弘则研究"
							  value="1"
							  :disabled="IsSubscribe.includes('2')"
						  />
						  <el-option 
							  label="已关注查研观向小助手"
							  value="3"
							  :disabled="IsSubscribe.includes('4')"
						  />
						  <el-option 
							  label="未关注弘则研究"
							  value="2"
							  :disabled="IsSubscribe.includes('1')"
						  />
						  <el-option 
							  label="未关注查研观向小助手"
							  value="4"
							  :disabled="IsSubscribe.includes('3')"
						  />
					  </el-select>
	
					  <el-select v-model="platform_type" style="margin-right: 10px;width: 250px;" @change="changeSubProductHandle">
						  <el-option
							  v-for="item in platformOption"
							  :key="item.key"
							  :label="item.ProductName"
							  :value="item.key"
						  >
							  {{ item.ProductName }}
						  </el-option>
					  </el-select>
					</template>
					  <el-input
						  placeholder="姓名/手机号码/邮箱"
						  v-model="search_txt"
						  style="maxWidth:400px"
						  @input="searchUser"
						  clearable>
						  <i slot="prefix" class="el-input__icon el-icon-search"></i>
					  </el-input>
				</div>
			</div>
			<div class="bot_cont">
				<el-table
				ref="userTable"
				:data="userTable"
				v-loading="isShowloadding"
				:row-class-name="setRowClass"
				element-loading-text="数据加载中..."
				border>
					<el-table-column
					prop="RealName"
					label="姓名"
					align="center">
						<template slot-scope="scope">
							<img :src="$icons.card" alt="" style="width:17px;cursor:pointer;marginRight:5px;"
								v-if="scope.row.BusinessCardUrl"
								@click="reviewCard(scope.row.BusinessCardUrl)">
							<img src="~@/assets/img/icons/like-heart.png" class="name-follow-heart" v-if="scope.row.IsFollow==1">
							<span>{{scope.row.RealName}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="Position" label="职位" align="center" min-width="80px"></el-table-column>
					<el-table-column
					prop="Mobile"
					label="手机号"
					align="center"
					min-width="100">
						<template slot-scope="scope"><span v-if="scope.row.Mobile&&scope.row.CountryCode">{{scope.row.CountryCode}}-</span><span>{{scope.row.Mobile+(scope.row.MobileTwo?'/'+scope.row.MobileTwo:'')}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="Email"
					label="邮箱"
					align="center"
					min-width="120">
						<template slot-scope="scope"> <span>{{scope.row.Email}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="IsMaker"
					label="是否KP"
					align="center">
						<template slot-scope="scope"> <span>{{scope.row.IsMaker==1?'是':'否'}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="IsRegister"
					label="是否注册"
					align="center">
						<template slot-scope="scope"> <span>{{scope.row.IsRegister?'已注册':'未注册'}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="CreatedTime"
					label="注册时间"
					min-width="150"
					align="center">
						<template slot-scope="scope"> <span>{{scope.row.RegisterTime}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="IsSubscribeHzyj"
					label="是否关注公众号"
					min-width="90"
					align="center">
						<template slot-scope="scope">
							<div style="text-align:left" v-if="RoleType !=='权益'">
								<img v-if="scope.row.IsSubscribeHzyj==1" style="width:16px;height:16px" src="~@/assets/img/icons/icon_1.png" alt="">
								<img v-else style="width:16px;height:16px" src="~@/assets/img/icons/icon_2.png" alt="">
								<span>弘则研究</span>
							</div>
							<div style="text-align:left">
								<img v-if="scope.row.IsSubscribeCygx==1" style="width:16px;height:16px" src="~@/assets/img/icons/icon_1.png" alt="">
								<img v-else style="width:16px;height:16px" src="~@/assets/img/icons/icon_2.png" alt="">
								<span>查研观向小助手</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column
					prop="ViewTotal"
					label="累计阅读次数"
					align="center">
						<template slot-scope="scope"> <span>{{scope.row.ViewTotal||'暂无'}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="LastViewTimeStr"
					label="最近一次阅读时间"
					min-width="150"
					align="center">
						<template slot-scope="scope"> <span>{{scope.row.ViewTotal?scope.row.LastViewTimeStr:''}}</span> </template>
					</el-table-column>
					<el-table-column
					label="研报统计"
					align="center">
						<template slot-scope="scope"> <span v-if="scope.row.ViewTotal!=0" class="editsty" @click="lookReport(scope.row)">点击查看</span></template>
					</el-table-column>
					<el-table-column
						v-if="ficcform && !isUserYanXuanButtonShow"
						prop="YbProductViewTotal"
						label="其他统计"
						min-width="110"
						align="center">
						<template slot-scope="scope"> <span :class="scope.row.YbProductViewTotal?'editsty':''" @click="lookReadInfo(scope.row)">{{scope.row.YbProductViewTotal||'0'}}</span> </template>
					</el-table-column>
					<el-table-column label="操作" align="center" min-width="155">
						<template slot-scope="scope">
							<div style="color:#4099ef; font-size:14px;">
								<span class="editsty" @click="editContact(scope.row)">编辑</span>
								<span class="editsty move" style="margin:0 5px;" @click="handleShowMove(scope.row)">移动</span>
								<span style="margin-right:5px;" :class="scope.row.IsFollow==1?'deletesty':'editsty'"
								@click="followContact(scope.row)"
								>{{ scope.row.IsFollow==1?'取消关注':'关注' }}</span>
								<span class="deletesty" @click.stop="delConcat(scope.row)">删除</span>
							</div>
						</template>
					</el-table-column>
					<div slot="empty" style="lineHeight:40px;margin:30px 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="10" 
					:total="total"
					style="float:right;">
					</el-pagination>
				</el-col>
			</div>
		</div>
		<!-- 添加联系人弹窗 -->
		<Contactdia
		:userId="userId"
		:id="companyId"
		:name="defaultName"
		:title="diatit"
		:userForm="diaform"
		:custom_name="diaform.companyName"
		:isAddContact="isAddContact"
		:isEditUser="true"
		:regionType="regionType"
		@cancel="canceldialog">
		</Contactdia>
		<!-- 阅读报告弹窗 -->
		<Readia
		:readId="readId"
		:lookRead="isRead"
		:title="readTit"
		@cancelRead="cancelRead">
		</Readia>
		<!-- 分产品阅读统计弹窗 -->
		<product-read-info
		:productReadInfoShow="productReadInfoShow"
		:productReadId="productReadId"
		:subProductId="platform_type"
		:subProductName="subProductName"
		:clickToal="clickToal"
		:productReadTitle="productReadTitle"
		@close="productReadInfoShow=false"
		></product-read-info>
		<!-- 图片预览 -->
		<el-image-viewer 
		v-if="showViewer" 
		:on-close="closeViewer" 
		:url-list="[imgView]" />
		<!-- 导入的联系人表格 -->
		<el-dialog
		title="批量导入"
		:visible.sync="isShowImportDia"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelImport"
		center
		width="1000px">
			<template  v-if="!isImportRepeat">
				<div style="fontSize:15px;color:#606266;marginBottom:10px;">请确认导入信息（已过滤信息不全的联系人）：</div>
				<el-table :data="importData" border height="350">
					<el-table-column align="center" label="姓名">
						<template slot-scope="scope">{{scope.row.RealName}}</template>
					</el-table-column>
					<el-table-column align="center" label="性别">
						<template slot-scope="scope">{{scope.row.Sex==1?'男':scope.row.Sex==2?'女':''}}</template>
					</el-table-column>
					<el-table-column align="center" label="手机号">
						<template slot-scope="scope">{{scope.row.Mobile?scope.row.CountryCode+'-'+scope.row.Mobile:''}}</template>
					</el-table-column>
					<!-- <el-table-column align="center" label="手机号2">
						<template slot-scope="scope">{{scope.row.MobileTwo||''}}</template>
					</el-table-column> -->
					<el-table-column align="center" label="邮箱">
						<template slot-scope="scope">{{scope.row.Email||''}}</template>
					</el-table-column>
					<el-table-column align="center" label="是否决策人">
						<template slot-scope="scope">{{scope.row.IsMaker==1?'是':'否'}}</template>
					</el-table-column>
					<el-table-column align="center" label="职位">
						<template slot-scope="scope">{{scope.row.Position||''}}</template>
					</el-table-column>
					<el-table-column align="center" label="部门">
						<template slot-scope="scope">{{scope.row.DepartmentName||''}}</template>
					</el-table-column>
				</el-table>
			</template>
			<!-- 重复联系人 -->
			<template v-else>
				<div style="font-size:16px;color:#606266;margin-bottom:10px">导入完成。</div>
				<div style="fontSize:16px;color:#606266;marginBottom:20px;">请单独处理以下系统中已存在的联系人：</div>
				<el-table :data="repeatData" border height="300">
					<el-table-column align="center" label="联系人">
						<template slot-scope="scope">{{scope.row.RealName}}</template>
					</el-table-column>
					<el-table-column  align="center" label="手机号/邮箱" width="300">
						<template slot-scope="scope">
							{{scope.row.Mobile}} 
							{{(scope.row.Mobile&&scope.row.Email)?'/':''}}
							{{scope.row.Email}}
						</template>
					</el-table-column>
					<el-table-column align="center" label="销售">
						<template slot-scope="scope">{{scope.row.SellerRealName}}</template>
					</el-table-column>
					<el-table-column align="center" label="关联客户" min-width="150">
						<template slot-scope="scope">{{scope.row.CompanyName}}</template>
					</el-table-column>
					<el-table-column align="center" label="操作">
						<template slot-scope="scope">
							<el-button type="text" size="small" @click="handleMoveToCurrentCustom(scope.row,scope.$index)" v-if="scope.row.HasMove">移至当前客户</el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>
			<div style="display:flex;justify-content:center;margin:30px 0">
				<template  v-if="!isImportRepeat">
					<el-button type="primary" style="marginRight:24px;" @click="ensureImport">确定</el-button>
					<el-button  type="primary" plain style="width:80px;" @click="cancelImport">取消</el-button>
				</template>
				<el-button type="primary" style="width:100px;" v-else @click="cancelImport(1)">知道了</el-button>
			</div>
		</el-dialog>
		<el-dialog
		:visible.sync="isCheck"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		:show-close="false"
		center
		width="560px">
			<div slot="title" style="display:flex;alignItems:center;">
				<span style="fontSize:16px;">提示</span>
			</div>
			<div style="textAlign:center;fontSize:16px;" v-if="codeRepeat == 1">
				<span v-if='raiform'>该客户属于权益客户，是否领取？</span>
				<span v-if='ficcform'>该客户属于FICC客户，是否领取？</span>
			</div>	
			<div style="textAlign:center;fontSize:16px;" v-else>
				<span>该客户已存在，请前往【客户检索】页面核实</span>
			</div>	
			<div style="display:flex;justify-content:center;margin:75px 0 50px;">
				<el-button type="primary" style="width:80px;marginRight:24px;" @click="goPickHandle">{{codeRepeat == 1 ?'去领取':'去核实'}}</el-button>
				<el-button  type="primary" plain style="width:80px;" @click="closeDia">取消</el-button>
			</div>
		</el-dialog>
		<!-- 移动联系人弹窗 -->
		<el-dialog
			title="提示"
			:visible.sync="isMove"
			:close-on-click-modal="false"
			:modal-append-to-body="false"
			@close="cancelMove"
			center
			top="25vh"
			width="500px">
			<div slot="title" style="display: flex; align-items: center; position: relative">
				<img
					src="../../../assets/img/icons/move.png"
					style="color: #fff; width: 16px; height: 16px; margin-right: 5px"/>
				<span style="font-size: 16px">移动联系人</span>
				<i
					class="el-icon-close"
					style="
						font-size: 24px;
						cursor: pointer;
						position: absolute;
						right: 20px;
						top: 50%;
						transform: translateY(-50%);
					"
					@click="cancelMove"
				></i>
			</div>
			<el-form
				@submit.native.prevent
				:model="moveForm"
				ref="moveFormvalidate"
				inline
				:rules="moveRule"
				label-width="80px"
				class="demo-ruleForm"
				style="margin-top: 15px">
				<el-form-item
					label="移动到"
					prop="companyId"
					style="width: 100%">
					<el-select
						v-model="moveForm.companyId"
						filterable
						remote
						:remote-method="getCompany"
						@focus="focusGetCompany"
						@change="getCompanySeller"
						placeholder="请选择公司"
						style="width: 280px">
						<el-option
							v-for="item in typeArr"
							:key="item.CompanyId"
							:label="item.CompanyName"
							:value="item.CompanyId">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					label="所属销售"
					prop="belongUser"
					style="width: 100%"
					v-if="!hideBelongUser">
					<el-select
						v-model="moveForm.belongUser"
						placeholder="请选择对应销售"
						style="width: 280px">
						<el-option
							v-for="item in belongList"
							:key="item.AdminId"
							:label="item.RealName"
							:value="item.AdminId">
						</el-option>
					</el-select>
				</el-form-item>
				<div v-if="isMoveShowTips&&ficcform&&['正式','试用','永续'].includes(ficcform.Status)" style="text-align:center;color:#999">提示：移动联系人会关闭该联系人的图表权限</div>
				<div style="display: flex; justify-content: center; margin: 30px 0 55px">
					<el-button type="primary" @click="submitMove">保存</el-button>
					<el-button @click="cancelMove">取消</el-button>
				</div>
			</el-form>
		</el-dialog>
	</div>	
</template>

<script>
import Ctimeline from '../compontents/Ctimeline.vue'
import Contactdia from '../compontents/Contactdialog.vue'
import Readia from '../compontents/ReadDialog.vue'
import ProductReadInfo from '../compontents/ProductReadInfo.vue'
import CpessionTable from '../compontents/CpessionTable.vue'
import { customInterence } from '@/api/api.js'
//import{province_sorce,city_sorce} from '@/utils/distpicker';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
// import CpessionTableEquity from '../compontents/CpessionTableEquity.vue'
import autocomplete from "@/components/autocomplete.vue";
import searchDistPicker from '@/components/searchDistPicker.vue';
import country from "@/utils/countryData"

export default {
	name:'',
	components: {Ctimeline,Contactdia,Readia,ProductReadInfo,ElImageViewer,CpessionTable,autocomplete,searchDistPicker},
	computed:{
		Role() {
			let role = localStorage.getItem('Role') || '';
			return role;
		},
		/* 客户类型 */
		typeArr() {
			let type = localStorage.getItem('RoleType') || '';
			if(type == 'ficc') {
				return ['ficc']
			}else if(type == '权益') {
				return ['权益']
			}else {
				return ['ficc','权益']
			}
		}
	},
	// watch: {
	// 	'dataForm.custype': {
	// 		handler() {
	// 			this.getIndustry(1);
	// 		}
	// 	},
	// 	'dataForm2.custype': {
	// 		handler() {
	// 			this.getIndustry(2);
	// 		}
	// 	}
	// },
	data () {
/*     this.province_sorce=province_sorce
    this.city_sorce=city_sorce */
		this.countryData = country
		return {
			isCheck: false,
			canEidtBtns:{},
			raiCollapseOpen:'1',//1展开 0 收起
			ficcCollapseOpen:'1',// 1展开 0 收起
			basicform:'',
			ficcform:"",
			raiform:"",
			optionsMoney:[{value:'1',label:'50亿以下'},{value:'2',label:'50~100亿'},{value:'3',label:'100亿以上'}],
			basicformRule:{
				CompanyName:[{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
				City: [{ required: true, message: "请选择地址", trigger: "change" }],
				CreditCode:[{ required: true, message: '社会信用码不能为空', trigger: 'blur' }],
			},
			raiformRule:{
				IndustryId:[{ required: true, message: "请选择行业", trigger: "change" }],
				Source:[{ required: true, message: "请选择来源", trigger: "change" }]
			},
			ficcformRule:{
				IndustryId:[{ required: true, message: "请选择行业", trigger: "change" }],
				Source:[{ required: true, message: "请选择来源", trigger: "change" }]
			},


			showData:false,
			downTemplate:process.env.API_ROOT+'/custom/template?'+localStorage.getItem('auth')||'',//下载模板
			roleDepart:'',//账号所属部门
			companyList:[],
			activeNames:'1',//默认展开
			companyId:this.$route.query.id,
			dataForm2:null,
			dataForm:{
				area:'',
				CompanyProductId:'',
				custom_name:'',
				code:'',
				province:'',
				city:'',
				cuStatus:'试用',
				custype:'',
				trade:'',
				from:'',
				sales:'',
				addreason:''
			},
			formRule:{
				/* 客户名称 */
				custom_name:[
					{ required: true, message: '公司名称不能为空', trigger: 'blur' },
				],
				/* 社会信用码 */
				code:[
					{ required: true, message: '社会信用码不能为空', trigger: 'blur' },
				],
				/* 客户状态 */
				cuStatus:[
					{ required: true, message: '客户状态不能为空', trigger: 'blur' },
				],
				/* 客户类型 */
				custype:[
					{ required: true, message: '客户类型不能为空', trigger: 'blur' },
				],
				/* 行业 */
				trade:[
					{ required: true, message: '行业不能为空', trigger: 'blur' },
				],
				/* 客户来源 */
				from:[
					{ required: true, message: '客户来源不能为空', trigger: 'blur' },
				],
				/* 销售 */
				sales:[
					{ required: true, message: '所属销售不能为空', trigger: 'blur' },
				],
				/* 备注 */
				// addreason:[
				// 	{ required: true, message: '备注不能为空', trigger: 'blur' },
				// ],
			},
			formRule2:{
				/* 客户名称 */
				// custom_name:[
				// 	{ required: true, message: '客户名称不能为空', trigger: 'blur' },
				// ],
				/* 社会信用码 */
				// code:[
				// 	{ required: true, message: '社会信用码不能为空', trigger: 'blur' },
				// ],
				/* 客户状态 */
				cuStatus:[
					{ required: true, message: '客户状态不能为空', trigger: 'blur' },
				],
				/* 客户类型 */
				custype:[
					{ required: true, message: '客户类型不能为空', trigger: 'blur' },
				],
				/* 行业 */
				trade:[
					{ required: true, message: '行业不能为空', trigger: 'blur' },
				],
				/* 客户来源 */
				from:[
					{ required: true, message: '客户来源不能为空', trigger: 'blur' },
				],
				/* 销售 */
				sales:[
					{ required: true, message: '所属销售不能为空', trigger: 'blur' },
				],
				/* 备注 */
				// addreason:[
				// 	{ required: true, message: '备注不能为空', trigger: 'blur' },
				// ],
			},
			fromArr:[],//客户来源
			tradeArr:[],//行业1
			tradeArr2:[],//行业2
			salesArr:[],//销售列表
			authList:[],//权限列表1
			authList2:[],
			search_txt:'',
			userTable:[],//联系人表格
			total:1,
			page_no:1,
			isAddContact:false,//联系人弹窗
			userId:'',//联系人id
			diaform:{
				companyName:'',
				name:'',
				sex:1,
				telCode:'86',
				tel1:'',
				tel2:'',
				mail:'',
				post:'',
				desiger:'',
				depart:'',
				carte:'',
				Source:'add_user'
			},
			defaultName:'',//默认公司名称
			diatit:'新增联系人',
			isRead:false,//阅读弹窗
			readTit:'阅读报告列表',
			readId:'',
			showViewer:false,
			imgView:'',
			isShowImportDia:false,//导入联系人弹窗
			importData:[],//要导入的信息
			isImportRepeat:false,//导入数据出现重复
			repeatData:[],//重复的联系人
			importParams:null,
			regionType:'',
			/* 表格展示权限 */
			check_auth:[],//勾选1 权益
			check_auth2:[],//勾选2 ficc
			repeatName:'',
			nameRepeat:false,
			codeRepeat:false,
			isCheckCompanyInfo:false,
			checkCompanyfocusIs:false, //

			isUserYanXuanButtonShow:false,//是否显示研选的按钮以及表格
			IsSubscribe:[],//是否关注公众号
			platform_type: 1,
			platformOption:[],
			subProductName: '',//分产品名称
			clickToal:'',//点击量
			productReadInfoShow:false,//分产品阅读统计弹窗
			productReadId:0,//联系人ID
			productReadTitle:'',//分产品阅读统计弹窗的标题

			isMove:false,//移动联系人弹窗
			isMoveShowTips:false,//移动联系人弹窗中是否提示移动联系人将重置图表权限
			moveForm:{
				companyId:'',
				belongUser:''
			},
			moveRule:{
				companyId:[{ required: true, message: "公司不能为空", trigger: "change" }],
				belongUser:[{ required: true, message: "所属销售不能为空", trigger: "change" }]
			},
			belongList:[],//所属销售列表
			typeArr: [], //公司列表
		};
	},
	methods: {
		// 导入联系人弹窗中的移动至当前客户
		handleMoveToCurrentCustom(e,index){
			let SellerId=localStorage.getItem('AdminId')
			let params={
				CompanyId: Number(this.companyId),
				BusinessCardUrl:e.BusinessCardUrl,
				DepartmentName:e.DepartmentName,
				Email:e.Email,
				IsMaker:Number(e.IsMaker),
				Mobile:e.Mobile,
				Position:e.Position,
				RegionType:"",
				RealName:e.RealName,
				Remark:"",
				SellerId:Number(SellerId),
				Sex:Number(e.Sex),
				UserId:Number(e.UserId),
			}
			customInterence.moveUser(params).then(res=>{
				if(res.Ret==200){
					this.$message.success("移动成功！");
					this.repeatData[index].HasMove=false
				}
			})
		},
		//选中后增加社会信用码
		customNameSelect(value) {
			this.basicform.CreditCode = value.CreditCode
			setTimeout(()=>{
				this.checkCompany()
			},10)
		},
		/* 获取客户来源数据 */
		getCustomerSourceList(){
			customInterence.customerSourceList({}).then(res=>{
				if(res.Ret===200){
					this.fromArr=res.Data.List
				}
			})
		},
		/* 获取客户详情信息 */
		getDetail() {
			customInterence.customDetail({
				CompanyId:this.companyId,
				IsEdit:true // 是否时编辑页详情
			}).then(res => {
				if(res.Ret === 200) {
					this.showData = true;
					let ficcform = res.Data.FiccItem;//ficc添加的信息
					let basicform = res.Data.Item;//客户基本信息
					let raiform = res.Data.RaiItem;//权益添加的信息

					this.canEidtBtns={
						FiccEdit:res.Data.BtnItem.FiccEdit,
						RaiEdit:res.Data.BtnItem.RaiEdit,
						BaseInfoEdit:res.Data.BtnItem.BaseInfoEdit
					}
					this.basicform = {...res.Data.Item,CreateAuth:res.Data.CreateAuth};//客户基本信息
					this.ficcform = res.Data.FiccItem;//ficc添加的信息
					this.raiform = res.Data.RaiItem;//权益添加的信息

					// 海外用户 取消基础信息中地址校验
					// 需求修改 海外用户 也需要校验 -- 2022/10/11
					// if(this.basicform.RegionType=='海外'){
					// 	this.basicformRule.City[0].required=false
					// }

					// 处理ficc权限列表格式
					if(res.Data.FiccItem){
						let auth = [];
						res.Data.FiccItem.PermissionList.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,
								...item,
							}
							auth.push(obj)
						})
						console.log(auth);
						this.ficcform={...this.ficcform,authList:auth}
					}
					// 处理权益权限列表格式
					if(res.Data.RaiItem){
						let auth = [];
						res.Data.RaiItem.PermissionList.forEach(item=> {
							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,
							}
							auth.push(obj)
						})
						this.raiform={...this.raiform,authList:auth}
					}

					this.companyStatus=res.Data.CreateAuth == 1?this.ficcform.Status:this.raiform.Status

					this.regionType=basicform.RegionType
					/* 基础表单 */
					this.dataForm = {
						area:basicform.RegionType,
						custom_name:basicform.CompanyName,
						code:basicform.CreditCode,
						province:basicform.Province,
						city:basicform.City,
						CompanyProductId:res.Data.CreateAuth == 1?ficcform.CompanyProductId:raiform.CompanyProductId,
						cuStatus:res.Data.CreateAuth == 1?ficcform.Status:raiform.Status,
						custype:res.Data.CreateAuth == 1?ficcform.ProductName:raiform.ProductName,
						trade:res.Data.CreateAuth == 1?ficcform.IndustryId:raiform.IndustryId,
						from:res.Data.CreateAuth == 1?ficcform.Source:raiform.Source,
						sales:res.Data.CreateAuth == 1?ficcform.SellerId:raiform.SellerId,
						addreason:res.Data.CreateAuth == 1?ficcform.Reasons:raiform.Reasons
					}
					if(res.Data.CreateAuth == 1) { //ficc创建客户
						/* 处理权限列表格式 */
						let auth = [];
						ficcform.PermissionList.forEach(item=> {
							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,
							}
							auth.push(obj)
						})
						this.authList = auth;
						// 
						if(raiform) {
							this.dataForm2 = {
								CompanyProductId:raiform.CompanyProductId,
								cuStatus:raiform.Status,
								custype:raiform.ProductName,
								trade:raiform.IndustryId,
								from:raiform.Source,
								sales:raiform.SellerId,
								addreason:raiform.Reasons
							}
							/* 处理权限列表格式 */
							let auth2 = [];
							raiform.PermissionList.forEach(item=> {
								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,
								}
								auth2.push(obj)
							})
							this.authList2 = auth2;
						}
					}else if (res.Data.CreateAuth == 2){ //权益创建客户
						// /* 基础表单 */
						// this.dataForm = {
						// 	custom_name:basicform.CompanyName,
						// 	code:basicform.CreditCode,
						// 	province:basicform.Province,
						// 	city:basicform.City,
						// 	cuStatus:raiform.Status,
						// 	custype:'权益',
						// 	trade:raiform.IndustryId,
						// 	from:raiform.Source,
						// 	sales:raiform.SellerName,
						// 	addreason:raiform.Reasons
						// }
						/* 处理权限列表格式 */
						let auth = [];
						raiform.PermissionList.forEach(item=> {
							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,
							}
							auth.push(obj)
						})
						this.authList = auth;
						//
						if(ficcform) {
							this.dataForm2 = {
								CompanyProductId:ficcform.CompanyProductId,
								cuStatus:ficcform.Status,
								custype:ficcform.ProductName,
								trade:ficcform.IndustryId,
								from:ficcform.Source,
								sales:ficcform.SellerId,
								addreason:ficcform.Reasons
							};
							/* 处理权限列表格式 */
							let auth2 = [];
							ficcform.PermissionList.forEach(item=> {
								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,
								}
								auth2.push(obj)
							})
							this.authList2 = auth2;
						}
					}

					this.isUserYanXuanButtonShow = res.Data.IsUserYanXuanButtonShow
				}
			})
		},
		async callbackHandle(data,cb) {
		 if (this.basicform.CompanyName) {
			 this.isCheckCompanyInfo = true;
					cb([]);
					let res = await customInterence.companyQccSearch({ KeyWord: this.basicform.CompanyName});
					if (res.Ret === 200) {
					this.isCheckCompanyInfo = false;
					if (res.Data && res.Data.length > 0) {
						let arr = res.Data.map((item) => {
						return { value:item.Name, ...item };
						});
						cb(arr);
					}else{
						cb([{}]);
						this.checkCompany()
					}
				}
			}
		},
		checkCompanyfocus(){
			this.checkCompanyfocusIs =true;
			setTimeout(() => {
			this.checkCompanyfocusIs =false;
			},500)
		},
		/* 客户名称/信用码失焦时校验客户名称是否存在 存在就提示 */
		checkCompany() {
		 setTimeout(()=>{
			 if(this.checkCompanyfocusIs) return;
			 if((!this.basicform.CompanyName && !this.basicform.CreditCode) || (this.isCheckCompanyInfo && this.basicform.CompanyName)) return
			customInterence.checkCompanyInfo({
				CompanyName:this.basicform.CompanyName,
				CreditCode:this.basicform.CreditCode
			}).then(res =>{
					if(res.Ret === 200){
					if(res.Data.RepeatStatus > 0) {
						this.repeatId = res.Data.CompanyId;
				 		this.repeatName = res.Data.ProductName;
						this.nameRepeat = res.Data.RepeatStatus
						this.codeRepeat = res.Data.Status
						this.isCheck = true;
					}else {
						this.nameRepeat = 0
						this.isCheck = false;
					}
				}
			})
		 },500)
		},
		lookReadInfo(item){
			if(!item.YbProductViewTotal) return 
			this.productReadId = item.UserId
			this.productReadTitle = item.RealName + '其他统计'
			this.clickToal = item.YbProductViewTotal
			this.productReadInfoShow = true
		},
		/* 获取分产品的几种类型 */
		getSubProductList() {
			customInterence.getSubProduct({StatisticFlag:true}).then(res => {
				if(res.Ret !== 200) return
				
				res.Data.forEach(item => {
					item.key = `${item.ProductType}-${item.ProductId}`
				})
				this.platformOption = res.Data;
				this.platform_type = `${res.Data[0].ProductType}-${res.Data[0].ProductId}`;
				this.subProductName = res.Data[0].ProductName;
				
				this.getuserTable();
			})
		},
		changeSubProductHandle(val) {
			this.search_txt = '';
			let obj = this.platformOption.find(_ =>_.key === val);
			this.subProductName = obj.ProductName;
			this.getuserTable();
		},
		changeSubscribe(){
			this.search_txt = '';
			this.getuserTable();
		},
		// 关注与取消关注
		followContact(row){
			// console.log(row);
			let isFollow = row.IsFollow==1
			let confirmText = isFollow?'是否取消':'是否设为'
			this.$confirm(`${confirmText}特别关注？`, "提示", {
				type: "warning",
			}).then(() => {
				let params={
					UserId:row.UserId,
					CompanyId:row.CompanyId,
					Type:isFollow?0:1
				}
				customInterence.concactFollow(params).then(res=>{
					if(res.Ret == 200){
						this.$message.success(isFollow?"取消成功":"关注成功")
						this.getuserTable()
					}
				})

			})
			.catch(() => {});
		},
		/* 获取联系人列表 */
		getuserTable() {
			const subProductArr = this.platform_type.split('-');
			customInterence.concactList({
				PageSize:10,
				CurrentIndex:this.page_no,
				CompanyId:this.companyId,
				KeyWord:this.search_txt,
				ProductType: Number(subProductArr[0]),
				ProductId: Number(subProductArr[1]),
				IsSubscribeHzyj:this.IsSubscribe.includes('1')?1:this.IsSubscribe.includes('2')?0:'',
				IsSubscribeCygx:this.IsSubscribe.includes('3')?1:this.IsSubscribe.includes('4')?0:'',
			}).then(res => {
				
				if(res.Ret === 200) {
					this.userTable = res.Data.List || [];
					this.total = res.Data.Paging.Totals
				}else {
					this.userTable = []
				}
			})
		},
		/* 获取客户名称 */
		getCompany(query) {
			if(query) {
				customInterence.companySearch({
					KeyWord:query
				}).then(res =>{
					if(res.Ret === 200) {
						let arr = [];
						res.Data.List&&res.Data.List.forEach(item => {
							let obj = {
								...item,
								value:item.CompanyName
							}
							arr.push(obj)
						})
						this.companyList = arr;
					}
				})
			}else {
				this.companyList = []
			}
		},
		// callbackHandle(data,cb) {
			
		// 	let results = data ? this.companyList.filter(item => {
		// 		return item.value.includes(data);
		// 	}) : this.companyList;
        //  clearTimeout(this.timeout);
        //  this.timeout = setTimeout(() => {
        //  	cb(results);
        //  }, 300);
		// },
		/* 获取销售 */
		getSale() {
			customInterence.saleslist().then(res => {
				if(res.Ret === 200) {
					this.salesArr = res.Data.List;
				}
			})
		},
		/* 根据类型获取行业 */
		getIndustry(type) {
			customInterence.getindustry({
				Classify:type
			}).then(res => {
				if(res.Ret === 200) {
					if(type=='权益') {
						this.tradeArr = res.Data.List || [];
					}else {
						this.tradeArr2 = res.Data.List || [];
					}
				}
			})
		},
		/* 选择行业先校验是否选择了客户类型提示  */
		slideTrade(e) {
			if(!this.dataForm.custype) {
				this.$message.warning('请先选择客户类型！')
			}
		},
		/* 保存 */
		async saveHandle() {
			try {
				let valid1=await this.$refs.basicform.validate()
				if(!valid1) return
				if(this.raiform){
					let valid2=await this.$refs.raiform.validate()
					if(!valid2) return
				}
				if(this.ficcform){
					let valid3=await this.$refs.ficcform.validate()
					if(!valid3) return
				}
				this.dealedit()
			} catch (error) {
				console.log(error);
			}
			
			// this.$refs.dataForm.validate((valid) => {
			// 	if (valid) {
			// 		if(this.dataForm2) {
			// 			this.$refs.dataForm2.validate((valid) => {
			// 				if (valid) {
			// 					this.dealedit()
			// 				}
			// 			})		
			// 		}else {
			// 			this.dealedit()
			// 		}
					
			// 	}
			// })
		},
		/* 取消 */
		handleCancel(){
			if(window.history.length>1){
				this.$router.go(-1)
			}else{
				this.$router.push({path:'/customList'})
			}
		},
		dealedit() {
			/* 处理公用客户表单 */
			let params_arr = [];
			/* 处理权限列表 */
			const { FiccEdit,RaiEdit  } = this.canEidtBtns;

			if(this.raiform && RaiEdit){
				let PermissionIds=this.check_auth.join(',')
				let obj={
					CompanyProductId:this.raiform.CompanyProductId,
					CompanyType:this.raiform.ProductName,
					IndustryId:this.raiform.IndustryId,
					PermissionIds:PermissionIds,
					Reasons:this.raiform.Reasons,
					SellsId:this.raiform.SellerId,
					Source:this.raiform.Source,
					Status:this.raiform.Status,
					Scale:this.raiform.Scale
				}
				params_arr.push(obj)
			}
			if(this.ficcform && FiccEdit){
				let PermissionIds=this.check_auth2.join(',')
				let obj={
					CompanyProductId:this.ficcform.CompanyProductId,
					CompanyType:this.ficcform.ProductName,
					IndustryId:this.ficcform.IndustryId,
					PermissionIds:PermissionIds,
					Reasons:this.ficcform.Reasons,
					SellsId:this.ficcform.SellerId,
					Source:this.ficcform.Source,
					Status:this.ficcform.Status
				}
				params_arr.push(obj)
			}



			let params = {
				CompanyId:Number(this.companyId),
				City:this.basicform.City,
				Province:this.basicform.Province,
				CompanyName:this.basicform.CompanyName,
				CreditCode:this.basicform.CreditCode,
				Products:params_arr,
				Nation:this.basicform.RegionType==='海外'?this.basicform.Nation:''
			}
			
			customInterence.customEdit(params).then(res => {
				if(res.Ret === 200) {
					this.$message.success(res.Msg);
					if(window.history.length>1){
						this.$router.go(-1)
					}else{
						this.$router.push({path:'/customList'})
					}
					
				}else {

				}
			})
		},
		/* 搜索联系人 */
		searchUser() {
			this.page_no = 1;
			this.getuserTable();
		},
		/* 新增联系人 */
		addConcat() {
			this.diaform.companyName = this.dataForm.custom_name;
			this.defaultName = this.dataForm.custom_name;
			this.isAddContact = true;
			this.diatit = '新增联系人';
		},
		/* 编辑联系人 */
		editContact(item) {
			this.defaultName = item.CompanyName;
			this.diaform = {
				companyName:item.CompanyName,
				name:item.RealName,
				sex:item.Sex,
				telCode:item.CountryCode,
				tel1:item.Mobile,
				tel2:item.MobileTwo||'',
				mail:item.Email||'',
				post:item.Position||'',
				desiger:item.IsMaker,
				depart:item.DepartmentName,
				carte:item.BusinessCardUrl,
				telQY:item.Mobile,
				mailQY:item.Email

			}
			this.userId = item.UserId;
			this.isAddContact = true;
			this.diatit = '编辑联系人';
		},
		/* 删除联系人 */
		async delConcat(item) {
			//删除前的判断 试用、正式、冻结、永续状态下的客户 如只剩一个联系人不允许删除
			let totalRes=await customInterence.companyUserTotal({CompanyId:this.companyId})
			if(totalRes.Ret===200){
				if(totalRes.Data.Total<=1&&(this.companyStatus=='试用'||this.companyStatus=='正式'||this.companyStatus=='永续'||this.companyStatus=='冻结')){
					this.$confirm('当前只有一个联系人，无法删除','提示',{
						confirmButtonText: '知道了',
						showCancelButton:false,
						type: 'warning',
					})
					return
				}
			}else{
				return
			}

			this.$confirm('是否确认删除该联系人吗?','提示',{
				type:'warning'
			}).then(() => {
				customInterence.concactDel({
					UserId:item.UserId
				}).then(res => {
					if(res.Ret === 200) {
						this.$message.success(res.Msg);
						this.page_no = 1;
						this.getuserTable();
						// let index = this.userTable.indexOf(item);
						// this.userTable.splice(index,1);
						// this.total = this.total-1;
					}
				})
			}).catch(() => {});
		},
		/* 关闭联系人弹窗 */
		canceldialog(type) {
			this.isAddContact = false;
			this.defaultName = this.dataForm.custom_name;
			this.diaform = {
				companyName:this.dataForm.custom_name,
				sex:1,
				telCode:'86',
				tel1:'',
				tel2:'',
				mail:'',
				post:'',
				desiger:'',
				depart:'',
				carte:''
			}
			if(type==1) {
				this.getuserTable();
			}
		},
		//获取公司对应的销售列表
		getCompanySeller(){
			this.moveForm.belongUser=null
			customInterence.companySellerList({CompanyId:Number(this.moveForm.companyId)}).then(res=>{
				if(res.Ret===200){
				if(!res.Data.List){
					this.hideBelongUser=true
					this.moveRule.belongUser[0].required=false
					return
				}
				if(res.Data.List.length===1){
					this.moveForm.belongUser=res.Data.List[0].AdminId
				}
				this.belongList=res.Data.List
				this.moveRule.belongUser[0].required=true
				this.hideBelongUser=false
				}
			})
		},
		//显示移动联系人弹窗
		handleShowMove(e){
			this.userId = e.UserId;
			this.isMoveShowTips=e.IsChartPermissionSetting==0?false:true
			this.isMove=true
		},
		//关闭移动联系人弹窗
		cancelMove(){
			this.isMove=false
			this.isMoveShowTips=false
			this.hideBelongUser=false
			this.moveForm.companyId=''
			this.moveForm.belongUser=''
			this.moveRule.belongUser[0].required=true
			this.$refs.moveFormvalidate.resetFields();
		},
		//提交移动联系人
		submitMove(){
			this.$refs.moveFormvalidate.validate((valid,key)=>{
				if(!valid) return
				console.log(this.moveForm.companyId,this.moveForm.belongUser,this.userId);
				customInterence
				.moveCustom({
					CompanyId:Number(this.moveForm.companyId),
					SellerId:Number(this.moveForm.belongUser)||0,
					UserId:Number(this.userId)
				}).then(res=>{
					if(res.Ret===200){
						this.$message.success('移动成功');
						this.$router.go(0)
					}
				})
			})
		},
		focusGetCompany() {
			customInterence
			.companySearch({
				KeyWord: "##",
			})
			.then((res) => {
				if (res.Ret === 200) {
					this.typeArr = res.Data.List || [];
				}
			});
		},
		/* 过滤公司 */
		getCompany(query) {
			if (query) {
				customInterence
				.companySearch({
					KeyWord: query,
				})
				.then((res) => {
					if (res.Ret === 200) {
					this.typeArr = res.Data.List || [];
					}
				});
			} else {
				this.typeArr = [];
			}
		},
		/* 页码改变 */
		handleCurrentChange(page) {
			this.page_no = page;
			this.getuserTable();
		},
		
		//选地地区时 选则的省份改变重置city为空
		provinceChange(){
			this.basicform.City=''
		},

		//选择地区
		selectRegion(e) {
			this.basicform.Province =e.province.value=='省'?'':e.province.value;
			this.basicform.City = e.city.value=='市'?'':e.city.value;
		},

		/* 查看阅读报告列表 */
		lookReport(item) {
			this.readId = item.UserId;
			this.readTit = item.RealName+'阅读报告列表';
			this.isRead = true;
		},
		/* 关闭阅读报告弹窗 */
		cancelRead() {
			this.readTit = '阅读报告列表';
			this.isRead = false;
		},
		/* 预览名片 */
		reviewCard(card) {
			this.showViewer = true;
			this.imgView = card;
		},
		/* 关闭预览 */
		closeViewer() {
			this.imgView = '';
			this.showViewer = false;
		},
		/* 导入联系人打开弹窗 */
		async importHandle() {
			let totalRes=await customInterence.companyUserTotal({CompanyId:this.companyId})
			if(totalRes.Ret===200){
				if(totalRes.Data.Total>=1) {
					$('#fileImport').click();
				}else {
					this.$message.error('请先至少添加一位名片联系人')
				}
			}else{
				this.$message.error(totalRes.ErrMsg)
			}
			
		},
		/* 关闭导入弹窗 */
		cancelImport(type) {
			this.isShowImportDia = false;
			this.isImportRepeat = false;
			this.importData = [];
			this.repeatData = [];
			this.importParams = null;
			if(type == 1) {
				this.getuserTable();
			}
		},
		// 获取文件上传的数据
		fileSelected(type){
			const that = this;
		   if( document.getElementById('fileImport').files[0] ){
		      let hostfile = document.getElementById('fileImport').files[0];
		      let size = Math.floor(hostfile.size / 1024 / 1024);
		      if( size>200 ){
		            that.$message.error('上传文件大小不能大于200M！');
		            hostfile = {};
		            return false
		      }
		      if( hostfile.name.toLowerCase().includes('.xlsx')){
		      	let form = new FormData();
		        	form.append('File',hostfile);  //hostfile.name
					form.append('CompanyId',that.companyId);
				
					customInterence.getimportList(form).then((res) => {
						if( res.Ret === 200 ){
							// that.isShowImportDia = true;
							// that.importParams = form;
							// that.importData = res.Data || [];
							if(res.Data.RepeatUser.length>0){
								this.$confirm('excel表中存在重复手机号，请去重后，重新导入','提示',{
									confirmButtonText: '知道了',
									showCancelButton:false,
									type: 'warning'
								})
							}else{
								that.isShowImportDia = true;
								that.importParams = form;
								that.importData = res.Data.ValidUser || [];
							}
						}
						$("#fileImport").val('');
						hostfile = {};
					});
				}else{
					that.$message.error('请上传.xlsx的文件格式！');
		      }
		   } 
		},
		/* 确认导入联系人 */
		ensureImport() {
			customInterence.importUser(this.importParams).then(res => {
				if(res.Ret === 200) {
					this.$message.success('导入成功');
					this.cancelImport(1);
				}else if(res.Ret === 600) {
					this.cancelImport();
					this.isShowImportDia = true;
					this.isImportRepeat = true;
					this.repeatData = res.Data;
				}
			})
		},
		/* 获取1选中的权限列表key */
		getAuthSelect(keys) {
			this.check_auth = keys;
		},
		/* 获取2选中的权限列表key */
		getAuthSelect2(keys) {
			this.check_auth2 = keys;
		},
		/* 选择全选或取消全选 */
		handleCheckAll(item) {
			// 取到所有的子菜单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;
			item.checkAll = len === item.Items.length;
			item.isIndeterminate = len > 0 && len < item.Items.length;
		},
			/* 去领取 */
		goPickHandle() {
			this.$router.push({
				path:'/customSearch',
				query:{
					name: this.nameRepeat == 2 ? this.basicform.CompanyName :'',
					code: this.nameRepeat == 1 ?   this.basicform.CreditCode : '' 
				}
			})
		},
		/* 关闭检查弹窗 */
		closeDia() {
			this.isCheck = false;
		},
		// 设置表格行的样式
		setRowClass({row}){
			if(row.NotRead && row.IsFollow==1){
				return "not-read-seven-days"
			}
		}
	},
	created() {},
	mounted() {
		this.getDetail();
		this.getSale();
		this.getCustomerSourceList()
		this.getIndustry('ficc')
		this.getIndustry('权益')
		this.roleDepart = localStorage.getItem('RoleType') || '';
		this.getSubProductList()
		this.getuserTable();
	},
}
</script>
<style lang='scss'>
.el-icon-arrow-right:before{
	color: #1989FA;
}
.page-title{
	font-size: 16px;
	font-weight: bold;
	color: #333;
	height: 40px;
	line-height: 40px;
	padding-left: 10px;
	background: #F0F2F5;
	margin-bottom: 40px;
}
.editCustom_container {
	// box-sizing: border-box;
	// min-height: calc(100vh - 160px);
	padding:30px 40px 60px 60px;
	background: #fff;
	position: relative;
	border: 1px solid #ECECEC;
	border-radius: 4px;
	box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	font-size: 16px;
	color: #666;
	/* reset */
	.el-form-item {
		margin-bottom: 30px;
		
		.el-form-item__label{
			font-size: 15px;
		}
		&:last-child {
			margin-bottom: 0;
		}
	}
	.el-collapse {
		border: none;
	}
	.el-collapse-item__header {
		display: block;
		border: none;
		font-size: 16px;
		color: #333;
	}
	.el-collapse-item__wrap {
		border: none;
	}
	.textarea_item .el-form-item__content {
		width: 100%;
	}
	.el-form-item__content .menu_item {
		line-height: 20px;
	}
	.distpicker-address-wrapper select {
		width: 45%;
	}
	/*  */
	.menu_lists {
		padding: 40px 18px;
		border: 1px dashed #AAB4CC;
		border-radius: 4px;
		.menu_item {
			display: flex;
			// align-items: center;
			margin-bottom: 30px;
			&:last-child {
				margin-bottom: 0;
			}
			.list_item {
				margin-right: 30px;
				margin-bottom: 10px;
				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
	.customList_bot_top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 28px;
	}
	.name-follow-heart{
		width:25px;
		height: 15px;
		position: absolute;
		left: 0;
		top: 0;
	}
	.not-read-seven-days{
		background-color: #FFF8F8;
	}
}
.el-autocomplete-suggestion-data-entry {
	width:auto !important;
}
.el-autocomplete-none {
	display: none !important;
}
.autocomplete-input {
.el-input__inner {
	padding-right:65px ;
	}
	input {
	overflow: hidden; // 溢出隐藏
 	text-overflow: ellipsis; // 显示省略号
 	white-space: nowrap; // 不换行
	}	
}
</style>