/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.客户资料明细
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		于继渤		        2022-0-12	            1.00		   	    
 *******************************************************************************/
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const mixins = require('@/mixins/index.js')
const app = getApp()
const config = require('@/config/config.js');
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    // 路由
    activeNames_goods: [1],
    routeObjName: 'customer',
    imageUrl: config.image_url + '/static/img/',
    cusFollowService: app.globalData['cusFollowService'],
    orderService: app.globalData['orderService'],
    saleOutBoundService: app.globalData['saleOutBoundService'],
    cusReceiptPaymentService: app.globalData['cusReceiptPaymentService'],
    item: {},
    customerFollowList: [],
    paymentRecordsList: [],
    refundRecordsList: [],
    orderList: [],
    active: null,
    activeCard: null,
    // 主键Id
    primaryKey: 'cusId',
  },
  /**
   * @desc : 展开明细
   * @date : 2024/5/24 15:49
   * @author : 周兴
   */
  handleExpandItem(e){
    let type = e.currentTarget.dataset.type
    let index = e.currentTarget.dataset.index
    console.log('type',type);
    // 销售退货
    if(type == 'order-return'){
      let orderOutReturnList = this.data.orderOutReturnList;
      orderOutReturnList[index].showReturnDetailFlag = !orderOutReturnList[index].showReturnDetailFlag
      this.setData({
        orderOutReturnList:orderOutReturnList
      })
    } else if(type == 'order-out'){
      // 销售出库
      let orderOutList = this.data.orderOutList;
      orderOutList[index].showDetailFlag = !orderOutList[index].showDetailFlag
      this.setData({
        orderOutList:orderOutList
      })
    }
  },
    /**
    * @desc   : 打电话
    * @author : 周兴
    * @date   : 2024/2/19 11:46
    */
   openTelPhone(e) { 
    let item = e.currentTarget.dataset.item; 
    wx.makePhoneCall({
      phoneNumber: item.cusPhone,
    })
  },
  /**
   * @desc : 收款单保存后重新刷新数据
   * @date : 2024/5/24 15:49
   * @author : 周兴
   */
  getData() {
    this._detail(this.data.item.cusId);
  },
  /**
   * @desc : 查询客户跟进
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getCusFollowList(cusId) {
    this.setData({
      loading: true
    })
    return this.excute(this.data.cusFollowService, this.data.cusFollowService.selectByList, { cusId: cusId }).then(res => {
      if (res.data.code == 200) {
        this.setData({
          loading: false
        })
        console.log('getCusFollowList', res.data.data)
        let list = res.data.data
        let followList = []
        for (let i = 0; i < list.length; i++) {
          if (list[i].followId) {
            followList.push(list[i])
          }
        }
        this.setData({
          customerFollowList: followList.length > 0 ? this.classify(followList) : []
        })
        if (followList.length > 0) {
          let that = this
          setTimeout(() => {
            wx.createSelectorQuery().select('#time0').boundingClientRect(function (rect) {
              that.setData({
                timeWidth: rect.width
              })
            }).exec()
            wx.createSelectorQuery().select('#xian0').boundingClientRect(function (rect) {
              that.setData({
                xianWidth: rect.width
              })
            }).exec()
            wx.createSelectorQuery().select('#kuang0').boundingClientRect(function (rect) {
              that.setData({
                kuangHeight: rect.height
              })
            }).exec()
          }, 200)
        }
      }
    });
  },

  /**
  * 把创建时间相同的跟进记录放入到一个item 然后扔到list
  * @param {*} arr 
  */
  classify(arr) {
    let map = {};
    let myArr = [];
    for (let i = 0; i < arr.length; i++) {
      if (!map[arr[i].createTime]) {
        myArr.push({
          createTime: arr[i].createTime,
          weekTime: arr[i].weekTime,
          data: [arr[i]]
        });
        map[arr[i].createTime] = arr[i]
      } else {
        for (let j = 0; j < myArr.length; j++) {
          if (arr[i].createTime === myArr[j].createTime) {
            myArr[j].data.push(arr[i]);
            break
          }
        }
      }
    }
    return myArr
  },
  /**
   * @desc : 给表单赋值
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setValuesByEdit(data) {
    data.name = 'edit'
    this.setData({
      item: data,
    })
    // 查询客户跟进
    if(this.data.gradeCode == Constants.gradeCode.PRO){
      this.getCusFollowList(this.data.id)
    }
  },
  /**
  * @desc : 切换tab
  * @date : 2024/5/24 15:49
  * @author : 周兴
  */
  onChange(e) {
    let name = e.detail.name
    let cusId = this.data.id
    if (name == 'follow') {
      this.getCusFollowList(cusId)
    }
    else if (name == 'deal') {
      // // 标准版查销售出库
      // if (this.data.gradeCode == Constants.gradeCode.STD) {
      //   this.getOrderOut(cusId, Constants.outType.sale)
      // } else {
      //   this.getOrderList(cusId)
      // }
      this.getOrderList(cusId)
    }
    // 收款
    else if (name == 'receipt') {
      this.getPayRecords(cusId, '收付款类型-收款')
    }
    // 退款
    else if (name == 'payment') {
      this.getPayRecords(cusId, '收付款类型-退收款')
    }
  },
  /**
  * @desc : 交易记录切换
  * @date : 2024/2/1 15:49
  * @author : 于继渤
  */
  changeTag(e) {
    let data = this.data.item
    let name = e.detail.name
    this.setData({
      activeCard: e.detail.name
    })
    if (name == 'order') {
      this.getOrderList(data.cusId)
    }
    else if (name == 'order-out') {
      this.getOrderOut(data.cusId, Constants.outType.sale)
    }
    else if (name == 'order-return') {
      this.getOrderOut(data.cusId, Constants.outType.intoReturn)
    }
  },
  /**
   * @desc : 查询订单
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getOrderList(cusId) {
    let params = {}
    params.cusId = cusId
    this.setData({
      loading: true
    })
    this.excute(this.data.orderService, this.data.orderService.selectTotalSingleTapeDetailPage, params).then(res => {
      if (res.data.code == 200) {
        this.setData({
          loading: false
        })
        res.data.data.list.forEach(item => {
          if (item.orderItemResponseList && item.orderItemResponseList.length > 0) {
            item.orderItemResponseList.forEach(it => {
              it.packageDetailsFlag = true
              if (it.skuImages && it.skuImages.value) {
                it.skuImages.value = JSON.parse(it.skuImages.value)

                it['imagesUrl'] = it.skuImages.value.length > 0 ? it.skuImages.value[0].url : null
              }
            })
          }
        })
        let list = res.data.data.list
        this.setData({
          orderList: list
        })
      }
    })
  },

  /**
   * @desc : 查询订单出库
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getOrderOut(cusId, orderType) {
    let params = {}
    params.cusId = cusId
    params.outType = orderType
    params.flgValid = true
    this.setData({
      loading: true
    })
    this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.selectByCondDetail, params).then(res => {
      if (res.data.code == 200) {
        this.setData({
          loading: false
        })
        res.data.data.list.forEach(item => {
          if (item.goodsList && item.goodsList.length > 0) {
            item.goodsList.forEach(it => {
              it.packageDetailsFlag = true
              if (it.skuImages && it.skuImages.value) {
                it.skuImages.value = JSON.parse(it.skuImages.value)

                it['imagesUrl'] = it.skuImages.value.length > 0 ? it.skuImages.value[0].url : null
              }
              // 根据状态显示不同的字段
              if (it.outStatus == Constants.outStatus.outBounding) {
                it.outAmt = it.outingAmt
                it.outQty = it.outingQty
              }
            })
          }
          // 根据状态显示不同的字段
          if (item.outStatus == Constants.outStatus.outBounding) {
            item.outAmt = item.outingAmt
            item.outQty = item.outingQty
          }
        })
        let list = res.data.data.list
        if (orderType == Constants.outType.sale) {
          this.setData({
            orderOutList: list
          })
        } else {
          this.setData({
            orderOutReturnList: list
          })
        }
      }
    })
  },
  /**
* @desc : 查询订单退货
* @date : 2024/2/1 15:49
* @author : 于继渤
*/
  getOrderOutReturn(cusId) {

  },

  /**
   * @desc : 跳转
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  toJump(e) {
    let key = e.currentTarget.dataset.key
    let url = null
    let gradeCode = this.data.gradeCode

    if (key == 'sale') {
      // if (gradeCode == Constants.gradeCode.STD) { //标准
      //   url = this.data.route.toSaleOutOrder.url
      // } else if (gradeCode == Constants.gradeCode.PRO) {
      //   url = this.data.route.toSaleOrder.url
      // }
      url = this.data.route.toSaleOrder.url
    }
    else if (key == 'receipt') {
      if (gradeCode == Constants.gradeCode.STD) { //标准
        url = this.data.route.collection.url
      } else if (gradeCode == Constants.gradeCode.PRO) {
        url = this.data.route.toReceipt.url
      }
    }
    else if (key == 'saleReturn') {
      url = this.data.route.toSaleOrderReturn.url
    }
    let that = this
    wx.navigateTo({
      url: url,
      events: {
        // 保存成功后刷新页面
        refresh: function (data) {
        }
      },
      success: function (res) {
        res.eventChannel.emit('params', { id: that.data.item.cusId, item: that.data.item, formType: Constants.formMode.add, formMode: Constants.formMode.add });
      }
    })
  },

  /**
   * @desc : 收款记录
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getPayRecords(cusId, type) {
    let params = {}
    params.objectId = cusId
    params.rpTypeList = [type]
    this.setData({
      loading: true
    })
    this.excute(this.data.cusReceiptPaymentService, this.data.cusReceiptPaymentService.selectByCond, params).then(res => {
      if (res.data.code == 200) {
        this.setData({
          loading: false
        })
        let list = res.data.data.list
        // if (list && list.length > 0) {
        //   list = list.filter(res => {
        //     return res.receiptResidue > 0
        //   })

        // }
        if (type == '收付款类型-收款') {
          this.setData({
            paymentRecordsList: list
          })
        } else {
          this.setData({
            refundRecordsList: list
          })
        }

      }
    })
  },
  /**
   * @desc : 跳转查看收款源单
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  toOriginalCollection(e) {
    let item = e.currentTarget.dataset.item
    this.setData({
      selectflag: true
    })
    let method = null;
    let route = this.data.route
    // 标准版跳转客户收款
    if (this.data.gradeCode == Constants.gradeCode.STD) {
      method = 'collectionDetail'
    } else {
      method = 'toReceiptDetail'
    }
    let url = route[method].url
    if (!url) return;
    wx.navigateTo({
      url: url,
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', { id: item.rpId, formMode: Constants.formMode.other })
      }
    })
  },
  /**
   * @desc : 初始加载
   * @date : 2024/5/24 15:49
   * @author : 周兴
   */
  loadInit() {
    let gradeCode = this.data.gradeCode
    let name = null
    if (gradeCode == Constants.gradeCode.STD) {
      name = 'deal'
      this.setData({
        active: name,
        activeCard: 'order'
      })
    } else {
      name = 'follow'
      this.setData({
        active: name,
        activeCard: 'order'
      })
    }
    let e = {
      detail: {
        name: name
      }
    }
    this.onChange(e);
  }

})