<script setup>
import { ref,computed,reactive,onBeforeMount } from "vue";
import { customInterence } from '@/api/api.js'
import { useRouter } from 'vue-router'
import { Search,MoreFilled } from '@element-plus/icons-vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import mPage from '@/components/mPage.vue'

const $router = useRouter()

const Role = computed(() => {
  let role = localStorage.getItem('Role') || '';
  return role;
})
const RaiSellerRole = computed(() => {
  return ['rai_seller','rai_admin','admin'].includes(Role)
})
const RoleType = computed(() => {
  let type = localStorage.getItem('RoleType') || '';
  return type;
})
const RoleIdentity = computed(() => {
  let role = localStorage.getItem('RoleIdentity') || '';
  return role;
})
const SellerAdminId = computed(() => {
  let type = localStorage.getItem('AdminId') || '';
  return type;
})


/* 获取表格数据 */
const search_txt = ref('')
const isShowloadding = ref(false)
const noResult = ref(false)
const	pageinfo = reactive({	// 分页信息
  total: 0,
  page_no: 1,
  page_size: 10
})
const tableData = ref([])
function getTableData() {
  isShowloadding.value = true;
  customInterence.searchList({
    KeyWord:search_txt.value,
    PageSize:pageinfo.page_size,
    CurrentIndex:pageinfo.page_no
  }).then(res => {
    if(res.Ret === 200) {
      tableData.value = res.Data?res.Data.List:[];
      pageinfo.total=res.Data && res.Data.Paging ? res.Data.Paging.Totals : 0
      tableData.value.forEach(item => {
        item.ApproveStatus = item.ApproveStatus=='待审批'?'待审批':''
      })
      noResult.value = res.Data.List.length ? false : true;
      isShowloadding.value = false
    }else {
      tableData.value = [];
      noResult.value = true;
      setTimeout(()=> {
        isShowloadding.value = false;
      },100)
    }
  })	
}

// 页码改变事件
function handleCurrentChange(page){
  pageinfo.page_no=page
  getTableData()
}


// 处理状态的数据
function transformedArray(row){
  return [
    {
      SigningStatus: row.CompanyStatusButton.FiccSigningStatus,
      Status: row.CompanyStatusButton.FiccStatus
    },
    {
      SigningStatus: row.CompanyStatusButton.RaiSigningStatus,
      Status: row.CompanyStatusButton.RaiStatus,
    }
  ];
}

//处理时长显示
function formateDuration(time,status){
  let timearr=time.split('/')
  let statusarr=status.split('/').map((item,index)=>{
    if(item=='冻结'){
      return `解冻天数:${timearr[index]?timearr[index]:'--'}`
    }else if(item=='流失'){
      return `流失天数:${timearr[index]?timearr[index]:'--'}`
    }else if(item=='永续'){
      return '永续'
    }else{
      return `剩余天数:${timearr[index]?timearr[index]:'--'}`
    }
  })

  return statusarr.join('/')
}	


const btnCommandList = {
  BtnAddAgreement: '补充协议',
  BtnApplyReceive: '申请领取',
  BtnDelay: '申请延期',
  BtnDelete: '删除',
  BtnDetail: '',
  BtnEdit: '编辑',
  BtnFreeze: '冻结',
  BtnModifySeller: '修改销售',
  BtnReceive: '领取客户',
  BtnReceiveOther: '领取',
  BtnSuspend: '启用/暂停',
  BtnThaw: '申请解冻',
  BtnTryOut: '增开试用',
  BtnTurnPositive: '申请转正',
  BtnUpdate: '续约申请',
  BtnView: '查看权限',
  BtnRemarkView: '备注',
  IsResearchShow:'研选详情'
}
// 按钮列表
function btnList(btnItem,part){
  const allBtnList=[]
  for (const key in btnItem) {
    btnItem[key]&&key!=='BtnClose' && allBtnList.push(key)
  }
  if(part==='front'){
    // 返回前三个按钮
    return allBtnList.slice(0,3)
  }else{
    // 返回三个后按钮
    return allBtnList.slice(3)
  }
}
// 用于返回按钮名称
function	btnName(btnItem,isSuspend){
  if(btnItem!=='BtnSuspend') return btnCommandList[btnItem]
  return isSuspend===1?'启用':'暂停'
}

/* 查看详情 */
function goDetail(item) {
  if(!item.BtnItem.BtnView) return
  $router.push({
    path:'/customDetail',
    query: {
      id:item.CompanyId
    }
  })
}

