<template>
  <scroll-view class="main">
    <view class="topBox">
      <view class="top">
        <picker :value="selectServiceId" :range="selectServiceList" @change="handleChangeService" range-key="label">
          <span class="service">{{ selectServiceList[selectIndex].label }}</span>
        </picker>
        <span class="time" @click="handleChangeSelect({id:3})">{{`${$moment(startDate).format('YYYY/MM')}-${$moment(endDate).format('YYYY/MM')}`}}</span>
      </view>



      <view class="topFilterBox">
        <view class="filterItem" v-for="(item,index) in menuList" :key="index" @click="handleChangeSelect(item)">
          <view class="imgIcon" :style="selectFilter===item.id ? 'background:#f0f7fe;' : 'background:#f6f7f8;'">
            <image class="img" :src="item.id===selectFilter?item.active: item.src"/>
          </view>
          <view class="filterLabel" :style="selectFilter===item.id ? 'color:#5B96E9' :'color:#808D97'">{{item.name}}
          </view>
        </view>
      </view>
    </view>


    <view class="dataList">
      <view class="dataItem" v-for="(item,index) in dataList" :key="index" @click="handleGoDetail(item)" :style="{boxShadow: item.SETTLEMENT_STATE===0 || item.SETTLEMENT_STATE===2?'0 0px 6rpx #f9b297':''}">
        <div class="content-index">{{index+1}}</div>
        <view class="itemRow" >
          <view class="projectName">{{ item.BUSINESSPROJECT_NAME }}</view>
          <view class="stateName" :style="{color: item.SETTLEMENT_STATE===2?'#FF814FFF':''}">{{ item.SETTLEMENT_STATE===0?'待结算':item.SETTLEMENT_STATE===1?'已结算':item.SETTLEMENT_STATE===2?'审批中':'' }}</view>
        </view>
        <view class="itemCenterRow" style="margin: 60rpx 0 20rpx">
          <view class="value">{{ item.SETTLEMENT_TYPE===1?$util.getMoney(item.REVENUE_AMOUNT):item.SETTLEMENT_TYPE===2?$util.getMoney(item.CURREVENUE_AMOUNT):'' }}</view>
          <view class="label">{{ item.SETTLEMENT_TYPE===1?'累计营业额':item.SETTLEMENT_TYPE===2?'本月营业额':'' }}</view>
        </view>
        <view class="itemRow">
          <view class="leftName">{{item.CURRENT_PERIOD || ''}}</view>
<!--          <view class="rightName">{{ $util.getMoney(item.REVENUE_AMOUNT) }}</view>-->

          <view class="rightName">{{item.SETTLEMENT_TYPE===1?'年度结算':item.SETTLEMENT_TYPE===2?'月度结算':''}}：{{item.SETTLEMENT_DATE || ''}} </view>
        </view>

        <view class="line"></view>
        <view class="itemRow">
          <view class="leftName"><span class="radio" style="background: #44bea3"></span>{{ item.MERCHANTS_NAME || '' }}</view>
          <view class="rightName"></view>
        </view>
        <view class="itemRow">
          <view class="leftName"><span class="radio" style="background: #398EFE"></span>{{item.SERVERPARTSHOP_NAME || ''}}</view>
        </view>
      </view>
    </view>
    <view class="load-more" v-if="dataList.length>0">
      <text>{{!isEnd ? '正在加载,请稍后...':'——— 我是有底线的 ———'}}</text>
    </view>
    <UniPop :show="showPop" @hidePopup="closePop" type="bottom" @touchmove.prevent round="true">
      <view class="uniPopup">
        <view class="uniPopupTop">
          <text class="uniPopupTitle">筛选</text>
          <image @click="closePop" class="close" src="https://eshangtech.com/ShopICO/ahyd-BID/examine/close.svg"></image>
        </view>

        <view class="filterBox">
          <view class="filterTitle">统计时间</view>
          <view class="filterTimeBox">
            <picker class="timeSelect" mode="date" fields="month" :value="$moment(startDate).format('YYYY-MM')" :start="'2023-01-01'" :end="end" @change="handleGetStartTime">{{startDate}}</picker>
            <span class="timeSelect" style="margin: 0 4rpx">-</span>
            <picker class="timeSelect" mode="date" fields="month" :value="$moment(endDate).format('YYYY-MM')" :start="start" :end="end" @change="handleGetEndTime">{{endDate}}</picker>
          </view>
        </view>

        <view class="filterBox" style="margin-top: 48rpx">
          <view class="filterTitle">结算类型</view>
          <view class="filterItemList">
            <view :class="SettlementType===0?'filterItem selectFilterItem':'filterItem'" @click="handleChangeSettlementType(0)">全部</view>
            <view :class="SettlementType===1?'filterItem selectFilterItem':'filterItem'" @click="handleChangeSettlementType(1)">年度</view>
            <view :class="SettlementType===2?'filterItem selectFilterItem':'filterItem'" @click="handleChangeSettlementType(2)">月度</view>
          </view>
        </view>

        <view class="button" @click="handleSubmit">查询</view>
      </view>
    </UniPop>
  </scroll-view>
