var app = getApp()
var that;
var animation;
Page({
  data: {
    members: '',//用户id
    userName: '',//用户名称
    items: [{//录入选项列表
      checked: true,//判断是否开启指定规则
      rule_id: '',//积分分类id
      item_id: '',//积分细则id 不选可以为0
      remark: '',//备注
      event_time: app.globalData.day,//事件时间
      reviewer_id: '',//审核人ID
      revieweName: '',//审批人姓名（非传）
      files: '',//附件数组列表
    }],
    animationInfo: '',
    isShowType: true,//是显示选择规则还是显示选择分类
    activeIndex: '',
    isArr: ['奖', '扣'],
    reviewerObj:[],
    disabled:false,
  },
  onLoad() {
    that = this;
    dd.setNavigationBar({ title: "申请积分" });
    this.setData({
        items: [{//录入选项列表
        checked: true,//判断是否开启指定规则
        rule_id: '',//积分分类id
        item_id: '',//积分细则id 不选可以为0
        remark: '',//备注
        event_time: app.globalData.day,//事件时间
        reviewer_id: app.globalData.userData.employee_detail.superior_list[0].id,//审核人ID
        revieweName: app.globalData.userData.employee_detail.superior_list[0].name,//审批人姓名（非传）
        files: '',//附件数组列表
      }],
    })
  },
  onShow() {
    animation = dd.createAnimation({
      duration: 200,
      timeFunction: "linear",
    });
  },
  //关闭规则
  onClose() {
    animation.translateY(750).step();
    that.setData({
      animationInfo: animation.export()
    });
    that.setData({
      isShowType:''
    });
  },
  //选择规则
  openSelect(e) {
    if(e.target.dataset.item){
       that.setData({ reviewerObj: [e.target.dataset.item] });
    }
    that.setData({ activeIndex: '' });
    that.setData({
      isShowType: e.target.dataset.num,
      activeIndex: e.target.dataset.index,
    });
    animation.translateY(0).step();
    that.setData({
      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) {
        var key = 'intesys/' + 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;
      }
      obj.employee_id = app.globalData.userData.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.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(() => {
            this.setData({disabled:false});
            dd.navigateBack({
              delta: 1
            })
          }, 1000);
        }
      }).catch(err=>{
        this.setData({disabled:false});
      })
    }
  },
  //删除一条
  deleteArr(e) {
    var index = e.target.dataset.index;
    var list = that.data.items;
    app.globalData.arrRemoveObj(list, list[index]);
    that.setData({
      items: list
    })
    console.log(that.data.items);
  },
  //选择人
   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 arr = {//录入选项列表
      checked: true,//判断是否开启指定规则
      rule_id: '',//积分分类id
      item_id: '',//积分细则id 不选可以为0
      remark: '',//备注
      event_time: app.globalData.day,//事件时间
      reviewer_id: app.globalData.userData.employee_detail.superior_list[0].id,//审核人ID
      revieweName: app.globalData.userData.employee_detail.superior_list[0].name,//审批人姓名（非传）
      files: '',//附件数组列表
    };
    var list = that.data.items
    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,
    })
  },
});
