<script setup>
import { ref } from 'vue'
import moment from 'moment'
import _ from 'lodash'
import { useRouter } from 'vue-router'
import { customInterence } from '@/api/api.js'
import { locationOptions } from "./location"

const router = useRouter()

const Role = localStorage.getItem('Role')

const dataList = ref([])
const allDataList = ref([])
const isAdmin = ref(false)
// 获取区域客户列表
function getList(){
  customInterence.getRegionCustom({
    Date: moment(new Date()).format('YYYY-MM-DD'),
    ProductId:1
  }).then(res=>{
    if(res.Ret==200){
      isAdmin.value=res.Data.IsAdmin
      // 过滤掉没有省市、以及省市没有客户的数据
      dataList.value = res.Data.List 
        ? res.Data.List.filter(element => {
            element.Item=element.Item.filter(item => item.Name && item.CompanyAreaNumNumList[0].TotalNum)
            return element.Name && element.CompanyAreaNumNumList[0].TotalNum
          })
        : []
    }
    let index=1
    dataList.value.forEach(element => {
      element.ind = index
      index++
      element.Item.forEach((item=>{
        item.ind = index
        // 所在市级的省级
        item.parentName = element.Name
        index++
      }))
    });

    handleSortChange({order:'descending',prop:'FormalNum'})

    allDataList.value=_.cloneDeep(dataList.value)
  })
}
getList()

 // 排序
function handleSortChange({order,prop}){
  dataList.value.sort((a,b)=>{
    if(order == 'ascending'){
      return a.CompanyAreaNumNumList[0][prop]-b.CompanyAreaNumNumList[0][prop]
    }else if(order == 'descending'){
      return b.CompanyAreaNumNumList[0][prop]-a.CompanyAreaNumNumList[0][prop]
    }
  })
  dataList.value.forEach(element => {
    if(element.Item){
      element.Item.sort((a,b)=> {
        if(order == 'ascending'){
          return a.CompanyAreaNumNumList[0][prop]-b.CompanyAreaNumNumList[0][prop]
        }else if(order == 'descending'){
          return b.CompanyAreaNumNumList[0][prop]-a.CompanyAreaNumNumList[0][prop]
        }
      })
    }
    
  });
}

 // 地区搜索
function handleRegionChange(regionData) {
  let tempArr=[]
  if(regionData.length>0){
    tempArr=allDataList.value.filter(item =>regionData.findIndex(it => it[0]==item.Name)!=-1)
    // 为了不影响 做一次深拷贝  filter不会改变原数组内容，但是会改变原数组指向 使得原数组和新数组的指向一样
    dataList.value = _.cloneDeep(tempArr)
    dataList.value.forEach((element,index) =>{
      element.Item=element.Item.filter(item => regionData.findIndex(it => it[0]==element.Name && it[1]==item.Name)!=-1)
      if(element.Item.length==0){
        dataList.value.splice(index,1)
      }
    })
  }else{
    tempArr=allDataList.value.filter(item => true)
    dataList.value = _.cloneDeep(tempArr)
  }
  
}

// 点击进入详情
function toDetail(row,status){
  // console.log(row,status);
  // 非超管、ficc管理员人员 查看详情
  if(!isAdmin.value){
    console.log(row,status);
    let ids = ''
    const StatusMap = {
      '正式':'FormalIds',
      '试用':'TryOutIds',
      '推进':'TryStagePushIds',
      '跟踪':'TryStageFollowIds',
      '预备':'TryStageReadyIds',
      '未分类':'TryStageInitIds'
    }
    ids = row.CompanyAreaNumNumList[0][StatusMap[status]]
    if(!ids) return
    router.push({
      path:'/regionCustomerDetail',
      query:{
        title:row.parentName?`${row.parentName}/${row.Name}/${status}`:`${row.Name}/${status}`,
        ids:ids
      }
    })
    return
  }

  const StatusArray=['未分类','推进','跟踪','预备']
  let Status = StatusArray.includes(status) ? '试用':status
  let TryStage = ['试用','正式'].includes(status) ? 0:(StatusArray.findIndex(item =>item==status)+1)
  let regionData=[]
  if(!row.Item){
    regionData.push([row.parentName,row.Name])
  }else{
    row.Item.map(item =>{ 
      regionData.push([row.Name,item.Name])
    })
  } 
  sessionStorage.setItem('regionData',JSON.stringify(regionData))

  router.push({
    name:'customList',
    params:{CompanyType:'ficc',Status,TryStage,valueLocation:'regionData'}
  })
}