</template>
<script>
import request from '@/util/index.js'
import Store from "../../store/store";
import UniPop from '@/components/uni-popup.vue'
import moment from "moment";
import {wrapTreeNode} from "../../util/dateTime";
  export default {
    components: {UniPop},
    data() {
      return {
        menuList: [
          { //列表头部菜单选项标签
            name: '全部',
            src: 'https://eshangtech.com/ShopICO/ahyd-BID/expense/type/yifq.png',
            active: 'https://eshangtech.com/ShopICO/ahyd-BID/expense/type/yifqz.png',
            id: 4
          }, {
            name: '待结算',
            src: 'https://eshangtech.com/ShopICO/ahyd-BID/expense/type/shenp.png',
            active: 'https://eshangtech.com/ShopICO/ahyd-BID/expense/type/shenpz.png',
            id: "0,2"
          }, {
            name: '已结算',
            src: 'https://eshangtech.com/ShopICO/ahyd-BID/expense/type/yichl.png',
            active: 'https://eshangtech.com/ShopICO/ahyd-BID/expense/type/yichlz.png',
            id: 1
          }, {
            name: '更多筛选',
            src: 'https://eshangtech.com/ShopICO/ahyd-BID/expense/type/shaix.png',
            active: 'https://eshangtech.com/ShopICO/ahyd-BID/expense/type/shaixz.png',
            id: 3
          } ],
        selectFilter: 4,
        dataList: [],
        selectServiceList:[],// 这个用户可以选择的服务区
        selectIndex:0,// 选中的索引
        selectServiceId:'',// 选择的服务区
        showPop: false,// 显示更多筛选
        startDate:'',// 开始时间
        endDate:'',// 结束时间
        start:'',// 限制的开始时间
        end:'',// 限制的结束时间
        SettlementType: 0,// 结算模式
        PageIndex: 1,// 默认的页数
        isEnd: false,// 判断是否到底了
        useInfo:{},// 用户详情
      }
    },
    onLoad(){
      let userInfo = uni.getStorageSync('vuex')
      userInfo = JSON.parse(userInfo)
      this.useInfo = JSON.parse(JSON.stringify(userInfo))
      console.log('this.useInfo',this.useInfo)

      this.startDate = this.$moment().startOf('year').format('YYYY-MM')
      this.endDate = this.$moment().subtract(1,'months').format('YYYY-MM')
      console.log('Store.state.userData',Store.state.userData)
      this.selectServiceList = Store.state.userData.serverPartList
      if(this.selectServiceList[0].value==='424'){
        let list = []
        this.selectServiceList.forEach(item=>{
          if(item.value!=='424'){
            list.push(item)
          }
        })
        this.selectServiceList = list
      }
      this.selectServiceId = this.selectServiceList[0].value
      this.handleGetPageData()
    },
    onShow(){
      let reload = uni.getStorageSync('reolad')
      if(reload==='true'){
        this.dataList = []
        this.handleGetPageData()
        uni.setStorageSync('reolad','')
      }
      let isGoNewMonth = uni.getStorageSync('handleGetNewMonth')
      let handleGetNewMonthObj = uni.getStorageSync('handleGetNewMonthObj')
      let handleGetNewMonthTime = uni.getStorageSync('handleGetNewMonthTime')
      console.log('isGoNewMonth',isGoNewMonth)
      console.log('handleGetNewMonthObj',handleGetNewMonthObj)
      console.log('handleGetNewMonthTime',handleGetNewMonthTime)
      if(isGoNewMonth==='true'){
        this.handleGetNewMonth(handleGetNewMonthObj,handleGetNewMonthTime)
        uni.setStorageSync('handleGetNewMonth','')
        uni.setStorageSync('handleGetNewMonthObj','')
        uni.setStorageSync('handleGetNewMonthTime','')
      }
    },
    methods:{
      // 自动跳转到指定月份的方法
      async handleGetNewMonth(obj,time){
        uni.showLoading({
          title: '正在加载...'
        })
        const req = {
          ServerpartId: obj?.SERVERPART_ID,
          ServerpartShopId: obj?.SERVERPARTSHOP_ID,
          StartDate: this.$moment(time).format('YYYYMM'),
          EndDate: this.$moment(time).format('YYYYMM'),
        }
        const data = await request.$webGet('EShangApiMain/BusinessProject/GetProjectAccountList',req)
        console.log('data',data)
        let res = data.Result_Data.List
        let bigObj = {}
        if(res && res.length>0){
          res.forEach(item=>{
            if(item.SETTLEMENT_TYPE===2 && this.$moment(item.ENDDATE).format('YYYYMM') === this.$moment(time).format('YYYYMM')){
              if (item.SHOPROYALTY_ID === obj.SHOPROYALTY_ID) {
                bigObj = item
              }
            }
          })
        }
        console.log('bigObj',bigObj)
        let result = {
          ...bigObj,
          Approvalstate: bigObj.SETTLEMENT_STATE === 0 ? 0 : bigObj.SETTLEMENT_STATE === 1 ? 9 : bigObj.SETTLEMENT_STATE === 2 ? 1 : '',
          startTime: this.$moment(bigObj.SETTLEMENT_DATE  + (bigObj.SETTLEMENT_TYPE===1?'':'/01') ).startOf('months').format('YYYY-MM-DD'),
          endTime: this.$moment(bigObj.SETTLEMENT_DATE  + (bigObj.SETTLEMENT_TYPE===1?'':'/01')).endOf('months').format('YYYY-MM-DD'),
        }
        this.$util.toNextRoute('navigateTo', `/pages/settlementApproval/detail?obj=${JSON.stringify(result)}&staticMonth=${time}`)

        uni.hideLoading()
      },
      // 改变筛选条件
      handleChangeSelect(obj){
        // 当为3时 就是点击了更多筛选
        if(Number(obj.id)===3){
          this.showPop = true
        }else{
          this.selectFilter = obj.id
          this.handleGetPageData()
        }
        this.isEnd = false
        this.PageIndex = 1
      },
      // 改变服务区
      handleChangeService(e){
        console.log('e',e)
        this.selectIndex = Number(e.target.value)
        this.selectServiceId = this.selectServiceList[Number(e.target.value)].value
        this.handleGetPageData()
        this.isEnd = false
        this.PageIndex = 1
      },
      // 关闭弹出框
      closePop(){
        this.showPop = false
      },
      // 改变开始时间
      handleGetStartTime(e){
        this.start = e.detail.value
        this.startDate = moment(e.detail.value).format('YYYY-MM')
      },
      // 改变结束时间
      handleGetEndTime(e){
        this.endDate = moment(e.detail.value).format('YYYY-MM')
      },
      handleChangeSettlementType(e){
        this.SettlementType = e
      },
      handleSubmit(){
        this.isEnd = false
        this.PageIndex = 1
        this.closePop()
        this.handleGetPageData()
      },
      // 跳转
      handleGoDetail(obj){
        console.log('obj',obj)
        let res = {
          ...obj,
          Approvalstate: obj.SETTLEMENT_STATE === 0 ? 0 : obj.SETTLEMENT_STATE === 1 ? 9 : obj.SETTLEMENT_STATE === 2 ? 1 : '',
          // startTime: new Date(obj.STARTDATE).getTime() < new Date(obj.SETTLEMENT_DATE).getTime()?this.$moment(obj.SETTLEMENT_DATE).startOf('months').format('YYYY-MM-DD'):this.$moment(obj.STARTDATE).format('YYYY-MM-DD'),
          // endTime: new Date(obj.ENDDATE).getTime() > new Date(obj.SETTLEMENT_DATE).getTime()?this.$moment(obj.SETTLEMENT_DATE).startOf('months').format('YYYY-MM-DD'):this.$moment(obj.STARTDATE).format('YYYY-MM-DD')
          startTime: this.$moment(obj.SETTLEMENT_DATE + (obj.SETTLEMENT_TYPE===1?'':'/01')).startOf('month').format('YYYY-MM-DD'),
          endTime: this.$moment(obj.SETTLEMENT_DATE +(obj.SETTLEMENT_TYPE===1?'':'/01')).endOf('month').format('YYYY-MM-DD'),
        }
        this.$util.toNextRoute('navigateTo', `/pages/settlementApproval/detail?obj=${JSON.stringify(res)}&staticMonth=${res.SETTLEMENT_DATE + (obj.SETTLEMENT_TYPE===1?'':'/01')}`)
      },
      async handleGetPageData(){
        const req = {
          ServerpartId: this.selectServiceId,
          SettlementState: this.selectFilter===4?'': this.selectFilter,
          SettlementType: this.SettlementType || '',
          StartDate: this.startDate?this.$moment(this.startDate).format('YYYYMM'):'',
          EndDate: this.endDate?this.$moment(this.endDate).format('YYYYMM'):'',
          PageIndex: this.PageIndex,
          PageSize: 10,
          UserId: this.useInfo.userData.UserId
        }
        uni.showLoading({
          title: '正在加载...'
        })
        const data = await request.$webGet('EShangApiMain/BusinessProject/GetProjectAccountList',req)
        console.log('data',data)
        this.dataList =  this.PageIndex === 1?data.Result_Data.List:[...this.dataList,...data.Result_Data.List]
        console.log('this.dataList',this.dataList)
        if(data.Result_Data.TotalCount < 10){
          this.isEnd = true
        }
        uni.hideLoading()
      },
      // 下拉刷新
      onPullDownRefresh(){
        console.log('1111')
        this.PageIndex = 1
        this.isEnd = false
        this.dataList = []
        this.handleGetPageData()
        setTimeout(function() {
          uni.stopPullDownRefresh()
        }, 1000)
      },
      // 滚动到底部
      onReachBottom(){
        console.log('1111')
        if(!this.isEnd){
          this.PageIndex = this.PageIndex + 1
          this.handleGetPageData()
        }
      }
    }
  }
