<script>
import { defineComponent } from 'vue'
export default defineComponent({
  //进入前是否清除参数
  beforeRouteEnter(to, from, next) {
    if(!['/editCustom','/turnCustom','/updateCustom','/customDetail'].includes(from.path)) {
      sessionStorage.removeItem('customListBack')
    }
    
		next()
  }
})
</script>

<script setup>
import { ref,computed,watch } from 'vue'
import { useRoute,useRouter,onBeforeRouteLeave } from 'vue-router'
import { Search,MoreFilled } from '@element-plus/icons-vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import DatePicker from "vue-datepicker-next";
import { formatTime } from '@/utils/date'
import moment from 'moment'
import { customInterence } from '@/api/api.js'
import { useViewPermissionDia,useLookTrialDia,useCommunicaRecordDia,useChooseContractDia,useList,useAddTrialDia,useViewRemarkCustomDia,useCompleteInfoDia,useFreezeReasonDia,useViewRoadShowDia  } from "./hooks/customlistHook";
import {locationOptions} from "./location"
import mPage from '@/components/mPage.vue'
import permissionView from './components/premissionView.vue'
import Capplydia from './components/Capplydialog.vue'
import Contactdia from './components/Contactdialog.vue'
import Cauthlist from './components/CauthList.vue'
import CompleteInfo from './components/CompleteInfo.vue'
import ContractInfo from './components/ContractInfo.vue'
import AccumulativeFrequencyDlg from './components/accumulativeFrequencyDlg.vue'
import TotalDayDialog from './components/TotalDayDialog.vue'
import ShareListDialog from './components/shareListDialog.vue'
import ModifyToDoDialog from './components/ModifyToDoDialog.vue'
import CheckToDoDialog from './components/CheckToDoDialog.vue'
import HistoryToDoDialog from './components/HistoryToDoDialog.vue'


onBeforeRouteLeave((to, form, next) => {
  let backData = {
			page_no:page_no.value,
			act_status:act_status.value,
			type:type.value,
			trade:trade.value,
			sales:sales.value,
			variety:variety.value,
			date:date.value,
			start_date:start_date.value,
			end_date:end_date.value,
			createdate:createdate.value,
			keyword:search_txt.value,
			setmealSelect:setmealSelect.value,
			valueLocation:JSON.stringify(valueLocation.value),
			todoStatus:todoType.value  
		}
  sessionStorage.setItem('customListBack',JSON.stringify(backData))
  next()
})

const $router = useRouter()
const $route = useRoute()

const typeArr = [{
    name: 'ficc'
}, {
    name: '权益'
}] //类型
const setmealArr = [{
    name: '大套餐',
    id: 1
}, {
    name: '小套餐',
    id: 2
}]
const trialTags = [ 
	{
		label: '推进',
		value: 2
	},
	{
		label: '跟踪',
		value: 3
	},
	{
		label: '预备',
		value: 4
	},
	{
		label: '未分类',
		value: 1
	},
]// 试用的标签状态
const	areaArr = [{name:'国内'},{name:'海外'}]
const todoTypeArr = [
	{
		id:1,
		name:'未完成'
	},
	{	id:2,
		name:'已完成'
	},
	{	id:3,
		name:'无任务'
	}
]


const { 
  suspendHandle,
  editHandle,
  Role,
  RaiSellerRole,
  RoleType,
  RoleIdentity,
  SellerAdminId,
	ManageType,
	goDetail
} = useList();

const { 
  isLook,
  lookTitle,
  lookAuthList,
  lookAuthListEquity,
  lookHandle,
  closeDia
} = useViewPermissionDia();//查看权限弹窗

const {
  isAddTrial,
  addTryId,
  addTrialHandle,
  closeAddTrial,
  authList
} = useAddTrialDia();//增开试用弹窗

const {
  lookRemarkTitle,
  lookRemarkList,
  lookRemarkTextarea,
  isRemarkLook,
  lookRemarkItem,
	lookRemarkAdd,
  lookRemarkDelete,
  closeRemark,
  lookRemarkHandle
} = useViewRemarkCustomDia();//查看备注弹窗

const { 
	accumulativeFrequencyClick,
	accumulativeFrequencyDlg,
	accumulativeFrequencyItem,
	closeAccumulativeDlg
} = useViewRoadShowDia();//路演详情弹窗


const { 
	isTotalDayDialogShow,
	customItem,
	handleTotalDayClick,
	closeLookTrial
} = useLookTrialDia();//查看累计试用天数弹窗

const { 
	shareCustomInfo,
	isShareRecodeDialogShow,
	allowEdit,
	handleShowShareRecode
} = useCommunicaRecordDia();//服务记录弹窗


