var app = getApp()
var that;
var animation;
Page({
  data: {
    users: [],
    items: [],
    animationInfo: '',
    isShowType: '',//是显示选择规则还是显示选择分类
    activeIndex: '',
    isArr: ['奖', '扣'],
    reviewerObj:[],//默认的审批人
     disabled:false,
  },
  onLoad() {
    that = this;
    dd.setNavigationBar({ title: "奖扣A分" });
    this.setData({
      items: [{//录入选项列表
              checked: true,//判断是否开启指定规则
              rule_id: '',//积分分类id
              rule_id2: '',
              rule_name: '',//积分分类名称

              item_id: 0,//积分细则id 不选可以为0

              point: '',//录入积分可为正负值，不能为0(细则)
              point2: '',//录入积分可为正负值，不能为0（分类）

              remark: '',//备注
              event_time: app.globalData.day,//事件时间
              pt_id: '',//积分种类id
              reviewer_id: '',//审核人ID
              revieweName: '',//审批人姓名（非传）
              files: '',//附件数组列表
              isArrindex: true,//奖扣索引（默认奖）(细则)
              isArrindex2: true,//奖扣索引（默认奖）（分类）
              selectRule: '',//选择的规则
            }],
    })
  },
  onShow() {
    animation = dd.createAnimation({
      duration: 200,
      timeFunction: "linear",
    });
  },
  //选择奖还是扣(细则)
  bindPickerChange(e) {
    var index = e.target.dataset.index;
    var isArrindex = `items[${index}].isArrindex`;
    var isTrue = that.data.items[index].isArrindex
    this.setData({
      [isArrindex]: !isTrue,
    });
  },
  //选择奖还是扣（分类）
  bindPickerChange2(e) {
    var index = e.target.dataset.index;
    var isArrindex2 = `items[${index}].isArrindex2`;
    var isTrue = that.data.items[index].isArrindex2
    this.setData({
      [isArrindex2]: !isTrue,
    });
  },
  //关闭规则
  onClose() {
    animation.translateY(750).step();
    that.setData({
      animationInfo: animation.export()
    });
    that.setData({isShowType: ''});
  },
  //选择规则
  openSelect(e) {
    that.setData({ activeIndex: '' });
    if(e.target.dataset.item){
       that.setData({ reviewerObj: [e.target.dataset.item] });
    }
    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 index2 = e.target.dataset.index;
    var files = that.data.items[index2].files;
    if (files.length >= 3) {
      app.globalData.showToast("只能上传三张");
      return false;
    }
    dd.chooseImage({
      count: 1,
      success: (res) => {
        console.log(res);
          that.postImg(res.filePaths[0], index2);
      },
    });
  },
  postImg(img_url,index) {
    var files_box = `items[${index}].files`;
    var files=this.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:img_url,
          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:(err)=>{
            console.log(err);
          }
        });

      },
      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) {
    console.log(e);
    var index = e.target.dataset.index;
    var remark = `items[${index}].remark`
    this.setData({
      [remark]: e.detail.value,
    });
  },
  //积分输入
  bindKeyInput(e) {
    var index = e.target.dataset.index;
    var point = `items[${index}].point`;
    var selectRule = this.data.items[index].selectRule;
    var isArrindex = this.data.items[index].isArrindex;
    // var strMin, strMax;
    // if (selectRule.min_point < 0) {
    //   var min = selectRule.min_point.toString();
    //   strMin = min.slice(1, min.length);
    // } else {
    //   strMin = selectRule.min_point
    // }
    this.setData({
      [point]: e.detail.value,
    });
    return;
    //最小值
    var value;
    var showValue = e.detail.value
    if (isArrindex == true) {
      value = e.detail.value;
    } else {
      value = 0 - e.detail.value;
    }
    if (selectRule) {
      if (value < selectRule.min_point || value > selectRule.max_point) {
        app.globalData.showToast("已超出范围值")
        that.setData({
          [point]: Number(strMin)
        });
      } else {
        this.setData({
          [point]: showValue,
        });
      }
    } else {
      this.setData({
        [point]: showValue,
      });
    }
  },
  //选择规则分类
  bindKeyInput2(e) {
    var index = e.target.dataset.index;
    var point = `items[${index}].point2`;
    this.setData({
      [point]: e.detail.value,
    });
  },

  //删除一条
  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);
  },
  //添加一条
  addArr() {
    var arr = {//录入选项列表
      checked: true,
      rule_id: '',
      rule_id2: '',
      rule_name: '',
      item_id: 0,
      point: '',
      point2: '',
      remark: '',
      event_time: app.globalData.day,
      pt_id: '',
      reviewer_id:'',//审核人ID
      revieweName:'',//审批人姓名（非传）
      files: '',
      isArrindex: true,
      isArrindex2: true,
      selectRule: '',
    };
    var list = that.data.items
    list.push(arr);
    that.setData({
      items: list
    })
  },
  showToast(text) {
    app.globalData.showToast(text);
  },
  formSubmit() {
    var items = this.data.items;
    var userData = this.data.users;
    var arr = [];
    var isTg = true;
    var pt_id = app.getTypesItem("AF").id;
    if(userData.length==0){
      this.showToast('请输入录入对象')
      return;
    }
    for (var i = 0; i < items.length; i++) {
      var obj = {};
      var item = items[i];
      var num = item.checked ? item.point : item.point2
      var point;
      if (item.checked) {
        if (item.isArrindex != true) {
          point = 0 - num;
        } else {
          point = num;
        }
        if (point < item.selectRule.min_point || point > item.selectRule.max_point) {
          this.showToast(`第${i + 1}项,积分超出可输入范围`);
          isTg = false;
        }
      } else {
        if (item.isArrindex2 != true) {
          point = 0 - num;
        } else {
          point = num;
        }
      }
      if (item.checked) {
        if (!item.rule_id) {
          this.showToast(`第${i + 1}项请选择规则`);
          isTg = false;
          break;
        }
      } else {
        if (!item.rule_id2) {
          this.showToast(`第${i + 1}项请选择规则分类`);
          isTg = false;
          break;
        }
      }
      if (point == 0 || !point) {
        this.showToast(`第${i + 1}项积分不能为0或者为空`);
        isTg = false;
        break;
      }

      if (!item.remark) {
        this.showToast(`第${i + 1}项事件内容不能为空`);
        isTg = false;
        break;
      }
      obj.rule_id = item.checked ? item.rule_id : item.rule_id2;
      obj.item_id = item.checked ? item.item_id : 0;
      obj.point = point;
      obj.remark = item.remark;
      obj.event_time = item.event_time;
      obj.pt_id = pt_id;
      obj.reviewer_id = item.reviewer_id? item.reviewer_id:0;
      obj.files = item.files;
      arr.push(obj);
    }
    var userIds=[]
    userData.map(item=>{
      userIds.push(item.id)
    })
    if (isTg) {
      var data = {
        members: JSON.stringify(userIds),
        items: JSON.stringify(arr)
      }
       this.setData({disabled:true});
      app.$post("api/integral/review/a/entry", data).then((res) => {
        var is = true;
        var msg;
        res.data.data.forEach(item => {
          if (item.status != 1) {
            is = false;
            msg=item.rule_item;
          }
        })
        if (is) {
          this.showToast('已提交');
          setTimeout(() => {
            this.setData({disabled:false});
            dd.navigateBack({ delta: 1})
          }, 1000);
        }else{
          this.setData({disabled:false});
          this.showToast(msg);
        }
      }).catch(err=>{
          this.setData({disabled:false}); 
      })
    }
  },
  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
        })
      },
    });
  },
  //选择人
  onSelectUser(item) {
    console.log(item);
    var elm=item.length>0? item:[];
      this.setData({
        users: elm
      })
    
  },
  //选择人2
  onSelectUser2(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,
    });
  },

  //选择规则分类
  onSelectType(item) {
    var index = this.data.activeIndex;
    var rule_id2 = `items[${index}].rule_id2`;//分类ID
    var rule_name = `items[${index}].rule_name`;//分类名称
    this.setData({
      [rule_id2]: item.id,
      [rule_name]: item.name,
    });
  },
  //选择规则
  onSelectItem(item) {
    var index = this.data.activeIndex;
    var point = `items[${index}].point`
    var isArrindex = `items[${index}].isArrindex`
    var selectRule = `items[${index}].selectRule`
    var remark = `items[${index}].remark`
    var rule_id = `items[${index}].rule_id`;//分类ID
    var item_id = `items[${index}].item_id`;//分类ID
    var strMin;
    if (item.min_point < 0) {
      var min = item.min_point.toString();
      var strMin = min.slice(1, min.length);
    } else {
      strMin = item.min_point;
    }
    this.setData({
      [point]: Number(strMin),
      [isArrindex]: item.min_point > 0 ? true : false,
      [selectRule]: item,
      [remark]: item.remark,
      [rule_id]: item.rule_id,
      [item_id]: item.id,
    });
  },
});

