var app = getApp()
var that;
var animation;
Page({
  data: {
    items: {
      dept_ids: [],//可见范围
      pt_id: 3,//积分种类id
      task_name: '',//任务名
      task_remark: '',//任务详细描述
      base_point: '',//任务参考积分
      base_point2: '',//任务参考积分
      expire_time: '',//截至时间 格式:2020-02-02 12：00
      file_list: [],//附件地址列表
      reviewer_id: '',//审批者id
      revieweName: '',
      timeout_deduction_point: '',//逾期扣分/天
      timeout_deduction_point_limit:'',//逾期扣分上限
      ahead_award_point: '',//提前奖分/天
      ahead_award_point_limit:'',//提前奖分上限
      task_cycle: 0,
      task_expire_day: 1,
      task_type:1,

      pt_name:'B分',
      checked: false,//是否选择规则
      rule_id: '',//积分分类id
      item_id: 0,//积分细则id 不选可以为0
    },
    reviewerObj: [],//默认审批人
    objectArray: [
      {
        id: 0,
        name: '不重复',
      },
      {
        id: 1,
        name: '每天重复',
      },
      {
        id: 2,
        name: '每周重复',
      },
      {
        id: 3,
        name: '每月重复',
      },
    ],
    arrIndex: 0,
    defaultSection: [],//选择的部门
    point_limit:0,

    defaultRuleId: '',
    selectRule: '',//选择的规则
    isArrindex: true,
    isGzType: 3,
    popupCx: '',
  },
  onLoad(e) {
    that = this;
    dd.setNavigationBar({ title: "悬赏任务编辑" });
    if (e.item) {
      var item = JSON.parse(e.item);
      var arr=[];
      if(item.department_info.length>0){
        item.department_info.forEach(item=>{
          arr.push(item.id);
        })
      }
      if(item.item_id){
        if(item.point_config.base_point<0){
          this.setData({
              isArrindex:false
          })
        }
      }
      this.setData({
        selectRule:item.item_id? item.point_config.item_info:'',
        reviewerObj:[{name:item.reviewer_name,id:item.reviewer_id}],
        users:[{name:item.employee_name,id:item.employee_id}],
        defaultSection:item.department_info,
        items: {
          dept_ids:arr,
          id:item.id,
          pt_id: item.pt_id,//积分种类id
          task_name: item.task_name,//任务名
          task_remark: item.task_remark,//任务详细描述
          base_point: item.point_config.base_point <0? (0-item.point_config.base_point):item.point_config.base_point,//任务参考积分
          base_point2: item.point_config.base_point <0? (0-item.point_config.base_point):item.point_config.base_point,//任务参考积分
          expire_time: item.expire_time,//截至时间 格式:2020-02-02 12：00
          file_list: item.task_file_list,//附件地址列表
          reviewer_id:item.reviewer_id,//审批者id
          revieweName:item.reviewer_name,
          timeout_deduction_point: item.point_config.timeout_deduction_point,//逾期扣分/天
          timeout_deduction_point_limit:item.point_config.timeout_deduction_point_limit,//逾期扣分上限
          ahead_award_point: item.point_config.ahead_award_point,//提前奖分/天
          ahead_award_point_limit:item.point_config.ahead_award_point_limit,//提前奖分上限
          task_cycle: 0,
          task_expire_day: 1,
          task_type:1,

          
          rule_id: item.rule_id,//积分分类id
          item_id: item.item_id,//积分细则id 不选可以为0
          checked: item.item_id? true:false,//是否选择规则
        },
        types: app.globalData.types,
        point_limit:app.globalData.userData.point_config.point_limit,
        isGzType: item.pt_id,
      })
    }
  },

  //选择奖还是扣(细则)
  bindPickerChange() {
    this.setData({
      isArrindex: !that.data.isArrindex,
    });
  },
  //选择规则
  onSelectItem(item) {
    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;
    }
    that.setData({
      selectRule: item,
      [`items.task_remark`]: item.remark,
      [`items.base_point`]: Number(strMin),
      isArrindex: item.min_point > 0 ? true : false,
      [`items.rule_id`]: item.rule_id,
      [`items.item_id`]: item.id,
    })
  },

  bindObjPickerChange(e) {
    this.setData({
      arrIndex: e.detail.value,
      [`items.task_cycle`]: e.detail.value
    });
  },
  openType(e) {
    var id = e.target.dataset.id;
    that.setData({
      [`items.pt_id`]: id,
      isGzType: id,
    })
    this.clearTree()
  },
  //清除已选规则
  clearTree(){
    that.setData({
      selectRule: '',
      ['items.task_remark']: '',
      [`items.base_point`]: '',
      isArrindex: true,
      [`items.rule_id`]: '',
      [`items.item_id`]: '',
      defaultRuleId: ''
    })
  },
  onShow() {
    animation = dd.createAnimation({
      duration: 200,
      timeFunction: "linear",
    });
  },
    //积分输入
  bindKeyInput2(e) {
    this.setData({
      [`items.base_point2`]: e.detail.value,
    });
  },
  //积分输入
  bindKeyInput1(e) {
    var point = `items.base_point`;
    this.setData({
      [point]: e.detail.value,
      [`items.qualified`]: e.detail.value
    });
  },
  //积分输入
  bindKeyInput3(e) {
    var name = e.target.dataset.name;
    let value = e.detail.value;
    var point = `items.${name}`;
    if (that.data.point_limit.length > 0) {
      var pointIimit = that.data.point_limit[1].point;
      if (pointIimit != 0 && pointIimit != -1) {
        if (name == 'timeout_deduction_point' || name == 'ahead_award_point') {
          pointIimit = pointIimit * 1;
          if (value > pointIimit) {
            this.showToast('分值不能超过您的奖扣分权限');
            this.setData({
              [point]: '',
            });
            return false
          }
        } else {
          pointIimit = pointIimit * 10;
          if (value > pointIimit) {
            this.showToast('上限不能超过' + pointIimit + '分');
            this.setData({
              [point]: '',
            });
            return false
          }
        }
      }
    }
    this.setData({
      [point]: value,
    });
  },

  //显示图片
  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(),
      popupCx: '',
      isShowType: '',
    });
  },
  //选择部门
  onSelectSection(e) {
    var arr = [];
    if (e.length > 0) {
      e.forEach(user => {
        arr.push(user.id);
      })
      that.setData({
        defaultSection: e,
        [`items.dept_ids`]: arr
      })
    }
  },
  //选择弹窗
  openSelect(e) {
    var num = e.target.dataset.num;
    if (e.target.dataset.item) {
      if (e.target.dataset.item.id) {
        that.setData({ reviewerObj: [e.target.dataset.item] });
      } else {
        that.setData({ reviewerObj: [] });
      }
    }
    if (e.target.dataset.ruleId) {
      that.setData({ defaultRuleId: e.target.dataset.ruleId });
    }
    animation.translateY(0).step();
    that.setData({
      animationInfo: animation.export(),
      isShowType: num,
      popupCx: 'container__mask',
    });
  },
  //删除图片
  deteleImg(e) {
    var index = e.target.dataset.index;//获取itemS集合中对应的files
    var files = that.data.items.file_list;//获取itemS集合中对应的files
    var files_box = `items.file_list`;//
    app.globalData.arrRemoveObj(files, files[index]);
    that.setData({
      [files_box]: files
    });

  },
  //图片选择
  openImg(e) {
    var files = that.data.items.file_list;
    if (files.length >= 3) {
      app.globalData.showToast("只能上传三张");
      return false;
    }
    dd.chooseImage({
      count: 1,
      success: (res) => {
        that.postImg(res.filePaths[0]);
      },
    });
  },
  postImg(img_url) {
    var files_box = `items.file_list`;
    var files = that.data.items.file_list;
    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: 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
              });
              console.log(that.data.items);
              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) {
    this.setData({
      [`items.task_name`]: e.detail.value,
    });
  },
  //备注输入
  bindTextAreaBlur2: function (e) {
    this.setData({
      [`items.task_remark`]: e.detail.value,
    });
  },

  showToast(text) {
    app.globalData.showToast(text);
  },
  formSubmit() {
    var items = this.data.items;
    if (!items.task_name) {
      this.showToast('请输入任务内容')
      return;
    }
    if(items.checked){
      let selectRule=this.data.selectRule;
      if (!selectRule) {
        this.showToast('请选择规则')
        return;
      }
      if (!items.base_point) {
        this.showToast('请输入任务积分')
        return;
      }
      let value=items.base_point;
      let point;
      if (!this.data.isArrindex) {
        point = 0 - value;
      } else {
        point = value;
      }
      if (point < selectRule.min_point || point > selectRule.max_point) {
        this.showToast(`任务分值超出可输入范围`);
        return false
      }
      items.base_point=point;
      items.qualified=point;
    }else{
      if (!items.base_point2) {
        this.showToast('请输入任务积分')
        return;
      }
      items.base_point=items.base_point2
      items.qualified=items.base_point2;
      delete items.rule_id
      delete items.item_id
    }
    if (!items.reviewer_id) {
      this.showToast('请选择审批人')
      return;
    }
    if (!items.expire_time) {
      this.showToast('请选择截止时间')
      return;
    }
     var page1 = getCurrentPages()[getCurrentPages().length - 2]//上一个页面的数据
    if(!items.task_remark){
      delete items.task_remark
    }
    if(!items.timeout_deduction_point){
      delete items.timeout_deduction_point
    }
    if(items.dept_ids.length==0){
      delete items.dept_ids
    }else{
      items.dept_ids=items.dept_ids.toString();
    }
    items.file_list=items.file_list.toString();
    this.setData({ disabled: true });
    app.$post('api/integral/task/update',items).then((res) => {
        page1.getDetail(items.id,function(){
            app.globalData.showToast(res.data.msg);
            setTimeout(() => {
              dd.navigateBack({ delta: 1 })
            }, 1000);
        })
    }).finally(err => {
      this.setData({ disabled: false });
    })
  },
  switchChange(e) {
    that.setData({
      [`items.checked`]: e.detail.value
    })
  },
  //选择时间
  openDate(e) {
    var item = `items.expire_time`
    dd.datePicker({
      format: 'yyyy-MM-dd HH:mm',
      currentDate: that.data.items.expire_time,
      success: (res) => {
        that.setData({
          [item]: res.date
        })
      },
    });
  },
  //选择审批人
  onSelectUser2(item) {
    var elm = item.length > 0 ? item[0] : { id: '', name: '' };
    var reviewer_id = `items.reviewer_id`
    var revieweName = `items.revieweName`
    that.setData({
      [reviewer_id]: elm.id,
      [revieweName]: elm.name,
    });

  },
});