const tabs =  ref([])
const act_status = ref($route.query.act_status||'全部') //状态
const type = ref('') //类型
const setmealSelect = ref('') //套餐的选择
const trade = ref('')
const variety = ref([]) //已购品种
const variety_red = ref([]) //阅读权限
const date = ref('')
const start_date = ref('') //开始日期
const end_date = ref('') //结束日期
const createdate = ref('') //创建日期
const tableData = ref([])
const isShowloadding = ref(false)
const search_txt = ref('')
const total = ref(1)
const page_no = ref(1)
const pageSize = ref(10)
const sort_type = ref('') //自定义排序方式
const sort_param = ref('') //自定义排序方式的哪一个
const valueLocation = ref([])
const provinceValue = ref('')
const cityValue = ref('')
const SortByTodo= ref(false)
const AddCompanyBtn= ref(false) //控制新增客户按钮是否显示
const act_trialTag = ref(0)//默认的标签状态
const trialTagArr = ref([])
const fromArea = ref('')
const userTableRef = ref(null)
/* 获取表格 */
function getTableData() {
	isShowloadding.value = true;
	/* 处理品种结构 和 阅读权限 */
	let param_arr = [];
	let variety_red_arr = []
	if(variety.value.length) {
		param_arr = variety.value.map(item => {
			return item[1];
		})
	}
	if(variety_red.value.length){
			variety_red_arr = variety_red.value.map(item => {
					return item[1];
			})
	}
	// 处理销售筛选
	let salesArr=[]
	if(sales.value.length){
		salesArr=sales.value.map(item=>{
			return item[item.length-1]
		})
	}

	let params = {
		SortParam:sort_param.value,//自定义排序字段
		SortType:sort_type.value,//排序方式
		PageSize:pageSize.value,
		CurrentIndex:page_no.value,
		Status:act_status.value,
		CompanyType:type.value,
		IndustryId:trade.value?Number(trade.value):'',
		AdminId:salesArr.join(','),
		ChartPermissionIds:variety_red_arr.join(','),//阅读权限
		ContractPermissionIds:param_arr.join(','),//已购权限
		StartDate:start_date.value,
		EndDate:end_date.value,
		CreateStartDate:createdate.value[0]?createdate.value[0]:'',
		CreateEndDate:createdate.value[0]?createdate.value[1]:'',
		KeyWord:search_txt.value,
		// Address:locationValue,
		Province:provinceValue.value,
		City:cityValue.value,
		PackageType: setmealSelect.value ? Number(setmealSelect.value) : 0,
		TodoStatus:todoType.value,
		SortByTodo:SortByTodo.value,
		TryStage: act_trialTag.value,
		RegionType:fromArea.value
	}
	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=='待审批'?'待审批':''
			})
			tabs.value = res.Data.StatusCount;
			total.value = res.Data.Paging.Totals;
			
			trialTagArr.value = res.Data.TryStageCount ? res.Data.TryStageCount.sort((x,y) => x.TryStage-y.TryStage ) : []
			if(trialTagArr.value.length) {
				const [ x, y, ...res] = trialTagArr.value;
				trialTagArr.value = [ x,...res,y ];
			}

			tableData.value = res.Data.List || [];
			AddCompanyBtn.value = res.Data.AddCompanyBtn	
			isShowloadding.value = false;
		}
	})
}
 /* 页码改变 */
function handleCurrentChange(page) {
    page_no.value = page;
    getTableData();
}
/* 搜索客户 重置筛选条件 */
function searchHandle() {
    init();
    getTableData();
}
/* 重置 */
function init() {
    act_status.value = '全部';
    if (['admin','finance'].includes(Role.value)) {
        type.value = '';
    }
    trade.value = '';
    sales.value = '';
    variety.value = '';
    date.value = '';
    valueLocation.value = []
    provinceValue.value = ''
    cityValue.value = ''
    start_date.value = ''; //开始日期
    end_date.value = ''; //结束日期
    page_no.value = 1;
}
/* 选择类型时 */
function changeType() {
    trade.value = '';
    variety.value = []
    page_no.value = 1;
    getTableData()
}
/* 选择行业 */
function filterChange() {
    page_no.value = 1;
    getTableData();
}
/* 选择服务日期 */
function dateChange(e) {
    if (e[0]) {
        start_date.value = e[0];
        end_date.value = e[1];
    } else {
        start_date.value = '';
        end_date.value = '';
    }
    page_no.value = 1;
    getTableData();
}
/* 选择日期 */
function dateChange2(e) {
    // console.log(e[0]);
    if (!e[0]) {
        createdate.value = []
    }
    page_no.value = 1;
    getTableData();
}
/* 切换状态 表格重置 */
function changeStatus(item, index) {
    act_status.value = item.Status;
    act_trialTag.value = 0;
    userTableRef.value.clearSort()
    sort_type.value = '';
    sort_param.value = '';
    SortByTodo.value = false
    page_no.value = 1;
    getTableData()
    //重新获取销售信息
    getSale();
}
function handleChangeLocation() {
    const provinceArr = []
    const cityArr = []
    valueLocation.value.forEach(item => {
        // 省
        provinceArr.push(item[0])
        // 市
        cityArr.push(item[1])
    })
    //provinceArr需要去重
    provinceValue.value = [...new Set(provinceArr)].join(',')
    cityValue.value = cityArr.join(',')
    page_no.value = 1;
    getTableData();
}

