<script setup>
import { ref,computed,reactive } from 'vue'
import $ from 'jquery'
import { ElImageViewer, ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Ctimeline from './components/Ctimeline.vue'
import Contactdia from './components/Contactdialog.vue'
import Readia from './components/ReadDialog.vue'
import CpessionTable from './components/CpessionTable.vue'
import { customInterence } from '@/api/api.js'
// import autocomplete from "@/components/autocomplete.vue";
import searchDistPicker from '@/components/searchDistPicker.vue';
import country from "@/utils/countryData"
import { useList,useReadia } from './hooks/customlistHook'
import { useRoute, useRouter } from 'vue-router'


const $router = useRouter()
const $route = useRoute()
const { Role,RoleType } = useList()

const { readId, isRead, cancelRead, lookReport, readTit } = useReadia()

//下载模板
const downTemplate = computed(() => {
	return import.meta.env.VITE_APP_API_ROOT+'/custom/template?'+localStorage.getItem('auth')||''
}) 

const optionsMoney = [
  {value:'1',label:'50亿以下'},{value:'2',label:'50~100亿'},{value:'3',label:'100亿以上'}
]
const	basicformRule = {
  CompanyName:[{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  City: [{ required: true, message: "请选择地址", trigger: "change" }],
  CreditCode:[{ required: true, message: '社会信用码不能为空', trigger: 'blur' }],
}
const raiformRule = {
  IndustryId:[{ required: true, message: "请选择行业", trigger: "change" }],
  Source:[{ required: true, message: "请选择来源", trigger: "change" }]
}
const ficcformRule = {
  IndustryId:[{ required: true, message: "请选择行业", trigger: "change" }],
  Source:[{ required: true, message: "请选择来源", trigger: "change" }]
}


const countryData = country;
const typeArr = computed(() => {
	let type = localStorage.getItem('RoleType') || '';
	if(type == 'ficc') {
		return ['ficc']
	}else if(type == '权益') {
		return ['权益']
	}else {
		return ['ficc','权益']
	}
})


const companyId = ref(Number($route.query.id))
const showData = ref(false)
const canEidtBtns = ref({})
const basicform = ref(null)
const ficcform = ref(null)
const raiform = ref(null)
const companyStatus = ref('')
const regionType = ref('')
const authList = ref([])
const	raiCollapseOpen = ref('1')//1展开 0 收起
const	ficcCollapseOpen = ref('1')// 1展开 0 收起
/* 获取客户详情信息 */
function getDetail() {
  customInterence.customDetail({
    CompanyId:companyId.value,
    IsEdit:true // 是否时编辑页详情
  }).then(res => {
    if(res.Ret === 200) {
      showData.value = true;

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

      // 处理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);
        ficcform.value={...ficcform.value,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)
        })
        raiform.value={...raiform.value,authList:auth}
      }

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

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


const fromArr = ref([])
/* 获取客户来源数据 */
function getCustomerSourceList(){
  customInterence.customerSourceList({}).then(res=>{
    if(res.Ret===200){
      fromArr.value=res.Data.List
    }
  })
}
getCustomerSourceList()


const tradeArr = ref([])//行业1
const tradeArr2 = ref([])//行业2
/* 根据类型获取行业 */
function getIndustry(type) {
  customInterence.getindustry({
    Classify:type
  }).then(res => {
    if(res.Ret === 200) {
      if(type=='权益') {
        tradeArr.value = res.Data.List || [];
      }else {
        tradeArr2.value = res.Data.List || [];
      }
    }
  })
}
getIndustry('ficc')
getIndustry('权益')


const search_txt = ref('')
const	userTable = ref([])//联系人表格
const	total = ref(1)
const	page_no = ref(1)
const	isAddContact = ref(false)//联系人弹窗
const defaultName = ref('')//默认公司名称
const	diatit = ref('新增联系人')
const userId = ref(0)//联系人id
const diaform = ref({
  companyName:'',
  name:'',
  sex:1,
  telCode:'86',
  tel1:'',
  tel2:'',
  mail:'',
  post:'',
  desiger:'',
  depart:'',
  carte:'',
  Source:'add_user'
})
/* 获取联系人列表 */
function getuserTable() {
  customInterence.concactList({
    PageSize:10,
    CurrentIndex:page_no.value,
    CompanyId:companyId.value,
    KeyWord:search_txt.value
  }).then(res => {
    
    if(res.Ret === 200) {
      userTable.value = res.Data.List || [];
      total.value = res.Data.Paging.Totals
    }else {
      userTable.value = []
    }
  })
}
getuserTable()
/* 页码改变 */
function handleCurrentChange(page) {
  page_no.value = page;
  getuserTable();
}
/* 搜索联系人 */
function searchUser() {
  page_no.value = 1;
  getuserTable();
}
/* 新增联系人 */
function addConcat() {
  diaform.value.companyName = dataForm.value.custom_name;
  defaultName.value = dataForm.value.custom_name;
  isAddContact.value = true;
  diatit.value = '新增联系人';
}
/* 编辑联系人 */
function editContact(item) {
  defaultName.value = item.CompanyName;
  diaform.value = {
    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

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

  ElMessageBox.confirm('是否确认删除该联系人吗?','提示',{
    type:'warning'
  }).then(() => {
    customInterence.concactDel({
      UserId:item.UserId
    }).then(res => {
      if(res.Ret === 200) {
        ElMessage.success(res.Msg);
        page_no.value = 1;
        getuserTable();
      }
    })
  }).catch(() => {});
}



const isShowImportDia = ref(false)//导入联系人弹窗
const importData = ref([])//要导入的信息
const isImportRepeat = ref(false)//导入数据出现重复
const repeatData = ref([])//重复的联系人
const importParams = ref(null)
// 导入联系人弹窗中的移动至当前客户
function handleMoveToCurrentCustom(e,index){
  let SellerId=localStorage.getItem('AdminId')
  let params={
    CompanyId: Number(companyId.value),
    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){
      ElMessage.success("移动成功！");
      repeatData.value[index].HasMove=false
    }
  })
}
/* 导入联系人打开弹窗 */
async function importHandle() {
  let totalRes=await customInterence.companyUserTotal({CompanyId:companyId.value})
  if(totalRes.Ret===200){
    if(totalRes.Data.Total>=1) {
      $('#fileImport').click();
    }else {
      ElMessage.error('请先至少添加一位名片联系人')
    }
  }else{
    ElMessage.error(totalRes.ErrMsg)
  }
  
}
/* 关闭导入弹窗 */
function cancelImport(type) {
  isShowImportDia.value = false;
  isImportRepeat.value = false;
  importData.value = [];
  repeatData.value = [];
  importParams.value = null;
  if(type == 1) {
    getuserTable();
  }
}
// 获取文件上传的数据
function fileSelected(type){
    if( document.getElementById('fileImport').files[0] ){
      let hostfile = document.getElementById('fileImport').files[0];
      let size = Math.floor(hostfile.size / 1024 / 1024);
      if( size>200 ){
            ElMessage.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 ){
            
              if(res.Data.RepeatUser.length>0){
                ElMessageBox.confirm('excel表中存在重复手机号，请去重后，重新导入','提示',{
                  confirmButtonText: '知道了',
                  showCancelButton:false,
                  type: 'warning'
                })
              }else{
                isShowImportDia.value = true;
                importParams.value = form;
                importData.value = res.Data.ValidUser || [];
              }
            }
            $("#fileImport").val('');
            hostfile = {};
          });
      }else{
        ElMessage.error('请上传.xlsx的文件格式！');
      }
    } 
}
/* 确认导入联系人 */
function ensureImport() {
  customInterence.importUser(importParams.value).then(res => {
    if(res.Ret === 200) {
     ElMessage.success('导入成功');
      cancelImport(1);
    }else if(res.Ret === 600) {
      cancelImport();
      isShowImportDia.value = true;
      isImportRepeat.value = true;
      repeatData.value = res.Data;
    }
  })
}
	/* 关闭联系人弹窗 */
