<template>
  <div id="customer-statistics-container" class="customer-statistics-container">
    <div class="search-zone">
      <div class="search-box">
        <el-form label-width="0" :inline="true" :model="formInline">
            <el-form-item label="">
              <el-input v-model="searchParams.Keyword" placeholder="请输入客户名称" clearable class="search-item"
              @input="searchList" prefix-icon="el-icon-search" style="width: 240px;" ></el-input>
            </el-form-item>
            <el-form-item label="" v-if="currentSdId==AdminId ||Role=='admin'||Role=='ficc_admin'||Role=='rai_admin'">
              <el-cascader :options="saleList" style="width: 240px;margin: 0 0 8px 0;" filterable v-model="checkedSale"
                @change="saleChange" placeholder="请选择销售" clearable collapse-tags :show-all-levels="false"
                :props="{multiple:true,label:'RealName',value:'AdminId',children:'ChildrenList',emitPath:false}" key="sale" >
              </el-cascader>
            </el-form-item>
            <el-form-item label="">
              <el-cascader :options="serviceList" style="width: 240px;margin: 0 0 8px 0;" filterable v-model="checkedService"
                @change="serviceChange" placeholder="请选择套餐信息" clearable collapse-tags :show-all-levels="false"
                :props="{multiple:true,label:'title',value:'service_template_id',children:'children',emitPath:false}" key="serivce" >
              </el-cascader>
            </el-form-item>
            <el-form-item label="">
              <div class="date-box">
                <el-date-picker v-model="searchDate" type="daterange" @change="currentDateTab=0" style="max-width: 240px;margin-right: 15px;"
                  value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                <div class="composition-button-tabs">
                  <el-button size="large" v-for="(item,index) in dateButtonData" :key="item.tabId"
                  class="date-button" 
                  :class="[index==0?'first-button':index==(dateButtonData.length-1)?'last-button':'inner-button',currentDateTab==item.tabId?'selectTab':'']" 
                  @click="changeDateType(item)">{{ item.text }}</el-button>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="searchParams.TimeType" placeholder="请选择日期类型" @change="searchList" style="width: 240px;" clearable>
                  <el-option :label="item.label" :value="item.value" v-for="item in timeTypeData" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="searchParams.HasInvoice" placeholder="请选择开票状态" @change="searchList" style="width: 240px;" clearable>
                  <el-option :label="item.label" :value="item.value" v-for="item in invoiceData" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="searchParams.HasPayment" placeholder="请选择到款状态" @change="searchList" style="width: 240px;" clearable>
                  <el-option :label="item.label" :value="item.value" v-for="item in paymentData" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="amount-show-zone">
      <div class="amount-show-item" style="margin-right: 20px;">
        <div class="amount-item-head" @click="foldOrUnfold(0)" 
        :style="{cursor:tableData.length>0?'pointer':'',padding:invoiceIsFold?'8px 20px 8px 20px':'20px'}">
          <div class="amount-item-head-title" >
            已开票合计金额（换算后）：{{ invoiceAmountTotal }}（CNY）
          </div>
          <div class="fold-expand-row" v-show="tableData.length>0">
            <span class="amount-item-head-icon">
            {{ invoiceIsFold?'展开':'收起' }}
            </span>
            <i class="el-icon-arrow-down" :style="!invoiceIsFold && 'transform: rotate(180deg)'" style="color: #409EFF;"></i>
          </div>
        </div>
        <div class="amount-item-body-package" :style="{height:invoiceIsFold?'0':'66px'}">
          <div class="amount-item-body">
            <div class="amount-item-body-box" v-for="item in invoiceAmountList" :key="item.code">
              <img :src="item.flag_img" style="height: 40px;width: 40px;margin-right: 20px;" />
              <div class="amount-item-body-info">
                <span>{{ item.name }}（{{ item.code }}）</span>
                <span>{{ item.amount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="amount-show-item">
        <div class="amount-item-head" @click="foldOrUnfold(1)" 
        :style="{cursor:tableData.length>0?'pointer':'',padding:placementIsFold?'8px 20px 8px 20px':'20px'}">
          <div class="amount-item-head-title" >
            已到款合计金额（换算后）：{{ placementAmountTotal }}（CNY）
          </div>
          <div class="fold-expand-row" v-show="tableData.length>0">
            <span class="amount-item-head-icon">
            {{ placementIsFold?'展开':'收起' }}
            </span>
            <i class="el-icon-arrow-down" :style="!placementIsFold && 'transform: rotate(180deg)'" style="color: #409EFF;"></i>
          </div>
        </div>
        <div class="amount-item-body-package" :style="{height:placementIsFold?'0':'66px'}"> 
          <div class="amount-item-body">
            <div class="amount-item-body-box" v-for="item in placementAmountList" :key="item.code">
              <img :src="item.flag_img" style="height: 40px;width: 40px;margin-right: 20px;" />
              <div class="amount-item-body-info">
                <span>{{ item.name }}（{{ item.code }}）</span>
                <span>{{ item.amount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="table-zone">
      <el-table :data="tableData" border ref="tableRef" max-height="580" @sort-change="sortChange" >
        <el-table-column label="序号" align="center" prop="serialNumber" width="60">
          <template slot-scope="{row}">
            {{ row.serialNumber }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="company_name" align="center">
          <template slot-scope="{row,$index}">
            <el-tooltip :content="row.company_name" placement="top" :disabled="disabledCheck($index)">
              <div class="company-name-column"><span class="company-name-span">{{ row.company_name }}</span></div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="是否新客户" prop="contract_type" align="center">
          <template slot-scope="{row}">
            {{ row.contract_type==1?'是':'否' }}
          </template>
        </el-table-column>
        <el-table-column label="合同有效期" prop="date" align="center" show-overflow-tooltip >
          <template slot-scope="{row}">
            {{ row.date }}
          </template>
        </el-table-column>
        <el-table-column label="开票日" show-overflow-tooltip sortable="custom" prop="invoice_time" align="center">
          <template slot-scope="{row}">
            {{ row.invoice_time }}
          </template>
        </el-table-column>
        <el-table-column label="开票金额" prop="invoice_amount" align="center">
          <template slot-scope="{row}">
            {{ row.invoice_amount }}
          </template>
        </el-table-column>
        <el-table-column label="到款日" show-overflow-tooltip sortable="custom" prop="payment_date" align="center">
          <template slot-scope="{row}">
            {{ row.payment_date }}
          </template>
        </el-table-column>
        <el-table-column label="到款金额" prop="payment_amount" align="center">
          <template slot-scope="{row}">
            {{ row.payment_amount }}
          </template>
        </el-table-column>
        <el-table-column label="付款方式" prop="pay_type" align="center">
          <template slot-scope="{row}">
            <span>{{ payTypeArray[row.pay_type]?payTypeArray[row.pay_type].type:'' }}</span>
          </template>
        </el-table-column>
        <template v-if="isAdmin">
          <el-table-column label="销售" prop="seller_name" align="center">
            <template slot-scope="{row}">
              {{ row.seller_name }}
            </template>
          </el-table-column>
          <el-table-column label="销售组别" prop="seller_group_name" align="center">
            <template slot-scope="{row}">
              {{ row.seller_group_name }}
            </template>
          </el-table-column>
          <el-table-column label="销售类型" prop="seller_type" align="center">
            <template slot-scope="{row}">
              {{ row.seller_type==1?'FICC销售':'权益销售' }}
            </template>
          </el-table-column>
        </template>
        <el-table-column label="套餐信息" prop="services_name" align="center">
          <template slot-scope="{row}">
            {{ row.services_name }}
          </template>
        </el-table-column>
        <template #empty>
          <div class="table-noData">
            <img src="~@/assets/img/cus_m/nodata.png">
            <span>暂无数据</span>
          </div>
        </template>
      </el-table>
      <!-- 分页 -->
      <m-page :pageSize="searchParams.PageSize" :page_no="searchParams.CurrentIndex" 
      style="display: flex;justify-content: flex-end;margin-top: 20px;" 
      :total="total" @handleCurrentChange="changePageNo" />
    </div>
  </div>
</template>

<script>
import mPage from '@/components/mPage.vue';
import {customInterence} from '@/api/api.js'
  export default {
    name:'contractStatistics',
    components:{mPage},
    data() {
      const startDate=this.$moment().startOf('year').format('YYYY-MM-DD')
      const endDate=this.$moment(new Date()).format('YYYY-MM-DD')

      this.payTypeArray=[{id:0,type:''},{id:1,type:'年付'},{id:2,type:'半年付'},{id:3,type:'季付'},{id:4,type:'次付'}]
      this.timeTypeData=[{label:'开票日期',value:1},{label:'到款日期',value:2},{label:'开票日期&到款日期',value:3}]
      this.invoiceData=[{label:'未开票',value:0 },{label:'已开票',value:1}]
      this.paymentData=[{label:'未到款',value:0 },{label:'到款',value:1}]
      this.dateButtonData=[{text:'近1周',tabId:1,type:'week',diff:1},{text:'近1月',tabId:2,type:'month',diff:1},
        {text:'近2月',tabId:3,type:'month',diff:2},{text:'近3月',tabId:4,type:'month',diff:3}]

      return {
        currentSdId:process.env.NODE_ENV=='production'?13:233,
        serviceList:[],
        saleList:[],
        checkedService:[],
        checkedSale:[],
        searchParams:{
          CurrentIndex:1,
          PageSize:10,
          Keyword:'',
          ServiceType:'',
          StartDate:startDate,
          EndDate:endDate,
          // 1-开票日期 2-到款日期 3-开票日期&到款日期
          TimeType:1,
          SortType:'',
          SortParam:'',
          HasInvoice:'',// 开票状态 0未开票，1已开票
          HasPayment:'',// 到款状态 0未到款，1到款
          SellerIds:''
        },
        currentDateTab:0,
        searchDate:[startDate,endDate],
        tableData:[],
        total:0,
        invoiceAmountTotal:0,
        invoiceAmountList:[],
        placementAmountTotal:0,
        placementAmountList:[],
        invoiceIsFold:true,//开票合计是否收起
        placementIsFold:true,//到款合计是否收起
        domList:[]
      }
    },
    created(){
      if(this.currentSdId==this.AdminId ||this.Role=='admin'||this.Role=='ficc_admin'||this.Role=='rai_admin'){
        this.saleSelect()
      }
      this.getSimpleServiceList()
      this.getList()
    },
    watch:{
      searchDate(newVal){
        if(newVal){
          this.searchParams.StartDate=newVal[0]
          this.searchParams.EndDate=newVal[1]
        }else{
          this.searchParams.StartDate=''
          this.searchParams.EndDate=''
        }
        this.searchList()
      }
    },
    computed:{
      isAdmin(){
        return localStorage.getItem('Role').indexOf('admin')!=-1 || localStorage.getItem('RoleIdentity').indexOf('ficc_group')!=-1
      },
      Role() {
        let role = localStorage.getItem('Role') || '';
        return role;
      },
      AdminId() {
        let role = localStorage.getItem('AdminId') || '';
        return role;
      },
    },
    methods: {
      getSimpleServiceList(){
        customInterence.getSimpleServiceList().then(res=>{
          if(res.Ret!=200) return
          this.serviceList = res.Data || []
          // 后端最外层的数据没有给 service_template_id 删除tag时会报错，手动加
          this.serviceList.map((item,index) =>{
            item.service_template_id = 500+index
          })
        })
      },
      getList(){
        // console.log(this.searchParams);
        customInterence.getCTContractStatistics(this.searchParams).then(res=>{
          if(res.Ret!=200) return
          this.tableData=[]
          let tempData = res.Data.data_list || []
          this.total = res.Data.Paging.Totals
          this.invoiceAmountTotal=res.Data.invoice_total
          this.invoiceAmountList = res.Data.invoice_currency_total || []
          this.placementAmountTotal=res.Data.payment_total
          this.placementAmountList = res.Data.payment_currency_total || []
          tempData.map((item,index) =>{
            item.invoice_payment_list.map((it,ind) =>{
              this.tableData.push({
                serialNumber:this.searchParams.PageSize*(this.searchParams.CurrentIndex-1)+index+1,
                ...item,date:item.start_date+'至'+item.end_date,...it
              })
            })
          })
        })
      },
      searchList(){
        this.searchParams.CurrentIndex=1
        this.getList()
      },
      changePageNo(pageNo){
        this.searchParams.CurrentIndex = pageNo
        this.getList()
      },
      saleChange(value){
        this.searchParams.SellerIds = value.join(',')
        this.searchList()
      },
      serviceChange(value){
        this.searchParams.ServiceType = value.join(',')
        this.searchList()
      },
      changeDateType({tabId,type,diff}){
        if(this.currentDateTab==tabId) return
        this.currentDateTab=tabId
        let startOfType='month'
        if(type=='week'){
          startOfType='isoWeek'
        }
        this.searchDate=[this.$moment().startOf(startOfType).subtract((diff-1), type+'s').format('YYYY-MM-DD'),
        this.$moment().format('YYYY-MM-DD')]
      },
      foldOrUnfold(type){
        if(this.tableData.length==0){
          return 
        }
        // type: 0-开票  1-到款
        if(type){
          this.placementIsFold = !this.placementIsFold
        }else{
          this.invoiceIsFold = !this.invoiceIsFold
        }
      },
      sortChange({order,prop}){
        this.searchParams.SortType=order=='descending'?'desc':order=='ascending'?'asc':''
        this.searchParams.SortParam=order?prop:''
        this.searchList()
      },
      disabledCheck(e){
        if(!this.domList[e]) return true
        return this.domList[e].offsetWidth<=this.domList[e].parentNode.offsetWidth
      },
      // 获取销售下拉列表
      saleSelect(){
        customInterence.sellerSelectList({}).then(res=>{
          console.log(res)
          this.saleList = res.Data.List || []
        })
      }
    },
    mounted(){
      this.$nextTick(()=>{
        this.domList=$('.company-name-span')
        // console.log(this.domList);
      })
    },
    updated(){
      this.domList=$('.company-name-span')
      // console.log(this.domList);
    }
  }
</script>

<style lang="scss" scoped>
  .customer-statistics-container{
    min-height: calc(100vh - 110px);
    .search-zone{
      margin-bottom: 20px;
      padding: 20px 30px 12px;
      background-color: white;
      border-radius: 4px;
      .search-box{
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .search-item{
          width: 232px;
          margin: 0 0 8px 0;
        }
        .date-box{
          display: flex;
          align-items: center;
          margin: 0 0 8px 0;
          .composition-button-tabs{
            white-space: nowrap;
            .date-button{
              height: 40px;
              color: #999999;
              border: 1px solid #DCDFE6;
              margin: 0;
              width: 60px;
              padding: 12px 6px;
            }
            .first-button{
              border-color: #DCDFE6;
              border-style: solid;
              border-width: 1px 0 1px 1px;
              border-radius: 4px 0 0 4px;
            }
            .inner-button{
              border: 1px solid #DCDFE6;
              border-radius: 0;
            }
            .last-button{
              border-color: #DCDFE6;
              border-style: solid;
              border-width: 1px 1px 1px 0;
              border-radius:0 4px 4px 0 ;
            }
            .selectTab{
              color:white;
              background-color: #409EFF;
            }
          }
        }
      }

    }
    .amount-show-zone{
      display: flex;
      align-items: flex-start;
      flex-wrap: wrap;
      margin-bottom: 10px;
      .amount-show-item{
        margin-bottom: 10px;
        background: #FFFFFF;
        // border: 1px solid #DCDFE6;
        // box-shadow: 0px 4px 12px rgba(153, 153, 153, 0.08);
        border-radius: 8px;
        width: 725px;
        box-sizing: border-box;
        .amount-item-head{
          transition: all 0.1s ease;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .amount-item-head-title{
            font-weight: 600;
            font-size: 18px;
            color: #000000;
          }
          .fold-expand-row{
            display: flex;
            align-items: center;
            .amount-item-head-icon{
              font-weight: 400;
              font-size: 14px;
              color: #409EFF;
              margin-right: 4px;
            }
          }

        }
        .amount-item-body-package{
          overflow: hidden;
          transition: height 0.1s ease;
          .amount-item-body{
            padding: 6px 20px 16px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .amount-item-body-box{
              display: flex;
              align-items: center;
              width: 220px;
              .amount-item-body-info{
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                span{
                  font-weight: 400;
                  font-size: 14px;
                  color: #666666;
                  margin-bottom: 2px;
                  &:last-child{
                    font-weight: 700;
                    font-size: 16px;
                    color: #333333;
                  }
                }
              }
            }
          }
        }
      }
    }
    .table-zone{
      padding: 20px 30px 65px;
      background-color: white;
      border-radius: 4px;
      .company-name-column{
        max-width: 100%;
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .table-noData{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin: 18vh 0;
        img{
          height: 110px;
          width: 136px;
        }
        span{
          font-weight: 400;
          font-size: 16px;
          color: #999999;
        }
      }
    }
  }
  .el-form-item{
    margin-bottom: 0;
  }
</style>