/* 到期天数排序发生变化 全局排序 */
function sortChangeHandle(item) {
    if (item.column.label === 'To-Do') {
        SortByTodo.value = !SortByTodo.value
        sort_type.value = ''
        sort_param.value = ''
    } else if (item.prop === 'Status') {
        SortByTodo.value = false
        sort_type.value = 'asc'
        sort_param.value = sort_param.value === 'tryStage' ? '' : 'tryStage'
    } else if (item.prop === 'deadline') {
        SortByTodo.value = false
        sort_type.value = 'asc'
        sort_param.value = sort_param.value === 'deadline' ? '' : 'deadline'
    } else {
        SortByTodo.value = false
        sort_type.value = item.order === 'ascending' ? 'asc' : item.order === 'descending' ? 'desc' : '';
        sort_param.value = item.column.label == '转正时间' ? 'formalTime' : item.column.label == '冻结时间' ?
            'freezeTime' : item.column.label == '流失时间' ? 'lossTime' : item.prop;
    }
    page_no.value = 1;
    getTableData();
}
	/* 切换标签状态 */
function changeTagStatus({ TryStage }) {
    act_trialTag.value = TryStage;
    userTableRef.value.clearSort()
    sort_type.value = '';
    sort_param.value = '';
    SortByTodo.value = false
    page_no.value = 1;
    getTableData()
}
	/* 改变客户的试用标签 */
function changeTrialHandle({ CompanyId },trialItem) {
  const { ProductId,TryStage } = trialItem;

  customInterence.setTrialTag({
    CompanyId,
    ProductId,
    TryStage
  }).then(res => {
    if(res.Ret !== 200) return
    ElMessage.success('设置成功');

    getTableData()
  })
}



watch(() => type.value,
  () => {
      getIndustry();
      getVariety();
  }
)
const varietyArr = ref([])
 /* 获取品种信息 */
