var app = getApp()
var that;
var animation;
Page({
  data: {
    items: {
      dept_ids: [],//可见范围
      pt_id: 3,//积分种类id
      task_name: '',//任务名
      task_remark: '',//任务详细描述
      base_point: '',//任务参考积分
      expire_time: '',//截至时间 格式:2020-02-02 12：00
      file_list: [],//附件地址列表
      reviewer_id: '',//审批者id
      revieweName: '',
      timeout_deduction_point: '',//逾期扣分/月
      task_cycle: 0,
      task_expire_day: 1,
      task_type:1,
    },
    reviewerObj: [],//默认审批人
    objectArray: [
      {
        id: 0,
        name: '不重复',
      },
      {
        id: 1,
        name: '每天重复',
      },
      {
        id: 2,
        name: '每周重复',
      },
      {
        id: 3,
        name: '每月重复',
      },
    ],
    arrIndex: 0,
    defaultSection: [],//选择的部门
  },
  onLoad() {
    that = this;
    dd.setNavigationBar({ title: "发布悬赏任务" });
    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,
    });
  },
  //积分输入
  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: '' });
  },
  //选择部门
  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: [] });
      }
    }
    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;
    console.log(items);
    if (!items.task_name) {
      this.showToast('请输入任务内容')
      return;
    }
    if (!items.base_point) {
      this.showToast('请输入任务记分')
      return;
    }
    if (!items.reviewer_id) {
      this.showToast('请选择审批人')
      return;
    }
    if (!items.expire_time) {
      this.showToast('请选择截止时间')
      return;
    }
    // items.file_list=JSON.stringify(items.file_list);
    // items.targets=JSON.stringify(items.targets);
    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 });
        var url;
    if (items.task_cycle == 0) {
        url = '/api/integral/task/publish'
      } else {
        url = '/api/integral/schedule/publish/task'
    }
    app.$post(url,items).then((res) => {
        this.showToast(res.data.msg);
        setTimeout(() => {
          this.setData({ disabled: false });
          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
        })
      },
    });
  },
  //选择审批人
  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,
    });

  },
});