</script>
<template>
  <div id="region-custom-container">
    <div class="search-zone">
      <el-cascader collapse-tags clearable
      :props="{multiple: true,value:'name',children:'city',label:'name'}" :options="locationOptions"  
      @change="handleRegionChange" placeholder="请选择区域" 
      style="width:240px;marginBottom:30px;"></el-cascader>
    </div>
    <el-table :data="dataList" border @sort-change="handleSortChange" 
    row-key="ind" :tree-props="{ children: 'Item' }">
      <el-table-column label="区域" align="center" prop="region">
        <template #default="{row}">
          {{row.Name}}
        </template>
      </el-table-column>
      <el-table-column label="正式" align="center" sortable="custom" prop="FormalNum">
        <template #default="{row}">
          <span class="table-data-detail" v-if="row.CompanyAreaNumNumList[0].FormalNum!=0"
           @click="toDetail(row,'正式')">{{row.CompanyAreaNumNumList[0].FormalNum}}</span>
          <span v-else>{{row.CompanyAreaNumNumList[0].FormalNum}}</span>
        </template>
      </el-table-column>
      <el-table-column label="试用" align="center" sortable="custom" prop="TryOutNum">
        <template #default="{row}">
          <span class="table-data-detail" v-if="row.CompanyAreaNumNumList[0].TryOutNum!=0" 
          @click="toDetail(row,'试用')">{{row.CompanyAreaNumNumList[0].TryOutNum}}</span>
          <span v-else>{{row.CompanyAreaNumNumList[0].TryOutNum}}</span>
        </template>
      </el-table-column>
      <el-table-column label="推进" align="center" sortable="custom" prop="TryStagePushNum">
        <template #default="{row}">
          <span class="table-data-detail" v-if="row.CompanyAreaNumNumList[0].TryStagePushNum!=0"
           @click="toDetail(row,'推进')">{{row.CompanyAreaNumNumList[0].TryStagePushNum}}</span>
          <span v-else>{{row.CompanyAreaNumNumList[0].TryStagePushNum}}</span>
        </template>
      </el-table-column>
      <el-table-column label="跟踪" align="center" sortable="custom" prop="TryStageFollowNum">
        <template #default="{row}">
          <span class="table-data-detail" v-if="row.CompanyAreaNumNumList[0].TryStageFollowNum!=0" 
          @click="toDetail(row,'跟踪')">{{row.CompanyAreaNumNumList[0].TryStageFollowNum}}</span>
          <span v-else>{{row.CompanyAreaNumNumList[0].TryStageFollowNum}}</span>
        </template>
      </el-table-column>
      <el-table-column label="预备" align="center" sortable="custom" prop="TryStageReadyNum">
        <template #default="{row}">
          <span class="table-data-detail" v-if="row.CompanyAreaNumNumList[0].TryStageReadyNum!=0" 
          @click="toDetail(row,'预备')">{{row.CompanyAreaNumNumList[0].TryStageReadyNum}}</span>
          <span v-else>{{row.CompanyAreaNumNumList[0].TryStageReadyNum}}</span>
        </template>
      </el-table-column>
      <el-table-column label="未分类" align="center" sortable="custom" prop="TryStageInitNum">
        <template #default="{row}">
          <span class="table-data-detail" v-if="row.CompanyAreaNumNumList[0].TryStageInitNum!=0" 
          @click="toDetail(row,'未分类')">{{row.CompanyAreaNumNumList[0].TryStageInitNum}}</span>
          <span v-else>{{row.CompanyAreaNumNumList[0].TryStageInitNum}}</span>
        </template>
      </el-table-column>
      <el-table-column label="合计" align="center" sortable="custom" prop="TotalNum">
        <!-- 自定义表头 -->
        <template #header>
          <span>
            合计
          </span>
          <el-tooltip content="该区域的正式和试用客户合计数量" placement="top" effect="dark">
            <i class="el-icon-info" style="color: #333333;"/>
          </el-tooltip>
        </template>
        <!-- 自定义表头 -->
        <template #default="{row}">
          {{row.CompanyAreaNumNumList[0].TotalNum}}
        </template>
      </el-table-column>
      <template #empty>
        <div class="table-noData">
          <img src="~@/assets/img/data_m/nodata-big.png">
          <span>暂无数据</span>
        </div>
      </template>
    </el-table>
  </div>
</template>
<style scoped lang="scss">
 #region-custom-container{
    background-color: white;
    padding: 30px;
    height: calc(100vh - 120px);
    overflow-y: auto;
    box-sizing: border-box;
    .table-data-detail{
      color: rgb(64, 158, 255);
      cursor: pointer;
    }
    .table-noData{
      margin-top:28vh;
      color:#999;
      img{
        display:block;
        width:260px;
        height:200px;
        margin: auto;
      }
    }

    :deep(.el-input__inner::placeholder){
      color: #606266;
      font-size: 16px;
    }
    :deep(.el-table__indent){
      padding-left:0!important;
    }
    :deep(.el-table__placeholder){
      width: 0;
    }
    :deep(.el-table__expand-icon){
      position: absolute;
      left: 5px;
    }
  }
</style>