function getVariety() {
    customInterence.getvariety({
        CompanyType: type.value
    }).then(res => {

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


const salesArr = ref([])//修改销售时可选择的数据
/* 获取销售 */
function getSale() {
  let status = 0;
	if (act_status.value == '流失') {
			status = 1;
	}
	customInterence.getSale({
			"Status": status
	}).then(res => {
			if (res.Ret === 200) {
					salesArr.value = res.Data.List;
			}
	})
}


 
const modifysalesArrtem = ref([])//从后台获取的修改销售时选择的列表(包括不可选的销售)
/* 修改销售时选择列表 */
function getmodifySale() {
	customInterence.getSale({AllSeller:true}).then(res => {
		if(res.Ret === 200) {
			modifysalesArrtem.value = res.Data.List;
		}
	})
}



const sales = ref('')
const modifySales = ref(0)//用于重新渲染选择销售级联选择窗
//根据AdminId生成sales:[]替换this.sales,并请求数据
async function getSaleByAdminId(){
	let temp = [["department_2","group_2","46"],["department_2","group_2","63"]]
	let salesArr = []
	const {adminId} = $route.query
	//从/todoTask来的AdminId只会有一个
	const formatSale = (list,AdminId)=>{
			for (let i in list) {
					if(list[i].AdminId==AdminId){
						return [list[i]]
					}
					if(list[i].ChildrenList){
						let node=formatSale(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 = formatSale(salesArr,adminId)
	sales.value = [temp.map(i=>i.AdminId).reverse()]
	modifySales.value++
	act_status.value = '试用'
	getTableData();
}



let btnCommandList = {
	BtnAddAgreement: '补充协议',
	BtnApplyReceive: '申请领取',
	BtnDelay: '申请延期',
	BtnDelete: '删除',
	BtnDetail: '',
	BtnEdit: '编辑',
	BtnFreeze: '冻结',
	BtnModifySeller: '修改销售',
	BtnReceive: '领取客户',
	BtnReceiveOther: '领取',
	BtnSuspend: '启用/暂停',
	BtnThaw: '申请解冻',
	BtnTryOut: '增开试用',
	BtnTurnPositive: '申请转正',
	BtnUpdate: '续约申请',
	BtnView: '查看权限',
	// BtnRemarkEdit: '编辑备注',
	BtnRemarkView: '备注',
	BtnShare:'设置共享',
	BtnCancelShare:'取消共享',
	BtnServiceRecord:'沟通记录',
	BtnClose:'关闭',
	BtnLoss:'转流失'
}	// 按钮命令列表
// 按钮列表
function 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)
	}
}
// 用于返回按钮名称
function btnName(btnItem,row){
	if(btnItem!=='BtnSuspend' && btnItem!=='BtnShare') return btnCommandList[btnItem]
	if(btnItem=='BtnSuspend') return row.IsSuspend===1?'启用':'暂停'
	if(btnItem=='BtnShare') return row.IsShare===1?'取消共享':'设置共享'
}


/* 操作 */
function itemclickHandle(query) {
  if(query.type == '申请转正') {
    applyTurn(query.data)
  }else if(query.type == '申请延期' || query.type == '申请解冻') {
    applyHandle(query.type,query.data)
  }else if(query.type == '申请领取') {
    if(RaiSellerRole.value && query.data.IsScrounge == 1){
      ElMessageBox.confirm('此客户存在长期且反复申请试用，但从未签约的情况，确定要领取吗？','申请领取',{
        type:'warning'
      }).then(() => {
        applyHandle('申请领取',query.data)
      }).catch(() => {});
    }else{
      applyHandle('申请领取',query.data)
    }
  }else if(query.type == '修改销售') {
    updateSale(query.data);
  }else if(query.type == '启用' || query.type == '暂停') {
    suspendHandle(query.data)
  }else if(query.type == '冻结') {
    freezHandle(query.data);
  }else if(query.type == '领取') {
    receiveOtherHandle(query.data);
  }else if(query.type == '增开试用') {
    addTrialHandle(query.data)
  }else if(query.type=='编辑'){
		regionType.value=query.data.RegionType
    editHandle(query.data)
  }else if(query.type=='删除'){
    delHandle(query.data)
  }else if(query.type=='查看权限'){
    lookHandle(query.data)
  }else if(query.type=='续约申请'){
    updateHandle(query.data)
  }else if(query.type=='补充协议'){
    addAgreement(query.data)
  }else if(query.type=='领取客户'){
    if(RaiSellerRole.value && query.data.IsScrounge == 1){
      ElMessageBox.confirm('此客户存在长期且反复申请试用，但从未签约的情况，确定要领取吗？','领取客户',{
        type:'warning'
      }).then(() => {
        receiveHandle(query.data)
      }).catch(() => {})
    }else{
      receiveHandle(query.data)
    }
  }else if(query.type=='备注'){
    lookRemarkHandle(query.data)
  }else if(query.type=='设置共享' || query.type=='取消共享'){
		shareSetting(query.data)
	}else if(query.type=='沟通记录'){
		handleShowShareRecode(query.data)
	}else if(query.type=='关闭'){
		openCloseReasonDialog(query.data)
	}else if(query.type=='转流失'){
		turnLose(query.data)
	}
}

/* 领取权益/ficc客户 */
async function receiveOtherHandle(item) {
  //判断是否需要补全信息
  let flag=await getCustomerDetail(item.CompanyId,1)
  if(flag) return

  $router.push({
    path:'/pickCustom',
    query:{
      id:item.CompanyId
    }
  })
}


/* 删除 */
function delHandle(item) {
  ElMessageBox.confirm('删除后客户将不能查阅报告，确定删除吗?','提示',{
    type:'warning'
  }).then(() => {
    customInterence.customDel({
      CompanyId:item.CompanyId
    }).then(res => {
      if(res.Ret === 200) {
        ElMessage.success(res.Msg)

        getTableData();
      }
    })
  }).catch(() => {});
}


// 设置/取消 共享
function shareSetting(row){
	customInterence.setCustomShare({CompanyId:row.CompanyId,IsShare:row.IsShare==0?1:0}).then(res=>{
		if(res.Ret==200){
			ElMessage.success(row.IsShare==0?'设置共享成功':'取消共享成功')
			getTableData()
		}
	})
}

/* 增加试用完成 */
function addTryOver() {
	isAddTrial.value = false;
	getTableData();
}


/* 新增客户 */
function addCustom() {
	$router.push({path:'/addCustom'});
}

const isCloseCustomDialogShow = ref(false)
const customInfo = ref({})
const	closeReason = ref('')
/* 关闭客户 */
function closeCustom(){
	if(!closeReason.value){
		ElMessage.warning('请填写关闭理由')
		return
	}
	customInterence.closeCustom({
		CompanyId:customInfo.value.CompanyId,
		Remark:closeReason.value
	}).then(res=>{
		if(res.Ret!==200) return 
		getTableData()
		ElMessage.success('关闭客户成功')
		isCloseCustomDialogShow.value = false
	})
	
}
/* 打开关闭理由弹窗 */
function openCloseReasonDialog(data){
	customInfo.value = data
	closeReason.value=''
	isCloseCustomDialogShow.value = true
}



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


/* 确认将客户转流失 */
function turnLose(data){
	ElMessageBox.confirm(`是否确认将【${data.CompanyName}】转为流失客户？`,'提示',{
		confirmButtonText:'确认',
		cancelButtonText:'取消',
		type: 'warning'
	}).then(()=>{
		customInterence.turnLose({
			CompanyId:data.CompanyId
		}).then(res=>{
			if(res.Ret!==200) return 
			getTableData()
			ElMessage.success('转流失成功')
		})
		
	}).catch(()=>{})
}


/* 申请延期 解冻 领取小弹窗 */
const isApply = ref(false)//申请弹窗
const applyForm = ref({})//客户信息
const applyTit = ref('')
const isShowclose = ref(false)//联系人弹窗时记录是否是领取流失客户
const isPickLoss = ref(false)//联系人弹窗时记录是否是领取流失客户
const	isPickSelf = ref(false)//是否为领取自己的流失客户
const regionType = ref("")
const isAddContact = ref(false) //添加联系人弹窗
const addCompanyId = ref('')//新增联系人的公司id
const diaform = ref({
  name:'',
  sex:1,
  telCode:'86',
  tel1:'',
  tel2:'',
  mail:'',
  post:'',
  desiger:'',
  depart:'',
  carte:'',
  Source:'pick_custom'
})
async function applyHandle(tit,item) {
  //判断是否需要补全信息
  let flag=await getCustomerDetail(item.CompanyId,0)
  if(flag) return
  applyTit.value = tit;
  applyForm.value = item;
  
  // 如果是申请领取（即领取自己流失客户）先添加联系人再进行申请操作
  if(tit=='申请领取'&& (item.SellerId !== SellerAdminId.value)){
    isPickLoss.value = true;
    isPickSelf.value = true
    regionType.value = item.RegionType;
    addCompanyId.value = item.CompanyId;
    diaform.value = {
      name:'',
      sex:1,
      telCode:'86',
      tel1:'',
      tel2:'',
      mail:'',
      post:'',
      desiger:'',
      depart:'',
      carte:'',
      Source:'pick_custom'
    },
    isAddContact.value = true;
  }else{
    isApply.value = true;
  }

  
}
/* 领取流失客户 */
async function receiveHandle(item) {
  //判断是否需要补全信息
  let flag = await getCustomerDetail(item.CompanyId,0)
  if(flag) return

  if(RaiSellerRole.value && item.IsScrounge == 1){
    // 已经弹过二次确认弹窗 避免再一次的弹窗
    isPickLoss.value = true;
    regionType.value = item.RegionType;
    addCompanyId.value = item.CompanyId;
    diaform.value.telCode='86'
    isAddContact.value = true;
    return 
  }
  
  ElMessageBox.confirm('是否确认领取该客户?','提示',{
    type:'warning'
  }).then(() => {

      isPickLoss.value = true;
      addCompanyId.value = item.CompanyId;
      regionType.value=item.RegionType
      diaform.value.telCode='86'
      isAddContact.value = true;
  }).catch(() => {});
}
/* 领取流失客户添加联系人后再领取 */
function cancelConcatdia(type) {
  isAddContact.value = false;
  isPickSelf.value=false
	diaform.value = {
		name:'',
		sex:1,
		telCode:'86',
		tel1:'',
		tel2:'',
		mail:'',
		post:'',
		desiger:'',
		depart:'',
		carte:'',
		Source:'pick_custom'
	};
  if(type == 1) {
    customInterence.Pick({
      CompanyId:addCompanyId.value,
    }).then(res => {
      if(res.Ret === 200) {
        ElMessage.success(res.Msg);
        getTableData();
      }
    })
  }else {
    ElMessage.warning('领取失败')
  }
}
function cancelHandle(type) {
  isApply.value = false;
  applyForm.value = {}
  if(type == 1) {
    getTableData();
  }
}
// 领取自己的流失客户下一步申请操作
const contactFormData = ref({})
function addContactNext({formData}){
  contactFormData.value=formData
  isAddContact.value=false
  isApply.value=true
}



/* 修改销售操作 */
const modifysalesArr = ref([])//修改销售选择列表（不存在不可选的销售）
const isMove = ref(false)//修改销售
const moveform = ref({
  companyType:'',
  companyId:'',//客户id
  companyName:'',
  sale:'',//修改的销售
})
const moveRule = {
  sale:[
    { required: true, message: '所属销售不能为空', trigger: 'blur' },
  ]
}
const moveformRef = ref(null)
function updateSale(item) {
  moveform.value = {
    companyType:item.CompanyType,
    companyName:item.CompanyName,
    companyId:item.CompanyId,
    sale:''
  }
  handleModifysalesArr(item.SellerId)
  isMove.value = true;
}
/* 移动客户所属销售 */
function saveMove() {
  moveformRef.value.validate((valid) => {
    if (valid) {
      customInterence.moveSale({
        CompanyType:moveform.companyType,
        CompanyId:moveform.companyId,
        SellsId:Number(moveform.sale[1])||Number(moveform.sale[2])
      }).then(res => {
        if(res.Ret === 200) {
          ElMessage.success(res.Msg);
          getTableData();
          isMove.value = false;
        }
      })
    }
  })		
}
/* 取消移动客户 */
function cancelMove() {
  moveformRef.value.resetFields();
  isMove.value = false;
}
// 处理修改销售数据 不可以修改到已存在销售
function handleModifysalesArr(ids){
	let idsArr=ids.split('/')
	let arr = _.cloneDeep(modifysalesArrtem.value)
	modifysalesArr.value=arr.map(item=>{
		if(item.ChildrenList){
			item.ChildrenList=item.ChildrenList.filter(e=>{
				return  !idsArr.includes(e.AdminId)
			})
		}
		return item
	})
}



const { 
  contractModel,
	applyTurn,
	updateHandle,
	addAgreement,
	handleContractModel,
	contractDialog,
  closeContractInfoDia
} = useChooseContractDia();//选择合同弹窗
function contractInfoDialogClose(e){
  closeContractInfoDia()
  if(e==='updateList'){
    getTableData();
  }
}


/* 冻结客户 */
const {
  isFreezeReason,
  freezeData,
  freezHandle,
  closeFreezeReason
} = useFreezeReasonDia();//冻结客户理由弹窗
async function  handleConfirmFreeze(){
  if(!freezeData.value.reason){
    ElMessage.error('请填写冻结理由')
    return
  }
  let res=await customInterence.Freez({
    CompanyId:Number(freezeData.value.CompanyId),
    CompanyType:freezeData.value.CompanyType,
    Remark:freezeData.value.reason
  })
  if(res.Ret===200){
    ElMessage.success('冻结成功');
    closeFreezeReason()
    getTableData();
  }
}




const ischeckToDoDialogShow = ref(false)//是否显示销售To-Do的确认完成弹窗
function handleApprove({Id,Remark}){
	customInterence.checkToDo({Id,Remark}).then(res=>{
		if(res.Ret===200){
			ischeckToDoDialogShow.value=false
			ElMessage.success(`审核完成`);
			getTableData()
		}
	})
}
const todoBtnType = [
	{
		label:'新建',
		key:'add'
	},
	{
		label:'编辑',
		key:'edit'
	},
	{
		label:'完成',
		key:'confirm'
	},
	{
		label:'历史',
		key:'history'
	}
]//销售To-Do的按钮
const todoInfo= ref(null)//
const isModifyDialogShow = ref(false)//是否显示销售To-Do新建/编辑的弹窗
const isHistoryDialogShow = ref(false)//是否显示销售To-Do的历史记录弹窗
const modifyToDoType = ref('add')//新增or编辑
const todoType = ref('')
//销售To-Do的按钮,根据每一行的信息决定显示哪些按钮,必须返回一个数组
function getToDoBtn(row){
	let todoBtn = []
	//该字段为true说明已有任务,隐藏新建按钮
	if(row.TodoStatus){
		todoBtn = todoBtnType.filter(i=>i.key!=='add')
	}else{
		todoBtn =  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()
	}
	return todoBtn
}
//销售To-Do的点击事件
function handleToDoBtnClick(row,type){
	todoInfo.value = row
	//打开新建/编辑弹窗
	if(['add','edit'].includes(type)){
		modifyToDoType.value = type
		isModifyDialogShow.value = true
		ischeckToDoDialogShow.value = false
		isHistoryDialogShow.value=false
	}
	//打开审核记录弹窗
	if(type==='confirm'){
		ischeckToDoDialogShow.value=true
		isModifyDialogShow.value=false
		isHistoryDialogShow.value=false
	}
	//打开历史记录弹窗
	if(type==='history'){
		isHistoryDialogShow.value=true
		isModifyDialogShow.value=false
		ischeckToDoDialogShow.value=false
	}
}
//处理销售ToDo
//新建\编辑弹窗的确认事件
async function handleModifyToDo({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){
			isModifyDialogShow.value=false
			ElMessage.success(`${type==='add'?'提交':'保存'}成功`);
			getTableData()
		}			
}
function getTodoBtnColor(colorName){
	if(colorName==='red'){
		return '#D1433A'
	}else if(colorName==='green'){
		return '#61D13A'
	}else{
		return '#999999'
	}
}


function initData() {
		/* 除admin账号 客户类型默认 */
		if (!['admin','finance'].includes(Role.value)) {
      type.value = RoleType.value;
  	}
 		variety.value = type.value == 'ficc' ? [[100, 1]] : []

		if(sessionStorage.getItem('customListBack')) {
			let backData = JSON.parse(sessionStorage.getItem('customListBack'));
			search_txt.value = backData.keyword;
			page_no.value = backData.page_no,
			act_status.value = backData.act_status,
			type.value = backData.type,
			trade.value = backData.trade,
			sales.value = backData.sales,
			variety.value = backData.variety,
			date.value = backData.date,
			start_date.value = backData.start_date,
			end_date.value = backData.end_date,
			createdate.value = backData.createdate,
			search_txt.value = backData.keyword,
			setmealSelect.value =backData.setmealSelect,
			valueLocation.value=JSON.parse(backData.valueLocation)
			todoType.value = backData.todoStatus  

			handleChangeLocation()
		}
	
		// 从客户区域统计列表过来的参数
		act_status.value=$route.params.Status ? $route.params.Status : act_status.value
		type.value = $route.params.CompanyType ? $route.params.CompanyType : type.value
		act_trialTag.value = $route.params.TryStage ? $route.params.TryStage : act_trialTag.value
		valueLocation.value = $route.params.valueLocation ? JSON.parse(sessionStorage.getItem('regionData')) || [] :[]

		if($route.query.adminId){
			isShowloadding.value = true
			getSaleByAdminId();
		}else if(valueLocation.value.length>0){
			handleChangeLocation()
			sessionStorage.removeItem('regionData')
		}else{
			getTableData();
		}
		getSale();
		getmodifySale();
}
initData()
</script>
<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>

				</div>
			</div>
			<el-input
			placeholder="客户名称/社会信用码/手机号码/邮箱"
			v-model="search_txt"
			style="max-width:520px"
			@input="searchHandle"
			clearable>
        <template #prefix>
          <el-icon><Search/></el-icon>
        </template>
			</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="filterChange">
						<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="filterChange">
						<el-option
							v-for="item in tradeArr"
							:key="item.IndustryId"
							:label="item.IndustryName"
							:value="item.IndustryId">
						</el-option>
					</el-select>
					<el-cascader
						v-if="act_status=='流失' ||(Role==['finance','admin','ficc_admin','rai_admin'].includes(Role)||ManageType!=0)"
						v-model="sales"
						placeholder="请选择销售"
						style="width:200px;marginRight:10px;marginBottom:8px;"
						:options="salesArr"
						:props="{
							multiple: true,
							label: 'RealName',
							children: 'ChildrenList',
							value: 'AdminId'
						}"
						:show-all-levels="false"
						:key="modifySales"
						collapse-tags
						clearable
						filterable
						@change="filterChange">
					</el-cascader>
					<el-select v-model="setmealSelect" placeholder="请选择套餐类型" style="width:200px;marginRight:10px;marginBottom:8px;" clearable @change="filterChange">
						<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="{
							 multiple: true,
							label: 'ClassifyName',
							children: 'Items',
							value: 'ChartPermissionId'
						}"
						:show-all-levels="false"
						collapse-tags
						clearable
						filterable
						@change="filterChange">
					</el-cascader>
                    <el-cascader
						v-model="variety_red"
						placeholder="请选择阅读权限"
						style="width:200px;marginRight:10px;marginBottom:8px;"
						:options="varietyArr"
						:props="{
							 multiple: true,
							label: 'ClassifyName',
							children: 'Items',
							value: 'ChartPermissionId'
						}"
						:show-all-levels="false"
						collapse-tags
						clearable
						filterable
						@change="filterChange">
					</el-cascader>
					<el-cascader v-model="valueLocation" collapse-tags :props="{
						multiple: true,value:'name',children:'city',label:'name'
					}" clearable :options="locationOptions"  @change="handleChangeLocation" 
            placeholder="请选择客户地址" style="width:200px;marginRight:10px;marginBottom:8px;">
          </el-cascader>
					<date-picker 
						v-model:value="date" 
						type="date" 
						range
						value-type="format"
						placeholder="服务日期" 
						@change="dateChange" 
						style="width:200px;marginRight:10px;marginBottom:8px;">
					</date-picker>
					<date-picker 
					v-model:value="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="filterChange" 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="userTableRef"
					: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 #default="scope"> 
              <div :class="{'isShared':scope.row.IsShared}">
                <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}"
                  :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.CompanyName}}</span>
                <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>
              </div>
						</template>
					</el-table-column>
					<el-table-column label="To-Do" prop="todo" align="center" min-width="5.14%" sortable="custom">
						<template #header>
							<div class="todolabel" :class="{sort:SortByTodo}" style="display:inline-block;">
								<span>To-Do</span>
							</div>
						</template>
						<template #default="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 #header>
							<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>
							</div>
						</template>
						<template #default="{row}">
							<span>{{row.Deadline||'--'}}</span>
      			</template>
					</el-table-column>
					<el-table-column
            prop="CompanyType"
            label="类型"
            align="center"
            min-width="4.14%"
					>
						<template #default="{row}"> 

							<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 #default="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 #default="scope">
						 <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 #default="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 #header>
							<div class="todolabel" :class="{sort:sort_param==='tryStage'}" style="display:inline-block;">
								<span>状态</span>
							</div>
					</template>
					<template #default="scope"> 
						<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="small" 
									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="small" 
									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 #default="{row}">
							<el-tooltip :disabled="row.IsSuspend===1||(row.FiccTryOutDay+row.RaiTryOutDay===0)">
                <template #content>
                  <div>
                    <p v-if="row.FiccTryOutDay">FICC累计试用天数：{{row.FiccTryOutDay}}</p>
                    <p v-if="row.RaiTryOutDay">权益累计试用天数：{{row.RaiTryOutDay}}</p>
                  </div>
                </template>
								<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 #default="{row}">
							<el-tooltip :disabled="row.IsSuspend===1 || (row.FiccView+row.RaiView)===0">
                <template #content>
								  <div>
                    <p v-if="row.FiccView">FICC报告阅读次数：{{row.FiccView}}</p><p v-if="row.RaiView">权益报告阅读次数：{{row.RaiView}}</p>
                  </div>
                </template>
								<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 #default="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 #default="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 #default="scope">
							<span :style="scope.row.IsSuspend===1?'color:#bbb':''">
								<!-- 正常的时间显示 -->
								<template v-if="scope.row.StartDate.indexOf('/')==-1">
									<template v-if="act_status=='流失'">
										创建时间：{{formatTime(scope.row.CreatedTime)}}
									</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 #default="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 #default="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
													?(`${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 #default="scope">
							<!-- 新操作栏 -->
							<div style="color:#4099ef; font-size:24px;display:flex;align-content: center;justify-content: center;align-items: center;"  v-if="!scope.row.ApproveStatus">
								<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="default" 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>  
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <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>
                    </template>
								</el-dropdown>
							</div>
						</template>
					</el-table-column>
          <template #empty>
            <div 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>
          </template>
				</el-table>
				<div class="toolbar fixedbar">
					<el-pagination 
					layout="prev,pager,next" 
					background
					:current-page="page_no"
					@current-change="handleCurrentChange"
					:page-size="pageSize"
					:total="total"
					style="float:right;">
					</el-pagination>
				</div>
			</div>
		</div>

		<!-- 申请弹窗 -->
		<Capplydia
		:isApply="isApply"
		:title="applyTit"
		:formdata="applyForm"
		:contactFormData="contactFormData"
		@cancelHandle="cancelHandle">
		</Capplydia>

		<!-- 查看权限弹窗 -->
		<permissionView :isLook="isLook" :lookTitle="lookTitle" :lookAuthList="lookAuthList" :lookAuthListEquity="lookAuthListEquity"
     @closeDia="closeDia"></permissionView>

		<!-- 增开试用弹窗 -->
		<el-dialog
		v-model="isAddTrial"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="isAddTrial=false"
		width="800px"
		draggable
		center>
      <template #header>
        <div style="display:flex;alignItems:center;">
          <!-- <img :src="$icons.auth" style="color:#fff;width:16px;height:16px;marginRight:5px;"> -->
          <span style="fontSize:16px;">增开试用（默认两个月）</span>
        </div>
      </template>
			<Cauthlist
			:autharr="authList"
			:id="addTryId"
			@addOver="addTryOver"
			@close="isAddTrial=false"/>
		</el-dialog>

		<!-- 修改销售弹窗 -->
		<el-dialog
		draggable
		v-model="isMove"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelMove"
		center
		width="30%">
      <template #header>
        <div style="display:flex;alignItems:center;">
          <img :src="$icons.edit" style="color:#fff;width:16px;height:16px;marginRight:5px;">
          <span style="fontSize:16px;">修改销售</span>
        </div>
      </template>
			<el-form :model="moveform" :rules="moveRule" ref="moveformRef" 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-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
		v-model="isFreezeReason"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="closeFreezeReason"
		width="800px"
		draggable
		center>
      <template #header>
        <div 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>
      </template>
			<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
			v-model="contractModel.show"
			:modal-append-to-body='false'
			width="800px"
			class="self-dialog"
			draggable
		>
			<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
		v-model="isRemarkLook"
		:close-on-click-modal="false"
		:modal-append-to-body="true"
		:append-to-body="true"
		@close="closeRemark"
		width="800px"
		draggable
		center>
      <template #header>
        <div 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 #default="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 #default="scope">{{scope.row.ProductName}}</template>
				</el-table-column>
				<el-table-column label="创建时间"  key="CreateTime" align="center">
					<template #default="scope">{{scope.row.CreateTime}}</template>
				</el-table-column>
				<el-table-column label="操作" align="center">
					<template #default="{row}">
						<el-button type="text" size="default" style="color:red;" v-if="row.ButtonDel"
							@click="lookRemarkDelete(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div style="padding:20px 0;"></div>
		</el-dialog>

		<!-- 查看备注弹窗 -->
		<accumulative-frequency-dlg 
			:accumulativeFrequencyDlg="accumulativeFrequencyDlg" 	:accumulativeFrequencyItem="accumulativeFrequencyItem"
			@close="closeAccumulativeDlg"
		/>

		<!-- 新建/编辑销售To Do的弹窗 -->
		<Modify-to-do-dialog 
			:todoInfo="todoInfo" 
			:type="modifyToDoType"
			:isModifyDialogShow="isModifyDialogShow"
			@modify="handleModifyToDo"
			@close="isModifyDialogShow=false"
		></Modify-to-do-dialog>

		<check-to-do-dialog 
			:todoInfo="todoInfo" 
			:ischeckToDoDialogShow="ischeckToDoDialogShow"
			@check="handleApprove"
			@close="ischeckToDoDialogShow=false"
		></check-to-do-dialog>

		<history-to-do-dialog 
			:todoInfo="todoInfo" 
			:isHistoryDialogShow="isHistoryDialogShow"
			@close="isHistoryDialogShow=false"
		></history-to-do-dialog>

    <!-- 累计试用天数弹窗 -->
    <total-day-dialog 
      :isTotalDayDialogShow="isTotalDayDialogShow"
      :customInfo="customItem"
			@close="closeLookTrial"
    />

		<!-- 服务记录弹窗 -->
		<share-list-dialog 
			:isShareRecodeDialogShow="isShareRecodeDialogShow"
			:customInfo="shareCustomInfo"
			:allowEdit="false"
			@close="isShareRecodeDialogShow=false"/>

		<!-- 关闭客户弹窗 -->
		<el-dialog
      v-model="isCloseCustomDialogShow"
      :close-on-click-modal="false"
      :modal-append-to-body='false'
      title="关闭"
      @close="isCloseCustomDialogShow=false"
      width="800px"
      draggable
      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>
	</div>
</template>
<style lang='scss' scoped>
	.self-dialog{
		width: 100% !important;
		max-width: 100% !important;
		:deep(.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 {
	:deep(.mx-datepicker) {
		width: 200px !important;
	}
	:deep(.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner) {
		background-color: #409EFF !important;
		border-color: #409EFF;
	}
	:deep(.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" scoped>
.customList_container {
	:deep(.el-input--small) {
		.el-input__inner{
			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" scoped>
.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>