<template>
  <div id="orderItem">
    <van-collapse v-model="activeNames">
      <van-collapse-item title="总览" name="1" class="pos-relative">
        <!-- <van-dropdown-menu>
          <van-dropdown-item v-model="value1" :options="option1" />
        </van-dropdown-menu> -->
        <van-row class="w100 font14 commonTotal">
          <van-col class="title" span="24">
            <span>订单信息统计</span>
          </van-col>
        </van-row>
        <van-row class="w100 font14 commonTotal">
          <van-col span="12">
            <div :style="{backgroundImage: 'url(' + greenPath + ')' }" class="client">
              <p class="p1">{{isJudgeNumber(itemInfo.CusNum)}} / {{isJudgeNumber(itemInfo.SalesQtySU)}}</p>
              <p class="p2">客户总数 / 交货数量</p>
            </div>
          </van-col>
          <van-col span="12">
            <div :style="{backgroundImage: 'url(' + bluePath + ')' }" class="client">
              <p class="p1">{{isJudgeNumber(itemInfo.SONum)}} / {{isJudgeNumber(itemInfo.LineNum)}}</p>
              <p class="p2">订单总数 / 行项目总数</p>
            </div>
          </van-col>
        </van-row>
        <van-row class="w100 font14 commonTotal">
          <van-col span="12">
            <div :style="{backgroundImage: 'url(' + redPath + ')' }" class="client">
              <p class="p1">{{isJudgeNumber(itemInfo.TotalValue)}}</p>
              <p class="p2">含税总金额(元)</p>
            </div>
          </van-col>
          <van-col span="12">
            <div :style="{backgroundImage: 'url(' + purplePath + ')' }" class="client">
              <p class="p1">{{isJudgeNumber(itemInfo.NetValue)}}</p>
              <p class="p2">无税总金额(元)</p>
            </div>
          </van-col>
        </van-row>
        <div class="my-swipe">
          <van-row class="w100 font14">
            <van-col class="title" span="24">
              <span>{{swipeTitle}}</span>
            </van-col>
          </van-row>
          <van-swipe @change="onChange" style="height: 240px;" indicator-color="#1989fa">
            <van-swipe-item class="w100">
              <echarts-view :clientInfo="clientInfo" :ordercount="ordercount" style=" height: 240px;" :key="count"/>
            </van-swipe-item>
            <van-swipe-item>
              <delivery-echarts-view :clientInfo="clientInfo" :ordercount="ordercount" style="height: 240px;" :key="counts"/>
            </van-swipe-item>
          </van-swipe>
        </div>
      </van-collapse-item>
    </van-collapse>
    <div class="list-amount">
        共<span class="red-tips">{{isJudgeNumber(itemInfo.CusNum)}}</span>条客户信息
    </div>
    <van-pull-refresh
      v-model="isRefreshing"
      @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad">
        <div v-for="(item, index) in datalists" :key="index" @click="itemClick(index)">
          <div class="content pos-relative" :class="{'active': (chooseIndex === index)}">