</script>

<style scoped lang="scss">
.main{
  width: 100%;
  min-height: 100vh;
  box-sizing: border-box;
  .topBox{
    width: 100%;
    box-sizing: border-box;
    padding: 24rpx 16rpx;
    background: #fff;
    .top{
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16rpx;
      .service{
        font-size: 24rpx;
        color: #010101;
        border-radius: 24rpx;
        padding: 4rpx 16rpx;
        background-color: #DEDEDE;
        text-align: center;
      }
      .time{
        font-size: 24rpx;
        color: #010101;
        border-radius: 24rpx;
        padding: 4rpx 16rpx;
        background-color: #DEDEDE;
        text-align: center;
      }
    }

    .topFilterBox{
      width: 100%;
      display: flex;
      box-sizing: border-box;
      .filterItem{
        width: 25%;
        display: flex;
        flex-direction: column;
        align-items: center;
        .imgIcon{
          height: 37px;
          width: 37px;
          border-radius: 50%;
          overflow: hidden;
          margin-bottom: 16rpx;
          padding: 9px;
          box-sizing: border-box;

          .img{
            width: 100%;
            height: 100%;
          }
        }
        .filterLabel{
          font-size: 24rpx;
          text-align: center;
          color: #808D97;
        }
      }
    }
  }

  .dataList{
    width: 100%;
    box-sizing: border-box;
    padding: 0 24rpx;
    .dataItem{
      width: 100%;
      box-sizing: border-box;
      background: #fff;
      padding: 16rpx;
      margin: 24rpx 0;
      border-radius: 8rpx;
      box-shadow: 0 0px 6rpx #E2E2E2;
      position: relative;
      .content-index {
        width: 42rpx;
        height: 32rpx;
        line-height: 32rpx;
        font-size: 24rpx;
        color: #fff;
        text-align: center;
        background-color: #fb8b56;
        position: absolute;
        top: 26rpx;
        left: -4rpx;
        box-shadow: 4rpx 4rpx 2rpx 0 rgba(238,112,27,0.5)
      }
      .itemRow{
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .projectName{
          width: 60%;
          font-size: 28rpx;
          height: 54rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          color: #333333;
          box-sizing: border-box;
          padding-left: 40rpx;
        }
        .leftName{
          color: #686868;
          font-size: 24rpx;
          .radio{
            display: inline-block;
            width: 14rpx;
            height: 14rpx;
            border-radius: 14rpx;
            margin: 0 8px 0 5px;
          }
        }
        .stateName{
          font-size: 28rpx;
          color: #999999;
        }
        .rightName{
          color: #686868;
          font-size: 24rpx;
          .radio{
            display: inline-block;
            width: 14rpx;
            height: 14rpx;
            border-radius: 14rpx;
            margin: 0 8px 0 5px;
          }
        }
      }
      .itemCenterRow{
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        .value{
          font-size: 16px;
          font-weight: 600;
          color: #FF814FFF;
        }
        .label{
          font-size: 12px;
          color: #999999;
        }
      }
      .line{
        height: 2rpx;
        width: 100%;
        background-color: #eee;
        margin-bottom: 18rpx;
        margin-top: 16rpx;
      }
    }
  }

  .uniPopup{
    width: 100%;
    height: 400px;
    box-sizing: border-box;
    padding: 32rpx;
    .uniPopupTop{
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .uniPopupTitle{
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 32rpx;
        color: #160002;
        line-height: 44rpx;
        text-align: left;
        font-style: normal;
      }
      .close{
        width: 40rpx;
        height: 40rpx;
      }
    }
    .filterBox{
      margin-top: 40rpx;
      .filterTitle{
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 28rpx;
        color: #212226;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
      }
      .filterTimeBox{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 24rpx;
        .timeSelect{
          width: calc((100% - 20px)/2);
        }
      }
      .filterItemList{
        margin: 24rpx;
        display: flex;
        flex-wrap: wrap;
        .filterItem{
          width: calc((100% - 32rpx)/3);
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16rpx;
          margin-bottom: 16rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 28rpx;
          color: #160002;
          line-height: 40rpx;
          text-align: right;
          font-style: normal;
          background: #F5F5F5;
          border-radius: 8rpx;
          padding: 12rpx 0;
        }
        .filterItem:nth-child(3){
          margin-right: 0;
        }
        .selectFilterItem{
          color: #2363FF;
          background: #ECF2FF;
        }
      }
    }
    .button{
      background: #2363FF;
      border-radius: 8rpx;
      width: calc(100% - 64rpx);
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 32rpx;
      color: #FFFFFF;
      line-height: 44rpx;
      text-align: left;
      font-style: normal;
      position: fixed;
      bottom: 32rpx;
      left: 50%;
      transform: translateX(-50%);
    }
  }
}
</style>