/* 操作 */
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=='编辑'){
    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=='研选详情'){
    researchDetailHandle(query.data)
  }
}


const completeForm = ref({
  show:false,
})//补全信息弹窗
//获取客户详情判断基本信息是否完整 id 客户id type 1 跨部门 0 不是跨部门
async function getCustomerDetail(id,type){
  
  let res=await customInterence.customDetail({
    CompanyId:id
  })
  if(res.Ret!=200) return

  // 跨部门领取
  if(type===1){
    if((res.Data.Item.RegionType!='海外'&&!res.Data.Item.Province&&!res.Data.Item.City)||!res.Data.Item.CreditCode){

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

  return new Promise((resolve,reject)=>{
    resolve(completeForm.value.show)
  })
    
}


/* 申请转正 */
const contractModel = reactive({
  show:true,
  data:null,//客户信息（列表用户数据）
	type:'',//类型 申请转正、续约申请、补充协议
})
async function applyTurn(item) {
  //判断是否需要补全信息
  let flag=await getCustomerDetail(item.CompanyId,0) 
  if(flag) return
  contractModel.show=true
  contractModel.data=item
  contractModel.type='申请转正'
}
/* 续约申请操作 */
async function updateHandle(item) {
  //判断是否需要补全信息
  let flag = await getCustomerDetail(item.CompanyId)
  if(flag) return
  contractModel.show=true
  contractModel.data=item
  contractModel.type='续约申请'
}
// 补充协议
async function addAgreement(item) {
  //判断是否需要补全信息
  let flag = await getCustomerDetail(item.CompanyId)
  if(flag) return
  contractModel.show=true
  contractModel.data=item
  contractModel.type='补充协议'
}



/* 申请延期 解冻 领取小弹窗 */
const isApply = ref(false)//申请弹窗
const applyForm = ref({})//客户信息
const applyTit = ref('')
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(() => {});
}


/* 修改销售操作 */
const isMove = ref(false)//修改销售
const moveform = ref({
  companyType:'',
  companyId:'',//客户id
  companyName:'',
  sale:'',//修改的销售
})
const moveRule = {
  sale:[
    { required: true, message: '所属销售不能为空', trigger: 'blur' },
  ]
}
function updateSale(item) {
  moveform.value = {
    companyType:item.CompanyType,
    companyName:item.CompanyName,
    companyId:item.CompanyId,
    sale:''
  }
  handleModifysalesArr(item.SellerId)
  isMove.value = true;
}
const salesArr = ref([])//修改销售时可选择的数据
// 处理修改销售数据 不可以修改到已存在销售
function handleModifysalesArr(id){
  const AllSalesArr = _.cloneDeep(modifysalesArrtem.value)
  salesArr.value=AllSalesArr.map(item=>{
    if(item.ChildrenList){
      item.ChildrenList=item.ChildrenList.filter(e=>{
        if(e.ChildrenList){
          e.ChildrenList = e.ChildrenList.filter(i=>{return i.AdminId!=id})
        }
        return  e.AdminId!=id
      })
    }
    return item
  })
}
const modifysalesArrtem = ref([])//从后台获取的修改销售的所有数据
/* 获取销售 */
function getSale() {
  customInterence.getSale({AllSeller:true}).then(res => {
    if(res.Ret === 200) {
      modifysalesArrtem.value = res.Data.List;
    }
  })
}
getSale();


/* 启用/暂停 */
function suspendHandle(item) {
  customInterence.Suspend({
    CompanyId:item.CompanyId
  }).then(res => {
    if(res.Ret === 200) {
      ElMessage.success(res.Msg);
      item.IsSuspend = item.IsSuspend === 1 ? 0 : 1;
    }
  })
}


/* 冻结客户 */
const isFreezeReason = ref(false)//冻结理由弹窗
const freezeData = ref({
  reason:"",//冻结理由
  CompanyId:'',
  CompanyType:""
})
function freezHandle(item) {
  isFreezeReason.value = true
  freezeData.value.CompanyId=item.CompanyId
  let RoleType=localStorage.getItem('RoleType')
  freezeData.value.CompanyType=RoleType
}


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

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


/* 增加试用 */
const isAddTrial = ref(false)//增加试用弹窗
const addTryId = ref('')//增开试用的id
function addTrialHandle(item) {
  authList.value = [];
  customInterence.lookauth({
    CompanyId:item.CompanyId,
    LookType:1
  }).then(res => {
    if(res.Ret === 200) {
      let auth = [];
      // res.Data.List 有值为 ficc
      // res.Data.ListRai 有值为 权益
      if(res.Data.List) {
        res.Data.List.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,
            defaultAuth:item.CheckList,
            customType:'ficc',
            ...item,
          }
          auth.push(obj)
        })
      }else if(res.Data.ListRai) {
        auth = filterRaiAuth(res.Data.ListRai,auth)

      }
     
      authList = auth;
    }
  })
  addTryId.value = item.CompanyId;
  isAddTrial.value = true;
}
function filterRaiAuth(data,auth) {
     // 权益 RaiMerge 0不管 1合并 2拆分 所传入的数据结构不一样
    data[0].RaiMerge==1
      ? data.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,
            defaultAuth:item.CheckList,
            ...item,
          }
          auth.push(obj)
        })
      : data.forEach(item=> { // 拆分
          let obj = {
            defaultAuth:item.CheckList,
            customType:'权益',
            ...item,
          }	
          // 组合所需的数据格式
          obj.dataList=[
            {
              PermissionTypeName:'',
              medicine:{
                value:'医药',
                isIndeterminate:item.CheckList.filter(id => [obj.Items[0].ChartPermissionId,obj.Items[1].ChartPermissionId].includes(id)).length ==1,
                isCheckAll:item.CheckList.filter(id => [obj.Items[0].ChartPermissionId,obj.Items[1].ChartPermissionId].includes(id)).length == 2,
                isDisabled:item.CheckList.filter(id => [obj.Items[0].ChartPermissionId,obj.Items[1].ChartPermissionId].includes(id)).length ==2
              },
              consumption:{
                value:'消费',
                isIndeterminate:item.CheckList.filter(id => [obj.Items[2].ChartPermissionId,obj.Items[3].ChartPermissionId].includes(id)).length ==1,
                isCheckAll:item.CheckList.filter(id => [obj.Items[2].ChartPermissionId,obj.Items[3].ChartPermissionId].includes(id)).length == 2,
                isDisabled:item.CheckList.filter(id => [obj.Items[2].ChartPermissionId,obj.Items[3].ChartPermissionId].includes(id)).length ==2
              },
              technology:{
                value:'科技',
                isIndeterminate:item.CheckList.filter(id => [obj.Items[4].ChartPermissionId,obj.Items[5].ChartPermissionId].includes(id)).length ==1,
                isCheckAll:item.CheckList.filter(id => [obj.Items[4].ChartPermissionId,obj.Items[5].ChartPermissionId].includes(id)).length == 2,
                isDisabled:item.CheckList.filter(id => [obj.Items[4].ChartPermissionId,obj.Items[5].ChartPermissionId].includes(id)).length ==2
              },
              smart:{
                value:'智造',
                isIndeterminate:item.CheckList.filter(id => [obj.Items[6].ChartPermissionId,obj.Items[7].ChartPermissionId].includes(id)).length ==1,
                isCheckAll:item.CheckList.filter(id => [obj.Items[6].ChartPermissionId,obj.Items[7].ChartPermissionId].includes(id)).length == 2,
                isDisabled:item.CheckList.filter(id => [obj.Items[6].ChartPermissionId,obj.Items[7].ChartPermissionId].includes(id)).length ==2
              },
              strategy:{
                value:'策略'
              },
              experts:{
                value:'专家'
              },
              roadshow:{
                value:'路演服务'
              },
              choose:{
                value:'研选订阅'
              },
              points:{
                value:'研选扣点包'
              },
            },
            {
              PermissionTypeName:{
                value:'主观',
                isIndeterminate:[1,2,3].includes(item.CheckList.filter(id => [obj.Items[0].ChartPermissionId,obj.Items[2].ChartPermissionId,
                  obj.Items[4].ChartPermissionId,obj.Items[6].ChartPermissionId].includes(id)).length),
                isCheckAll:item.CheckList.filter(id => [obj.Items[0].ChartPermissionId,obj.Items[2].ChartPermissionId,
                  obj.Items[4].ChartPermissionId,obj.Items[6].ChartPermissionId].includes(id)).length == 4,
                isDisabled:item.CheckList.filter(id => [obj.Items[0].ChartPermissionId,obj.Items[2].ChartPermissionId,
                  obj.Items[4].ChartPermissionId,obj.Items[6].ChartPermissionId].includes(id)).length ==4
              },
              medicine:{
                value:obj.Items[0].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[0].ChartPermissionId)
              },
              consumption:{
                value:obj.Items[2].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[2].ChartPermissionId)
              },
              technology:{
                value:obj.Items[4].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[4].ChartPermissionId)
              },
              smart:{
                value:obj.Items[6].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[6].ChartPermissionId)
              },
              strategy:{
                value:obj.Items[8].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[8].ChartPermissionId)
              },
              experts:{
                value:obj.Items[9].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[9].ChartPermissionId)
              },
              roadshow:{
                value:obj.Items[10].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[10].ChartPermissionId)
              },
              choose:{
                value:obj.Items[11].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[11].ChartPermissionId)
              },
              points:{
                value:obj.Items[12].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[12].ChartPermissionId)
              }
            },
            {
              PermissionTypeName:{
                value:'客观',
                isIndeterminate:[1,2,3].includes(item.CheckList.filter(id => [obj.Items[1].ChartPermissionId,obj.Items[3].ChartPermissionId,
                  obj.Items[5].ChartPermissionId,obj.Items[7].ChartPermissionId].includes(id)).length),
                isCheckAll:item.CheckList.filter(id => [obj.Items[1].ChartPermissionId,obj.Items[3].ChartPermissionId,
                  obj.Items[5].ChartPermissionId,obj.Items[7].ChartPermissionId].includes(id)).length == 4,
                isDisabled:item.CheckList.filter(id => [obj.Items[1].ChartPermissionId,obj.Items[3].ChartPermissionId,
                  obj.Items[5].ChartPermissionId,obj.Items[7].ChartPermissionId].includes(id)).length ==4
              },
              medicine:{
                value:obj.Items[1].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[1].ChartPermissionId)
              },
              consumption:{
                value:obj.Items[3].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[3].ChartPermissionId)
              },
              technology:{
                value:obj.Items[5].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[5].ChartPermissionId)
              },
              smart:{
                value:obj.Items[7].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[7].ChartPermissionId)
              },
              strategy:{
                value:obj.Items[8].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[8].ChartPermissionId)
              },
              experts:{
                value:obj.Items[9].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[9].ChartPermissionId)
              },
              roadshow:{
                value:obj.Items[10].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[10].ChartPermissionId)
              },
              choose:{
                value:obj.Items[11].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[11].ChartPermissionId)
              },
              points:{
                value:obj.Items[12].ChartPermissionId,
                isDisabled:item.CheckList.includes(obj.Items[12].ChartPermissionId)
              }
            }
          ]

          auth.push(obj)
        })
        
    return auth
}


