var app = getApp()
var that;
var animation;
Page({
  data: {
    users: [],
    items: {
      targets: [],//工作执行者列表,以逗号分割的字符串或直接传入数组
      pt_id: 3,//积分种类id
      task_name: '',//任务名
      task_remark: '',//任务详细描述
      base_point: '',//任务参考积分
      expire_time: '',//截至时间 格式:2020-02-02 12：00
      package_id: 0,//绩效任务包id 绩效任务包发布工作时必须大于0，其余工作发布为0
      weight: 0,//绩效权重 绩效任务包发布工作时必须大于0，其余工作发布为0
      file_list: [],//附件地址列表
      reviewer_id: '',//审批者id
      revieweName: '',
      timeout_deduction_point: '',//逾期扣分/月
      qualified: '',//
      cate_id: 0,// 共组分类id   
      task_cycle: 0,//重复周期
      task_expire_day: 1
    },
    reviewerObj: [],//默认审批人
    objectArray: [
      {
        id: 0,
        name: '不重复',
      },
      {
        id: 1,
        name: '每天重复',
      },
      {
        id: 2,
        name: '每周重复',
      },
      {
        id: 3,
        name: '每月重复',
      },
    ],
    arrIndex: 0
  },
  onLoad(e) {
    that = this;
    dd.setNavigationBar({ title: "任务编辑" });
    if (e.item) {
      var item = JSON.parse(e.item);
      console.log(item)
      this.setData({
        reviewerObj:[{name:item.reviewer_name,id:item.reviewer_id}],
        users:[{name:item.employee_name,id:item.employee_id}],
        items: {
          id:item.id,
          targets: [item.employee_id],//工作执行者列表,以逗号分割的字符串或直接传入数组
          pt_id: item.pt_id,//积分种类id
          task_name: item.task_name,//任务名
          task_remark: item.task_remark,//任务详细描述
          base_point: item.point_config.base_point,//任务参考积分
          expire_time: item.expire_time,//截至时间 格式:2020-02-02 12：00
          package_id: 0,//绩效任务包id 绩效任务包发布工作时必须大于0，其余工作发布为0
          weight: 0,//绩效权重 绩效任务包发布工作时必须大于0，其余工作发布为0
          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,//逾期扣分/月
          qualified:item.point_config.base_point,//
          cate_id: 0,// 共组分类id   
          task_cycle:0,//重复周期
          task_expire_day: 1
        },
      })
    }
    that.setData({
      types: app.globalData.types
    })
  },
  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
    })
  },
  onShow() {
    animation = dd.createAnimation({
      duration: 200,
      timeFunction: "linear",
    });
  },
  //积分输入
  bindKeyInput(e) {
    var point = `items.base_point`;
    this.setData({
      [point]: e.detail.value,
      [`items.qualified`]: e.detail.value
    });
  },
  //积分输入
  bindKeyInput2(e) {
    var point = `items.timeout_deduction_point`;
    this.setData({
      [point]: e.detail.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()
    });
    that.setData({ isShowType: '' });
  },
  //选择弹窗
  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: [] });
      }
    }
    that.setData({
      isShowType: num,
    });
    animation.translateY(0).step();
    that.setData({
      animationInfo: animation.export()
    });
  },
  //删除图片
  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;
    var page1 = getCurrentPages()[getCurrentPages().length - 2]//上一个页面的数据
    console.log(items);
    if (!items.task_name) {
      this.showToast('请输入任务内容')
      return;
    }
    if (!items.base_point) {
      this.showToast('请输入任务记分')
      return;
    }
    if (items.targets.length == 0) {
      this.showToast('请选择执行对象')
      return;
    }
    if (!items.reviewer_id) {
      this.showToast('请选择审批人')
      return;
    }
    if (!items.expire_time) {
      this.showToast('请选择截止时间')
      return;
    }
    if (!items.task_remark) {
      delete items.task_remark
    }
    if (!items.timeout_deduction_point) {
      delete items.timeout_deduction_point
    }
    items.file_list = items.file_list.toString();
    items.targets = items.targets.toString();
    this.setData({ disabled: true });
    app.$post('api/integral/work/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) {
    var index = e.target.dataset.index;
    var item = `items[${index}].checked`;
    that.setData({
      [item]: 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
        })
      },
    });
  },
  //选择执行人
  onSelectUser(item) {
    var arr = [];
    if (item.length > 0) {
      item.forEach(user => {
        arr.push(user.id);
      })
      that.setData({
        users: item.length > 0 ? item : [],
        [`items.targets`]: arr
      })
    }

  },
  //选择审批人
  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,
    });

  },
});