<!--            <van-row class="w100 font14 pos-relative" style="margin-bottom: 16px;">-->
<!--              <van-col span="9" style="font-weight: 600;">序号：{{index+1}}</van-col>-->
<!--              <van-col span="14" style="text-align: right;color:#1989fa;">-->
<!--                <span>查看客户订单</span>-->
<!--              </van-col>-->
<!--              <van-col span="1" style="text-align: right;color:#1989fa;">-->
<!--                <van-icon class="rightIcon" name="arrow" />-->
<!--              </van-col>-->
<!--            </van-row>-->
            <div class="w100 font16 " style="margin-bottom: 16px;display: flex;align-items: center;height: 22px">
              <div span="15" style="font-weight: bolder;flex: 1">客户：{{index+1}}</div>
              <span style="text-align: right;color:#1989fa;">查看客户订单</span>
              <van-icon size="20px" style="line-height: 22px;" color="#1989fa" name="arrow" />
            </div>
            <van-row class="w100 font14 margin-t8" style="height: 22px;line-height: 22px">
              <van-col span="9">客户信息:</van-col>
              <van-col span="15">
                <!-- 药厂码/（SAP码）名称 -->
                {{titleInitial(item)}}
              </van-col>
            </van-row>
            <van-row class="w100 font14 margin-t8" style="height: 30px;line-height: 30px">
              <van-col span="9">订单总数:</van-col>
              <van-col span="15">
                {{item.SONum}}
              </van-col>
            </van-row>
            <van-row class="w100 font14 margin-t8">
              <van-col span="9">含税金额:</van-col>
              <van-col span="15">
                {{item.TotalTax}} 元
              </van-col>
            </van-row>
            <van-row class="w100 font14 margin-t8">
              <van-col span="9">无税金额:</van-col>
              <van-col span="15">
                <!-- 价格处理 -->
                {{item.NetTax}} 元
              </van-col>
            </van-row>
            <!-- <van-icon class="rightIcon" name="arrow" /> -->
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import EchartsView from '@/components/EchartsView.vue'
import deliveryEchartsView from '@/components/deliveryEchartsView.vue'
import bluePath from '@/assets/img/1.jpg'
import redPath from '@/assets/img/2.jpg'
import greenPath from '@/assets/img/3.jpg'
import purplePath from '@/assets/img/4.png'
import { numFormat, AmountNumFormat } from '@/utils/common'
import { getWarehouseListHttp, getCustomerListHttp, getOrderInforHttpList, getOrderStatusHttp } from '@/api/overview'
export default {
  components: {
    EchartsView,
    deliveryEchartsView
  },
  name: 'CusItem',
  data() {
    return {
      count: 1,
      counts: 1,
      activeNames: ['1'],
      datalists: [],
      isRefreshing: false,
      loading: false,
      finished: false,
      greenPath: greenPath,
      bluePath: bluePath,
      redPath: redPath,
      purplePath: purplePath,
      chooseIndex: '',
      title: '',
      itemInfo: {
        CusNum: '', // 客户总数
        SONum: '', // 订单总数
        TotalValue: '', // 含税金额
        NetValue: '', // 无税金额
        LineNum: '', // 销售订单行项目个数
        SalesQtySU: '' // 交货数
      },
      value1: 0,
      option1: [],
      ordercount: Number,
      currentPage: 0,
      pageSize: 10,
      swipeTitle: '订单数纬度'
    }
  },
  props: {
    itemData: Object,
    activeTab: Number,
    clientInfo: {
      type: Object,
      default: () => {
        return {
          EDate: '',
          SDate: '',
          CustID: '',
          SODoc: '',
          PrnSo: ''
        }
      }
    }
  },
  watch: {
    activeTab(val) {
    },
    clientInfo: {
      handler (val) {
        // console.log(this.clientInfo)
        // console.log('-------')
        this.overviewSearchAction(this.clientInfo)
      },
      immediate: true,
      deep: true
    }
  },
  mounted () {
    // this.count ++
    // this.counts ++
    // this.getOrderInforHttpAction()
    // console.log('mounted')
    // this.getWarehouseListHttpAction()
    // this.getCustomerListHttpAction()
  },
  methods: {
    /// 标题拼接 <!-- 药厂码/（SAP码）名称 -->
    titleInitial(model) {
      let titleStr = ''
      if (this.isJudgeStrNull(model.PRNCustID)) {
        titleStr = model.PRNCustID + '/'
      }
      if (this.isJudgeStrNull(model.Customer)) {
        titleStr = titleStr + '(' + model.Customer.replace(/\b(0+)/gi,"") + ')'
      }
      if (this.isJudgeStrNull(model.CustomerName)) {
        titleStr = titleStr + ' ' + model.CustomerName
      }
      return titleStr
    },
    /// 数值加逗号
    // numFormat(num) {
    //   num = Number(num)
    //   var c = (num.toString().indexOf ('.') !== -1) ? num.toLocaleString() : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    //   return c
    // },
    //金额加逗号
    // AmountNumFormat(value) {
    //   if(!value) return '0.00'
    //   /*原来用的是Number(value).toFixed(0)，这样取整时有问题，例如0.51取整之后为1，感谢Nils指正*/
		// 	/*后来改成了 Number(value)|0,但是输入超过十一位就为负数了，具体见评论 */
    //   var intPart = Math.trunc(value);
		// 	var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); //将整数部分逢三一断
    //   var floatPart = ".00"; //预定义小数部分
		// 	var value2Array = value.toString().split(".");
		// 	//=2表示数据有小数位
		// 	if(value2Array.length == 2) {
		// 		floatPart = value2Array[1].toString(); //拿到小数部分

		// 		if(floatPart.length == 1) { //补0,实际上用不着
		// 			return intPartFormat + "." + floatPart + '0';
		// 		} else {
		// 			return intPartFormat + "." + floatPart;
		// 		}

		// 	} else {
		// 		return intPartFormat + floatPart;
		// 	}
    // },
    /// 高级搜索 调用接口
    overviewSearchAction(clientInfo) {
      this.activeNames = ['1']
      this.clientInfo = clientInfo
      // console.log(clientInfo)
      // console.log('overviewSearchAction')
      this.count ++
      this.counts ++
      // this.currentPage = 0
      this.onRefresh()
    },
    /// 获取总览订单数据
    getOrderInforHttpAction() {
      //EDate结束日期 SDate起始时间 CustID客户编号 SODoc订单编号 PrnSo药厂订单编号
      // console.log(this.clientInfo)
      let data = {
        param: `sdossParameters(UID='${this.$route.query.sysUserId}',PrnSo='${this.clientInfo.PrnSo}',SODoc='${this.clientInfo.SODoc}',EDate='${this.clientInfo.EDate}',SDate='${this.clientInfo.SDate}',CustID='${this.clientInfo.CustID}')/Results?$format=json`
      }
      getOrderInforHttpList(data).then((rt) => {
        // console.log(rt)
        if (rt.code === 200) {
          rt.data.results.forEach((res)=>{
            this.itemInfo = {
              SONum: numFormat(this.isJudgeNumber(res.SONum)),
              CusNum: numFormat(this.isJudgeNumber(res.CusNum)),
              LineNum: numFormat(this.isJudgeNumber(res.LineNum)),
              NetValue: AmountNumFormat(this.isJudgeNumber(res.NetValue)),
              TotalValue: AmountNumFormat(this.isJudgeNumber(res.TotalValue)),
              SalesQtySU: numFormat(this.isJudgeNumber(res.SalesQtySU))
            }
            // console.log(this.itemInfo)
          })
          this.ordercount = this.SONum
        } else {
          this.$toast(rt.msg)
          this.itemInfo = {
            CusNum: '', // 客户总数
            SONum: '', // 订单总数
            TotalValue: '', // 含税金额
            NetValue: '', // 无税金额
            LineNum: '' // 销售订单行项目个数
          }
        }
      }).catch((e) => {
        this.$toast('获取信息失败！')
      })
    },
    onChange(index) {
      if (index === 0) {
        this.swipeTitle = '订单数纬度'
      } else {
        this.swipeTitle = '交货数量纬度'
      }
    },
    itemClick(index) {
      this.chooseIndex = index
      // console.log(this.chooseIndex)
      this.$emit('itemClickCus', this.datalists[index])
    },
    onRefresh() {
      // 刷新接口
      this.datalists = []
      this.currentPage = 0
      this.isRefreshing = true
      // setTimeout(() => {
      //   this.isRefreshing = false;
      //   this.datalists = [1,2,3,4,5]
      //   this.finished = false;
      // }, 500)
      this.getCustomerListHttpAction()
    },
    onLoad() {
      // 加载更多接口
      this.loading = true
      this.getCustomerListHttpAction()
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.datalists.push(this.datalists.length + 1);
      //   }
      //   // 加载状态结束
      //   this.loading = false;

      //   // 数据全部加载完成
      //   if (this.datalists.length >= 20) {
      //     this.finished = true;
      //   }
      // }, 500)
    },
    // 获取客户信息列表
    getCustomerListHttpAction() {
      this.getOrderInforHttpAction()
      let data = {
        param: `sdoscParameters(UID='${this.$route.query.sysUserId}',PrnSo='${this.clientInfo.PrnSo}',SODoc='${this.clientInfo.SODoc}',EDate='${this.clientInfo.EDate}',SDate='${this.clientInfo.SDate}',CustID='${this.clientInfo.CustID}')/Results?$format=json&$top=${this.pageSize}&$skip=${this.currentPage}`
      }
      // let data = {
      //   param: `sdoscParameters(UID='${this.$route.query.sysUserId}',PrnSo='',SODoc='',EDate='${this.clientInfo.EDate}',SDate='${this.clientInfo.SDate}',CustID='')/Results?$format=json&$top=${this.pageSize}&$skip=${this.currentPage}`
      // }
      getCustomerListHttp(data).then((rt) => {
        // console.log(rt)
        if (rt.code === 200) {
          if (this.currentPage === 0) {
            this.datalists = []
          }
          rt.data.results.forEach((res)=>{
            res.NetTax = AmountNumFormat(res.NetValue)
            res.TotalTax = AmountNumFormat(res.TotalValue)
            res.LineNum = numFormat(res.LineNum)
            res.SONum = numFormat(res.SONum)
            this.datalists.push(res)
          })
          this.finished = false;
          this.isRefreshing = false;
          if (rt.data.results.length < 10) {
            this.finished = true;
          } else {
            this.currentPage = this.currentPage + this.pageSize
          }
        } else {
          this.$toast(rt.msg)
          this.isRefreshing = false
          this.error = true
          this.finished = true
        }
        // 加载状态结束
        this.loading = false;
      }).catch((e) => {
        // this.$toast('获取信息失败！')
        this.$toast('列表获取失败')
        this.isRefreshing = false
        this.loading = false
        this.error = true
        this.finished = true
      })
    },
    /// 判断数值是否为0
    isJudgeNumber(val) {
      if (val === null || val === undefined || val === '') {
        return 0.00
      }
      return val
    },
    /// 判断数值是否为空
    isJudgeStrNull(val) {
      if (val !== null && val !== undefined && val !== '') {
        return true
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
#orderItem{
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  /deep/ .van-collapse-item__content{
    padding: 10px;
  }
  /deep/ .van-swipe__indicator{
    background-color: #999999;
  }
  /deep/ .van-cell__right-icon{
    color: #1989fa;
  }
  .my-swipe{
    margin-top: 10px;
  }
  .title{
    width: 100%;
    text-align: left;
    font-size: 14px;
    font-weight: bolder;
    color: #333333;
    margin-bottom: 10px;
  }
  .list-amount {
    padding: 10px;
    height: 20px;
    line-height: 20px;
  }
  .red-tips {
    color: #fb1c1c;
    font-weight: bold;
    margin: 0 8px;
  }

  .commonTotal{
    background-color: #fff;
    // border-bottom: 1px solid #eeeeee;
    .client{
      height: 60px;
      margin: 5px;
      padding-top: 5px;
      .p1{
        color: #fff;
        text-align: center;
        margin: 0px 5px 0px 5px;
        line-height: 25px;
        display: flex;
        justify-content: left;
        height: 25px;
      }
      .p2{
        color: #fff;
        text-align: center;
        margin: 0px 5px 0px 5px;
        line-height: 25px;
        display: flex;
        justify-content: left;
        height: 25px;
        font-size: 13px;
      }
    }
  }
  .content {
    background: #FFFFFF;
    padding: 16px;
    border-bottom: #dedede 1px solid;
    &.active{
      background-color: #eaeaea;
      border-color: #eaeaea;
    }
    .rightIcon {
      font-size: 16px;
      height: 16px;
      width: 30px;
      text-align: center;
      line-height: 16px;
      display: inline-block;
      vertical-align: middle;
    }
  }
}
</style>