/* 编辑客户 */
function editHandle(item) {
  $router.push({
    path:'/editCustom',
    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(() => {});
}


/* 查看权限 */
const isLook = ref(false)//权限弹窗
const authList = ref([])
const lookAuthList = ref([])//查看的权限
const lookAuthListEquity = ref([])
const isPermissionTypeShow = ref(false)
function lookHandle(item) {
  authList.value = [];
  lookAuthList.value = [];
  customInterence.lookauth({
    CompanyId:item.CompanyId
  }).then(res => {
    if(res.Ret === 200) {
    let auth = [];			
      res.Data.List ?	res.Data.List.forEach(item=> { 
        auth.push(item.Items)
      }):''
      lookAuthList.value = auth.flat(Infinity);
      getRowSpan();
      let authEquity =[] //权益
      res.Data.ListRai ?	res.Data.ListRai.forEach(item=> {//权益
        // 过滤没有权限的套餐
        authEquity.push(item.Items.filter(it => item.CheckList.includes(it.ChartPermissionId)))
      }):''
      lookAuthListEquity.value = authEquity.flat(Infinity) //权益
      isPermissionTypeShow.value = lookAuthListEquity.value.some(item => !item.IsMerge)
      
      getSpanArr(lookAuthListEquity.value) //权益
    }
  })
  isLook.value = true;
}

/* 权益处理数据 */
const indexArrEquity = ref([])//权益
const spanArrEquity = ref([]);
const posEquity = ref(0)
function getSpanArr(data) {
  data.map((v, i, s) => {
    if (!v.PermissionTypeName) {
      indexArrEquity.value.push(i);
    }
  });
  for (var i = 0; i < data.length; i++) {
    let element = data[i]
    if (i === 0) {
      spanArrEquity.value.push(1);
      posEquity.value = 0;
    } else {
      // 判断当前元素与上一个元素是否相同（line为标记）
      if (element.PermissionName === data[i - 1].PermissionName) {
        if(element.IsMerge){
          // 主客观都有，需要合并
          spanArrEquity.value[posEquity.value] += 1;
          spanArrEquity.value.push(0);
        }else{
          // 主客观都有 不需要合并，说明是服务期限或者状态不一样
          spanArrEquity.value[posEquity.value] += 0.5;
          spanArrEquity.value.push(0.5);
        }
      } else {
        spanArrEquity.value.push(1);
        posEquity.value = i;
      }
    }
  }
  // console.log(this.indexArrEquity,this.spanArrEquity);
}

/* 处理合并数组 */
const rowSpanArr = ref([])
const position = ref(0)
function getRowSpan() {
  rowSpanArr.value = [];
  /* [2,0,1] */
  lookAuthList.value.forEach((item, index) => {
    if (index === 0) {
      rowSpanArr.value.push(1);
      position.value = 0;
    } else {
      if (lookAuthList.value[index].ClassifyName === lookAuthList.value[index - 1].ClassifyName) {
        rowSpanArr.value[position.value] += 1; //项目名称相同，合并到同一个数组中
        rowSpanArr.value.push(0);
        lookAuthList.value[index].ClassifyName = lookAuthList.value[index - 1].ClassifyName;
      } else {
        rowSpanArr.value.push(1);
        position.value = index;
      }
    }
  });
}
/* 合并行规则 */
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  if (columnIndex === 0) {
    const _row = this.rowSpanArr[rowIndex];
      return {
        rowspan: _row,
        colspan: 1
      };
  }
}


/* 查看备注 */
const lookRemarkTitle = ref('')//查看备注标题
const	lookRemarkList = ref([])//查看备注列表
const	lookRemarkTextarea = ref('')//备注的文本框
const	isRemarkLook = ref(false)////查看备注弹窗
const	lookRemarkItem = ref({})////查看备注的item项
function lookRemarkHandle(item) {
  /*
  lookRemarkTitle:'',//查看备注标题
  lookRemarkList:[],//查看备注列表
  */
  lookRemarkTitle.value = "备注";
  lookAuthList.value = [];
  lookRemarkItem.value = item;
  customInterence.lookRemarkAuth({
    CompanyId:item.CompanyId
  }).then(res => {
    if(res.Ret === 200) {
      lookRemarkList.value=res.Data;
    }
  })
  isRemarkLook.value = true;
}

const isPermissionDetailShow = ref(false)// 权限详情 弹框
const	researchDetailId = ref(0)
function researchDetailHandle(item) {
  isPermissionDetailShow.value = true
  researchDetailId.value = item.CompanyId
}



function handleContractModel() {

}

</script>
<template>
  <div class="customSearch_container">
    <div class="customSearch_top">
      <el-input
        placeholder="客户名称/社会信用码/手机号码/邮箱"
        v-model="search_txt"
        style="max-width: 520px"
        @keyup.enter="getTableData"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button
        type="primary"
        @click="
          pageinfo.page_no = 1;
          getTableData();
        "
        style="margin-left: 20px"
        >客户检索</el-button
      >
    </div>
    <div class="customSearch_cont">
      <el-table
        ref="table"
        :data="tableData"
        v-loading="isShowloadding"
        element-loading-text="客户检索中..."
        border
      >
        <el-table-column prop="CompanyName" label="客户名称" align="center">
          <template #default="scope">
            <span
              class="mouse-enter"
              :style="
                scope.row.Status == '潜在' ? '' : 'color:#bbb;cursor:pointer;'
              "
              @click="goDetail(scope.row)"
              v-if="scope.row.IsSuspend === 1 || scope.row.Status == '潜在'"
            >
              {{ scope.row.CompanyName }}
            </span>
            <span
              v-else
              :class="scope.row.BtnItem.BtnView ? 'customName' : ''"
              :style="{
                color: scope.row.BtnItem.BtnView ? '#409EFF' : '#606266',
                cursor: scope.row.BtnItem.BtnView ? 'pointer' : 'text',
              }"
              @click="goDetail(scope.row)"
              >{{ scope.row.CompanyName }}</span
            >
            <el-tooltip
              content="此客户存在长期且反复申请试用，但从未签约的情况，请谨慎领取"
              placement="top"
              :open-delay="500"
              v-if="RaiSellerRole && scope.row.IsScrounge == 1"
            >
              <img
                width="16"
                style="cursor: pointer"
                src="../../assets/img/icons/warning_triangle_yellow.png"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="CreditCode" label="社会信用码" align="center">
          <template #default="scope">
            <span :style="scope.row.IsSuspend === 1 ? 'color:#bbb' : ''">{{
              scope.row.CreditCode
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="客户状态" align="center">
          <template #default="scope">
            <p
              :style="
                scope.row.IsSuspend === 1
                  ? 'color:#bbb;margin:3px 0'
                  : 'margin:3px 0'
              "
              v-for="item in transformedArray(scope.row)"
              :key="item"
            >
              <template v-if="item.Status">
                {{ item.Status }}
                <br v-if="item.SigningStatus" />
                <el-tag
                  v-if="item.SigningStatus"
                  :type="item.SigningStatus === '已签约过' ? '' : 'warning'"
                  size="small"
                  >{{ item.SigningStatus }}</el-tag
                >
              </template>
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="CompanyType" label="客户类型" align="center">
          <template #default="scope">
            <span :style="scope.row.IsSuspend === 1 ? 'color:#bbb' : ''">{{
              scope.row.CompanyType
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="SellerName" label="销售" align="center">
          <template #default="scope">
            <span :style="scope.row.IsSuspend === 1 ? 'color:#bbb' : ''">{{
              scope.row.SellerName || "--"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Duration" label="时长（天）" align="center">
          <template #default="scope">
            <span :style="scope.row.IsSuspend === 1 ? 'color:#bbb' : ''">{{
              formateDuration(scope.row.Duration,scope.row.Status)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="120">
          <template
            #default="scope"
          >
            <!-- 新操作栏 -->
            <div style="color: #4099ef; font-size: 24px" v-if="!scope.row.ApproveStatus || scope.row.ApproveStatus === '待审批'">
              <span
                :class="item === 'BtnDelete' ? 'deletesty' : 'editsty'"
                style="margin: 0 5px"
                @click.stop="
                  itemclickHandle({
                    type: btnName(item, scope.row.IsSuspend),
                    data: scope.row,
                  })
                "
                v-for="(item, index) in btnList(scope.row.BtnItem, 'front')"
                :key="index"
                >{{ btnName(item, scope.row.IsSuspend) }}</span
              >
              <el-dropdown
                placement="bottom-start"
                @command="itemclickHandle"
                v-if="btnList(scope.row.BtnItem, 'back').length"
              >
                <span class="el-dropdown-link" style="margin:0 5px">
                  <el-icon><MoreFilled /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      :command="{
                        type: btnName(item, scope.row.IsSuspend),
                        data: scope.row,
                      }"
                      v-for="(item, index) in btnList(
                        scope.row.BtnItem,
                        'back'
                      )"
                      :key="index"
                    >
                      <span>{{ btnName(item, scope.row.IsSuspend) }}</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <div
            style="line-height: 44px; margin: 60px 0; color: #999"
            v-if="noResult"
          >
            <img
              src="~@/assets/img/cus_m/nodata.png"
              alt=""
              style="display: block; width: 160px; height: 128px; margin: auto"
            />
            <span>暂无信息</span>
          </div>
          <div
            style="line-height: 44px; margin: 200px 0; color: #999"
            v-else
          ></div>
        </template>
      </el-table>
      <!-- 分页 -->
      <el-col :span="24" class="toolbar">
        <mPage
          :total="pageinfo.total"
          :page_no="pageinfo.page_no"
          :pageSize="pageinfo.page_size"
          @handleCurrentChange="handleCurrentChange"
        />
      </el-col>
    </div>
    
  </div>
</template>
<style scoped lang="scss">
.customSearch_container {
	.customSearch_top {
		display: flex;
		// justify-content:flex-end;
		align-items: center;
		border: 1px solid #ECECEC;
		padding: 20px 30px;
		background: #fff;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	}
	.customSearch_cont {
		min-height: calc(100vh - 320px);
		padding: 20px 30px 80px;
		background: #fff;
		margin-top: 20px;
		position: relative;
		border: 1px solid #ECECEC;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	}
	.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;
				}
			}
		}
	}
	.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;
	
	}
	.mouse-enter {
		&:hover {
			text-decoration:underline;
		}
	}

  .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;
	
	}
  
  :deep(.el-dropdown) {
    vertical-align: middle;
  }
}
</style>