function canceldialog(type) {
  isAddContact.value = false;
  defaultName.value = dataForm.value.custom_name;
  diaform.value = {
    companyName:dataForm.value.custom_name,
    sex:1,
    telCode:'86',
    tel1:'',
    tel2:'',
    mail:'',
    post:'',
    desiger:'',
    depart:'',
    carte:''
  }
  if(type==1) {
    getuserTable();
  }
}



const dataForm = reactive({
	area:'国内',
	custom_name:'',
	code:'',
	province:'',
	city:'',
	cuStatus:'试用',
	custype:typeArr.value[0]||'',
	trade:'',
	from:'',
	sales:Number(localStorage.getItem('AdminId')) || 0,
	addreason:'',
	money:''
})
const companyList = ref([])
const checkCompanyfocusIs = ref(false) 
const isCheckCompanyInfo = ref(false) //
const isCheck = ref(false)//检查客户弹窗
const repeatId = ref('')//重复公司id
const repeatName = ref('')//重复公司类型
const nameRepeat = ref(false)
const codeRepeat = ref(false)
const codeDisable = ref(false)//是否可编辑社会信用码国内可
/* 获取客户名称 */
function getCompany(query) {
	if(query) {
		customInterence.companySearch({
			KeyWord:query
		}).then(res =>{
			if(res.Ret === 200) {
				let arr = [];
				if(res.Data.List) {
					res.Data.List.forEach(item => {
						let obj = {
							...item,
							value:item.CompanyName
						}
						arr.push(obj)
					})
				}
				companyList.value = arr;
			}
		})
	}else {
		companyList.value = []
	}
}
function checkCompanyfocus(){
	checkCompanyfocusIs.value =true;
	setTimeout(() => {
	checkCompanyfocusIs.value =false;
	},500)
}
/* 客户名称/信用码失焦时校验客户名称是否存在 存在就提示 */
function checkCompany() {	
	setTimeout(()=>{
	if(checkCompanyfocusIs.value) return
	if((!basicform.value.CompanyName && !basicform.value.CreditCode) || (isCheckCompanyInfo.value && basicform.value.CompanyName )) return
	customInterence.checkCompanyInfo({
		CompanyName:basicform.value.CompanyName,
		CreditCode:basicform.value.CreditCode
	}).then(res =>{
		if(res.Ret === 200){
			if(res.Data.RepeatStatus > 0) {
				repeatId.value = res.Data.CompanyId;
				repeatName.value = res.Data.ProductName;
				nameRepeat.value = res.Data.RepeatStatus
				codeRepeat.value = res.Data.Status
				isCheck.value = true;
			}else {
				nameRepeat.value = 0
				isCheck.value = false;
			}
		}
	})
	},500)
}
/* 关闭检查弹窗 */
function closeDia() {
	repeatId.value = '';
	repeatName.value = '';
	isCheck.value = false;
}
async function callbackHandle(data,cb) {
	if (basicform.value.CompanyName) {
		isCheckCompanyInfo.value =true
		cb([]);
		let res = await customInterence.companyQccSearch({ KeyWord: basicform.value.CompanyName});
		if (res.Ret === 200) {
			isCheckCompanyInfo.value =false;
			if (res.Data && res.Data.length > 0) {
				let arr = res.Data.map((item) => {
				  return { value:item.Name, ...item };
				});
				cb(arr);
			}else{
				cb([{}]);
				checkCompany()
			}	
		}	
	}
}
//选中后增加社会信用码
function customNameSelect(value) {
	basicform.value.CreditCode = value.CreditCode
	setTimeout(async()=>{
			checkCompany()
	},10)
}


