var app = getApp()
var that;
var animation;
Page({
  data: {
    members: '',//用户id
    userName: '',//用户名称
    items: [{//录入选项列表
      employee_id: '',
      employeeName: '',
      checked: true,//判断是否开启指定规则
      rule_id: '',//积分分类id
      item_id: '',//积分细则id 不选可以为0
      remark: '',//备注
      event_time: app.globalData.day,//事件时间
      reviewer_id: '',//审核人ID
      revieweName: '',//审批人姓名（非传）
      files: '',//附件数组列表
    }],
    animationInfo: '',
    isShowType: '0',//是显示选择规则还是显示选择分类
    activeIndex: '',
    isArr: ['奖', '扣'],
    reviewerObj: [],//选中的审批人
    employeeObj: [],//选中的录入对象
    disabled: false,
    superior_list: [],//录入人的上级
    getReviewerObj: {},//默认当前的缓存对象
    defaultRuleId: '',
    qrcodeId: '',//扫码进入
    popupCx: '',
    boxTop:0,
  },
  onLoad(e) {
    that = this;
    dd.setNavigationBar({ title: "申请积分" });
    if (e.id) {
      this.setData({ //获取扫码进入参数 
        qrcodeId: e.id
      })
    } else {
      this.getReviewerObj(app.globalData.userData.id, function (res) {
        that.setData({
          getReviewerObj: res,
          items: [{//录入选项列表
            checked: true,//判断是否开启指定规则
            employee_id: app.globalData.isCreator ? '' : app.globalData.userData.id,
            employeeName: app.globalData.isCreator ? '' : app.globalData.userData.name,
            rule_id: '',//积分分类id
            item_id: '',//积分细则id 不选可以为0
            remark: '',//备注
            event_time: app.globalData.day,//事件时间
            reviewer_id: res.id,
            revieweName: res.name,
            files: '',//附件数组列表
          }],
        })
      })
    }
  },
  onPageScroll(e){
      if(e.scrollTop!=0){
        this.setData({
          boxTop:e.scrollTop
        })
      }
  },
  //获取缓存的审批人
  getReviewerObj(id, fuc) {
    dd.getStorage({
      key: String(id),
      success: function (res) {
        if (res.data) {
          fuc(res.data);
        } else {
          fuc({});
        }
      }
    });
  },
  onShow() {
    dd.hideLoading();
    animation = dd.createAnimation({
      duration: 200,
      timeFunction: "linear",
    });
    if (app.globalData.userData) {
     that.showQrcode();
    } else {
      app.login(app.globalData.corpId, function (is) {
        if (is) {
         that.showQrcode();
        } else {
          dd.reLaunch({
            url: '../noJurisdiction/noJurisdiction'
          })
        }
      },function(){})
    }
  },
  //显示二维码规则ID内容
  showQrcode() {
    if (this.data.qrcodeId) {
      if (app.globalData.isCreator) {
        app.globalData.showToast("您当前身份为创始人,不需要申请记分功能");
        setTimeout(() => {
          dd.switchTab({
            url: '../index/index'
          })
          this.setData({ disabled: false });
        }, 1000);
        return;
      }
      app.$get("api/integral/rule/items/info", { item_id: this.data.qrcodeId }).then((res) => {
        var item = res.data.data || {}
        item.pt_Obj = app.getTypesItem(item.pt_id);
        var selectRule = `items[0].selectRule`
        var remark = `items[0].remark`
        var employee_id = `items[0].employee_id`
        var employeeName = `items[0].employeeName`
        that.setData({
          [employee_id]:app.globalData.userData.id,
          [employeeName]: app.globalData.userData.name,
          [selectRule]: item,
          [remark]: item.remark,
        })
      });
    }
  },
  //显示图片
  showImg(e) {
    var index = e.target.dataset.index;
    var item = e.target.dataset.item
    dd.previewImage({
      current: index,
      urls: item
    });
  },
  //关闭规则
  onClose() {
    animation.translateY(1200).step();
    that.setData({
      animationInfo: animation.export(),
      isShowType: '',
      popupCx: ''
    });
    setTimeout(()=>{
      dd.pageScrollTo({
        scrollTop: that.data.boxTop
      })
    },100)
  },
  showToast(text) {
    app.globalData.showToast(text);
  },
  //选择
  openSelect(e) {
    var index = e.target.dataset.index;
    var item = e.target.dataset.item;
    var num = e.target.dataset.num;
    that.setData({ activeIndex: '', isShowType: '0' });
    if (num == 2) {
      if (!item.employee_id) {
        this.showToast('请先选择录入对象')
        return;
      }
      // 获取录入对象的上级
      this.getEmployeeList([item.employee_id], function (res) {//获取共同上级
        var reviewer_id = `items[${index}].reviewer_id`
        var revieweName = `items[${index}].revieweName`
        let is = false;//是否还在
        res.forEach(items => {
          if (items.id == item.id) {//判断缓存起来的审批人是否还在审批人列表中
            is = true;
          }
        })
        if (is) {
          that.setData({
            superior_list: res,
            isShowType: num,
            activeIndex: index,
            reviewerObj: [item]
          })
        } else {
          that.setData({
            superior_list: res,
            isShowType: num,
            activeIndex: index,
            reviewerObj: [],
            [reviewer_id]: '',
            [revieweName]: ''
          })
        }
        animation.translateY(0).step();
        that.setData({
          popupCx: 'container__mask',
          animationInfo: animation.export()
        });
      });
    } else {
      if (e.target.dataset.ruleId) {
        that.setData({ defaultRuleId: e.target.dataset.ruleId });
      }
      animation.translateY(0).step();
      that.setData({
        employeeObj: num == 3 ? [e.target.dataset.item] : [],
        isShowType: num,
        activeIndex: index,
        popupCx: 'container__mask',
        animationInfo: animation.export()
      });
    }
  },
  //删除图片
  deteleImg(e) {
    var { itemIndx, index } = e.target.dataset;
    var files = that.data.items[itemIndx].files;//获取itemS集合中对应的files
    var files_box = `items[${itemIndx}].files`;//
    app.globalData.arrRemoveObj(files, files[index]);
    that.setData({
      [files_box]: files
    });
  },
  //图片选择
  openImg(e) {
    var index = e.target.dataset.index;
    var files = that.data.items[index].files;
    if (files.length >= 3) {
      app.globalData.showToast("最多能选择三张");
      return false;
    }
    dd.chooseImage({
      count: 1,
      success: (res) => {
        that.postImg(res, index);
      },
    });
  },
  postImg(data, index) {
    var files_box = `items[${index}].files`;
    var files = that.data.items[index].files;
    dd.httpRequest({
      url: app.globalData.imgHttpUrl,
      method: 'POST',
      data: {
        md5: that.random_string(32),
        'name': app.globalData.day
      },
      success: function (res) {
        if (app.globalData.userData.site_id) {
          var key = 'intesys/dd/' + app.globalData.userData.site_id + "/" + app.globalData.day + '/' + that.random_string(32) + '.png';
        } else {
          var key = 'intesys/dd/' + app.globalData.day + '/' + that.random_string(32) + '.png';
        }
        var obj = res.data.data;
        dd.uploadFile({
          url: app.globalData.ALIOSS_URL,
          fileType: 'image',
          fileName: 'file',
          filePath: data.filePaths[0],
          formData: {
            key: key,
            policy: obj.policy,
            OSSAccessKeyId: obj.accessid,
            success_action_status: 200,
            signature: obj.signature
          },
          success: (res) => {
            if (res.statusCode == 200) {
              if (files.length > 0) {
                files.push('http://cdn.intesys.g107.com/' + key)
              } else {
                files = ['http://cdn.intesys.g107.com/' + key];
              }
              that.setData({
                [files_box]: files
              });
              app.globalData.showToast("已上传");
            }
          },
        });

      },
      fail: function (res) {
        app.globalData.showToast("上传失败");
      }

    })
  },
  random_string(len) {
    len = len || 32
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    var maxPos = chars.length
    var pwd = ''
    for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
  },
  //备注输入
  bindTextAreaBlur: function (e) {
    var index = e.target.dataset.index;
    var remark = `items[${index}].remark`
    this.setData({
      [remark]: e.detail.value,
    });
  },

  formSubmit() {
    var items = this.data.items;
    var arr = [];
    var isTg = true;
    for (var i = 0; i < items.length; i++) {
      var obj = {};
      var item = items[i];
      if (!item.remark) {
        app.globalData.showToast(`第${i + 1}项申请内容不能为空`);
        isTg = false;
        break;
      }
      if (!item.reviewer_id) {
        app.globalData.showToast(`第${i + 1}项申请审批人不能为空`);
        isTg = false;
        break;
      }
      obj.employee_id = item.employee_id;
      if (item.checked) {
        obj.rule_id = item.selectRule ? item.selectRule.rule_id : 0;
        obj.item_id = item.selectRule ? item.selectRule.id : 0;
      } else {
        obj.rule_id = 0;
        obj.item_id = 0;
      }
      if (item.checked) {
        if (!obj.rule_id) {
          app.globalData.showToast(`第${i + 1}项必须选择规则`);
          isTg = false;
          break;
        }
      }
      obj.remark = item.remark;
      obj.event_time = item.event_time;
      obj.reviewer_id = item.reviewer_id;
      obj.revieweName = item.revieweName;
      obj.files = item.files;
      arr.push(obj);
    }
    if (isTg) {
      var data = {
        items: JSON.stringify(arr)
      }
      this.setData({ disabled: true });
      app.$post("api/integral/review/apply", data).then((res) => {
        var is = true;
        res.data.data.list.forEach(item => {
          if (item.status == 0) {
            is = false;
            this.setData({ disabled: false });
            app.globalData.showToast(item.msg);
          }
        });
        if (is) {
          app.globalData.showToast('申请成功');
          setTimeout(() => {
            if (this.data.qrcodeId) {
              dd.switchTab({
                url: '../index/index'
              })
            } else {
              dd.navigateBack({
                delta: 1
              })
            }
            this.setData({ disabled: false });
          }, 1000);
        }
      }).catch(err => {
        this.setData({ disabled: false });
      }).finally(() => {
        if (arr.length > 0) {
          arr.forEach(item => {
            dd.setStorage({
              key: String(item.employee_id),
              data: { id: item.reviewer_id, name: item.revieweName },
            });
          })
        }
      })
    }
  },
  //删除一条
  deleteArr(e) {
    var index = e.target.dataset.index;
    var list = that.data.items;
    app.globalData.arrRemoveObj(list, list[index]);
    that.setData({
      items: list
    })
  },
  //选择录入对象
  onSelectUserEmployee(item) {
    var elm = item.length > 0 ? item[0] : { id: '', name: '' };
    var index = this.data.activeIndex;
    var employee_id = `items[${index}].employee_id`
    var employeeName = `items[${index}].employeeName`
    var reviewer_id = `items[${index}].reviewer_id`
    var revieweName = `items[${index}].revieweName`
    that.setData({
      [employee_id]: elm.id,
      [employeeName]: elm.name,
    });
    dd.getStorage({
      key: String(elm.id),
      success: function (res) {
        if (res.data) {
          that.setData({
            [reviewer_id]: res.data.id,
            [revieweName]: res.data.name
          });
        } else {
          that.setData({
            [reviewer_id]: '',
            [revieweName]: ''
          });
        }
      }
    });
  },
  //获取人员（上级人员）
  getEmployeeList(userIdArr, callBack) {
    app.$get("api/employee/superior", { employee_id: userIdArr, filter_applyor: 1 }).then((res) => {
      callBack(res.data.data.list || [])
    })
  },
  //选择审批人
  onSelectUser(item) {
    var elm = item.length > 0 ? item[0] : { id: '', name: '' };
    var index = this.data.activeIndex;
    var reviewer_id = `items[${index}].reviewer_id`
    var revieweName = `items[${index}].revieweName`
    that.setData({
      [reviewer_id]: elm.id,
      [revieweName]: elm.name,
    });
  },
  //添加一条
  addArr() {
    var list = that.data.items
    if(list.length>=10){
      this.showToast('一次只能添加10条申请')
      return;
    }
    var arr = {//录入选项列表
      employee_id: app.globalData.isCreator ? '' : app.globalData.userData.id,
      employeeName: app.globalData.isCreator ? '' : app.globalData.userData.name,
      checked: true,//判断是否开启指定规则
      rule_id: '',//积分分类id
      item_id: '',//积分细则id 不选可以为0
      remark: '',//备注
      event_time: app.globalData.day,//事件时间
      reviewer_id: this.data.getReviewerObj.id,
      revieweName: this.data.getReviewerObj.name,
      files: '',//附件数组列表
    };
    list.push(arr);
    that.setData({
      items: list
    })
  },
  switchChange(e) {
    var index = e.target.dataset.index;
    var item = `items[${index}].checked`
    that.setData({
      [item]: e.detail.value
    })
  },
  //选择时间
  openDate(e) {
    var index = e.target.dataset.index;
    var item = `items[${index}].event_time`
    dd.datePicker({
      format: 'yyyy-MM-dd',
      currentDate: app.globalData.day,
      success: (res) => {
        that.setData({
          [item]: res.date
        })
      },
    });
  },
  //选择规则
  onSelectItem(item) {
    var index = this.data.activeIndex;
    var selectRule = `items[${index}].selectRule`
    var remark = `items[${index}].remark`
    that.setData({
      [selectRule]: item,
      [remark]: item.remark,
    })
  },
});
