
var app = getApp()
var that;
var socket = null;
var setTime;
Page({
  data: {
    date: app.globalData.month,
    httpType: 'waiting',
    keyword: '',
    page: 1,
    isBh: false,//是否显示驳回弹窗
    textArea: "",

    showStaff: false,//显示员工选择
    staffVal: '奖扣对象',
    target_id: '',

    selectIds: [],//选择的人员
    dataList: [],
    isAll: true,

    // 长连接结果
    results: [], //提交的返回结果集合
    isResult: false,
    percentage: 0,
    resultList: [],//要发送数据的集合
    resultIndex: 0,
    isShowError: false,
  },
  onLoad() {
    that = this;
    dd.setNavigationBar({ title: "批量审批" });
  },
  // 页面被关闭
  onUnload() {

  },
  onShow() {
    if (app.globalData.userData) {
      that.refreshData();
    } else {
      app.login(app.globalData.corpId, function (is) {
        if (is) {
          that.refreshData();
        } else {
          dd.reLaunch({
            url: '../../noJurisdiction/noJurisdiction'
          })
        }
      }, function () { })
    }
  },
  closeTc() {
    this.setData({
      results: [], //提交的返回结果集合
      isResult: false,
      percentage: 0,
      resultList: [],//要发送数据的集合
      resultIndex: 0,
      selectIds: [],
      isBh: false,//是否显示驳回弹窗
      isShowError: false,
      textArea: '',
      page: 1,
    })
    app.globalData.socketApi.closewebsocket();
    this.getData();
  },
  // 驳回
  openBh() {
    if (this.data.selectIds.length == 0) {
      app.globalData.showToast("请先选择审批单");
      return false
    }
    this.setData({
      isBh: true,
    })
  },
  // 通过
  openTg() {
    let that = this;
    if (this.data.selectIds.length == 0) {
      app.globalData.showToast("请先选择审批单");
      return false
    }
    dd.confirm({
      title: '批量通过',
      content: `已选中${this.data.selectIds.length}条审批单，确认全部通过？`,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          that.webSocket(true);
        }
      },
    });
  },
  webSocket(is) {
    let arr = [];
    let wsData;
    this.data.selectIds.forEach(item => {
      if (is) {
        wsData = {
          type: 'review',
          action: 'complete',
          review_id: item,
        };
      } else {
        wsData = {
          type: 'review',
          action: 'refuse',
          review_id: item,
          remark: this.data.textArea,
        };
      }
      arr.push(wsData);
    });
    this.setData({
      resultList: arr,
      resultIndex: 0,
      percentage: 0,
      results: [],
      isResult: true,
    })
    this.opneWebSocket()
  },
  opneWebSocket() {
    let wsData = this.data.resultList;
    if (wsData[this.data.resultIndex]) {
      setTime = setTimeout(() => {
        dd.alert({
            title: '温馨提示',
            content: '网络异常,请检查网络',
            buttonText: '我知道了',
            success: (result) => {
                clearTimeout(setTime);
                app.globalData.socketApi.closewebsocket();
                that.closeTc();
             },
        });
      }, 15000)
      app.globalData.socketApi.sendData(wsData[this.data.resultIndex], this.onmessageWS);
    } else {
      // console.log(this.data.results)
    }
  },
  onmessageWS(e) {
    // 因为作用域问题，这个函数不能使用this
    if (e.type == 'review') {
       clearTimeout(setTime);
      let data = e.result;
      let employee = that.returnResult(e.result.task.msg.review_id)[0]
      data.target = employee.employee_name;
      data.remark = employee.remark;
      data.point = employee.point;
      data.pt_name = employee.pt_name;
      // console.log(employee)
      // data.msg=e.msg
      let results = that.data.results;//结果集
      results.unshift(e.result);
      let lng = that.data.resultList.length;// 进度条
      that.setData({
        percentage: Math.floor(that.data.percentage += (100 / lng)),
        results: results,
        resultIndex: that.data.resultIndex + 1
      })
      that.opneWebSocket();
      if (lng == that.data.results.length) {
        that.setData({
          percentage: 100,
        })
      }
    }
    if (e.type == 'error') {
       clearTimeout(setTime);
      that.setData({
        isShowError: true,
      })
    }
  },
  returnResult(id) {
    return this.data.dataList.filter(item => {
      return item.id == id;
    })
  },
  confirmBh() {
    if (that.data.textArea == '') {
      app.globalData.showToast("请输入审批意见");
      return;
    }
    this.setData({ isBh: false })
    that.webSocket(false);
  },

  onChange(e) {
    if (e) {
      this.setData({
        selectIds: e.detail.value
      })
    }
  },
  selectAll() {
    let selectIds = [];
    let dataList = this.data.dataList.map(item => {
      item.checked = this.data.isAll;
      selectIds.push(item.id);
      return item;
    })
    this.setData({
      dataList: dataList,
      selectIds: this.data.isAll ? selectIds : [],
      isAll: !this.data.isAll,
    })
  },
  bindKeyInput(e) {
    this.setData({
      page: 1,
      isVal: e.detail.value ? true : false,
      keyword: e.detail.value ? e.detail.value : '',
    })
    this.getData();
  },
  //关闭弹窗
  onClose() {
    this.setData({
      showStaff: false,
    })
  },
  //选择员工
  onConfirmStaff(data) {
    if (!data) {
      this.setData({ staffVal: '奖扣对象', target_id: '', page: 1 })
      this.getData();
      return false;
    }
    if (data.length > 0) {
      this.setData({ staffVal: data[0].name, target_id: data[0].id, page: 1 })
    } else {
      this.setData({ staffVal: '奖扣对象', target_id: '', page: 1 })
    }
    this.getData();
  },
  //显示选择员工
  selectStaff() {
    this.setData({
      showStaff: true
    })
  },
  openDetail(e) {
    var id = e.target.dataset.item.id;
    dd.navigateTo({
      url: '../approveDetail/approveDetail?id=' + id
    })
  },
  showText() {
    dd.alert({
      title: '温馨提示',
      content: '批量审批仅支持快速处理任务审批和已指定规则的积分审批，其余情况的审批单请到【待我审批】处理，权限分不足时，请进入【审批详情】→【通过】→【递交审批】给上级',
      buttonText: '我知道了',
      success: (result) => { },
    });
  },
  //当在详情返回时刷新列表，但你请求接口
  refreshData(id) {
    if (this.data.page == 1) {
      dd.hideLoading();
      that.getData();
    } else {
      if (id) {//当page不为一并下一页返回上一页不执行onshow()
        var arr = this.data.dataList;
        arr.forEach((element, index) => {
          if (element.id == id) {
            arr.splice(index, 1);
          }
        });
        this.setData({
          dataList: arr
        })
      }
    }
  },
  bindTextAreaBlur(e) {
    this.setData({
      textArea: e.detail.value
    });
  },
  closeBh() {
    this.setData({ isBh: false, textArea: '' })
  },
  onReset() {
    this.setData({
      keyword: '',
      isVal: false,
      page: 1,
    })
    this.getData();
  },
  getData(type) {
    let data = {
      source_type: '0',
      batch: 1,
      type: 'waiting',
      page: that.data.page,
      pt_id: 0,
      page_size: 20,
      keyword: that.data.keyword
    }
    if (that.data.target_id) {
      data.target_id = that.data.target_id;
    }
    app.$get("api/integral/review/list", data).then((res) => {
      var list = res.data.data.list || [];
      list.forEach(element => {
        if (element.pt_id) {
          element.pt_name = app.getTypesItem(element.pt_id).name
        }
      });
      if (that.data.page == 1) {
        this.setData({
          dataList: []
        })
      }
      var data = list;
      var dataList = that.data.dataList || [];
      if (type == '2') {
        if (data.length < 20) {
          this.setData({
            dataList: dataList.concat(data),
            isData: true
          })
        } else {
          this.setData({
            dataList: dataList.concat(data),
          })
        }
      } else {
        this.setData({ dataList: data, isData: false })
      }
    })
  },
  //上啦加载
  onScrollToLower() {
    if (!that.data.isData) {
      this.setData({ page: ++that.data.page })
      this.getData("2");
    }
  },
});