/* 选择行业先校验是否选择了客户类型提示  */
function slideTrade(e) {
  if(!dataForm.value.custype) {
    ElMessage.warning('请先选择客户类型！')
  }
}


const basicformRef = ref(null)
const raiformRef = ref(null)
const ficcformRef = ref(null)
/* 保存 */
async function saveHandle() {
  try {
    let valid1=await basicformRef.value.validate()
    if(!valid1) return
    if(raiform.value){
      let valid2=await raiformRef.value.validate()
      if(!valid2) return
    }
    if(ficcform.value){
      let valid3=await ficcform.value.validate()
      if(!valid3) return
    }
    dealedit()
  } catch (error) {
  }

}
/* 取消 */
function handleCancel(){
  if(window.history.length>1){
    $router.go(-1)
  }else{
    $router.push({path:'/customList'})
  }
}
function dealedit() {
    /* 处理公用客户表单 */
    let params_arr = [];
    /* 处理权限列表 */
    const { FiccEdit,RaiEdit  } = canEidtBtns.value;

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


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


const check_auth = ref([])//勾选1 权益
const	check_auth2 = ref([])//勾选2 ficc
/* 获取1选中的权限列表key */
function  getAuthSelect(keys) {
  check_auth.value = keys;
}
/* 获取2选中的权限列表key */
function getAuthSelect2(keys) {
  check_auth2.value = keys;
}

/* 选择全选或取消全选 */
function handleCheckAll(item) {
  // 取到所有的子菜单id
  let ids = item.Items.map(item =>{
    return item.ChartPermissionId
  })
  item.CheckList = item.checkAll ? ids : [];	
      item.isIndeterminate = false;
}
/* 复选框組选中时 */
function handleChecked(item) {
  let len = item.CheckList.length;
  item.checkAll = len === item.Items.length;
  item.isIndeterminate = len > 0 && len < item.Items.length;
}



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


const showViewer = ref(false)
const	imgView = ref('')
	/* 预览名片 */
function reviewCard(card) {
  showViewer.value = true;
  imgView.value = card;
}
/* 关闭预览 */
function closeViewer() {
  imgView.value = '';
  showViewer.value = false;
}


	/* 去领取 */
function goPickHandle() {
  $router.push({
    path:'/customSearch',
    query:{
      name: nameRepeat.value == 2 ? basicform.value.CompanyName :'',
      code: nameRepeat.value == 1 ?   basicform.value.CreditCode : '' 
    }
  })
}


</script>
<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="basicformRef"
						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
                disabled
								v-model="basicform.CompanyName" 
								placeholder="请输入客户名称"
								style="width:80%">
							</el-input>
							
						</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?true:false"
								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="raiformRef"
						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 #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="ficcformRef"
						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 #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="default" 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>
				<el-input
					placeholder="姓名/手机号码/邮箱"
					v-model="search_txt"
					@input="searchUser"
					style="maxWidth:500px">
          <template #prefix>
            <el-icon><Search/></el-icon>
          </template>
				</el-input>
			</div>
			<div class="bot_cont">
				<el-table
				ref="userTableRef"
				:data="userTable"
				border>
					<el-table-column
					prop="RealName"
					label="姓名"
					align="center">
						<template #default="scope">
							<img :src="$icons.card" alt="" style="width:17px;cursor:pointer;marginRight:5px;" 
							v-if="scope.row.BusinessCardUrl"
							@click="reviewCard(scope.row.BusinessCardUrl)">
							<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 #default="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 #default="scope"> <span>{{scope.row.Email}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="IsMaker"
					label="是否KP"
					align="center">
						<template #default="scope"> <span>{{scope.row.IsMaker==1?'是':'否'}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="IsRegister"
					label="是否注册"
					align="center">
						<template #default="scope"> <span>{{scope.row.IsRegister?'已注册':'未注册'}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="CreatedTime"
					label="注册时间"
					min-width="150"
					align="center">
						<template #default="scope"> <span>{{scope.row.RegisterTime}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="ViewTotal"
					label="累计阅读次数"
					align="center">
						<template #default="scope"> <span>{{scope.row.ViewTotal||'暂无'}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="LastViewTimeStr"
					label="最近一次阅读时间"
					min-width="150"
					align="center">
						<template #default="scope"> <span>{{scope.row.ViewTotal?scope.row.LastViewTimeStr:''}}</span> </template>
					</el-table-column>
					<el-table-column
					label="阅读报告列表"
					align="center">
						<template #default="scope"> <span v-if="scope.row.ViewTotal!=0" class="editsty" @click="lookReport(scope.row)">点击查看</span></template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="140px">
						<template #default="scope">
							<div style="color:#4099ef; font-size:24px;">
								<span class="editsty" style="marginRight:8px;" @click="editContact(scope.row)">编辑</span>
								<span class="deletesty" @click.stop="delConcat(scope.row)">删除</span>
							</div>
						</template>
					</el-table-column>
          <template #empty>
            <div 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>
          </template>
				</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>
		<!-- 图片预览 -->
		<el-image-viewer 
		v-if="showViewer" 
		@close="closeViewer" 
		:url-list="[imgView]" />
		<!-- 导入的联系人表格 -->
		<el-dialog
		title="批量导入"
		v-model="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 #default="scope">{{scope.row.RealName}}</template>
					</el-table-column>
					<el-table-column align="center" label="性别">
						<template #default="scope">{{scope.row.Sex==1?'男':scope.row.Sex==2?'女':''}}</template>
					</el-table-column>
					<el-table-column align="center" label="手机号">
						<template #default="scope">{{scope.row.Mobile?scope.row.CountryCode+'-'+scope.row.Mobile:''}}</template>
					</el-table-column>
					<!-- <el-table-column align="center" label="手机号2">
						<template #default="scope">{{scope.row.MobileTwo||''}}</template>
					</el-table-column> -->
					<el-table-column align="center" label="邮箱">
						<template #default="scope">{{scope.row.Email||''}}</template>
					</el-table-column>
					<el-table-column align="center" label="是否决策人">
						<template #default="scope">{{scope.row.IsMaker==1?'是':'否'}}</template>
					</el-table-column>
					<el-table-column align="center" label="职位">
						<template #default="scope">{{scope.row.Position||''}}</template>
					</el-table-column>
					<el-table-column align="center" label="部门">
						<template #default="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 #default="scope">{{scope.row.RealName}}</template>
					</el-table-column>
					<el-table-column  align="center" label="手机号/邮箱" width="300">
						<template #default="scope">
							{{scope.row.Mobile}} 
							{{(scope.row.Mobile&&scope.row.Email)?'/':''}}
							{{scope.row.Email}}
						</template>
					</el-table-column>
					<el-table-column align="center" label="销售">
						<template #default="scope">{{scope.row.SellerRealName}}</template>
					</el-table-column>
					<el-table-column align="center" label="关联客户" min-width="150">
						<template #default="scope">{{scope.row.CompanyName}}</template>
					</el-table-column>
					<el-table-column align="center" label="操作">
						<template #default="scope">
							<el-button type="text" size="default" @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
		v-model="isCheck"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		:show-close="false"
		center
		width="560px">
      <template #header>
        <div style="display:flex;alignItems:center;">
          <span style="fontSize:16px;">提示</span>
        </div>
      </template>
			<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>
	</div>
</template>
<style lang="scss" scoped>
:deep(.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 {

	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 */
	:deep(.el-form-item) {
		margin-bottom: 30px;
		
		.el-form-item__label{
			font-size: 15px;
		}
		&:last-child {
			margin-bottom: 0;
		}
    .el-form-item__content {
      height: 40px;
    }
	}
	:deep(.el-collapse) {
		border: none;
	}
	:deep(.el-collapse-item__header) {
		display: block;
		border: none;
		font-size: 16px;
		color: #333;
    text-align: left;
	}
	:deep(.el-collapse-item__wrap) {
		border: none;
	}
	:deep(.textarea_item .el-form-item__content) {
		width: 100%;
	}
	:deep(.el-form-item__content .menu_item) {
		line-height: 20px;
	}
	:deep(.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;
	}
}
:deep(.el-autocomplete-suggestion-data-entry) {
	width:auto !important;
}
:deep(.el-autocomplete-none) {
	display: none !important;
}
.autocomplete-input {
.el-input__inner {
	padding-right:65px ;
	}
	input {
	overflow: hidden; // 溢出隐藏
 	text-overflow: ellipsis; // 显示省略号
 	white-space: nowrap; // 不换行
	}	
}
</style>