import config from '../../../config'
import {
  getToken
} from '../../../utils/auth'
import {
  findPlanDatas,
  findRecursionPlan,
  findPreviousSchedule,
  submitPlanSchedule
} from '../../../api/project'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    maxDate: new Date().getTime() + (3600 * 24 * 30 * 1000),
    form: {
      schedulePercent: 1
    },
    loadShow: false,
    imageInfoData: [],
    picker: false,
    planOptions: [],
    previousSchedule: null, //上次填报数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!getToken()) {
      wx.redirectTo({
        url: '../../../pages/login/login',
      })
    }
    this.setData({
      "form.projectId": app.globalData.useProjectId,
      "form.projectName": app.globalData.useProjectName
    });
    this.initPlanDatas();
  },

  /**
   * 打开选择窗
   */
  openPicker() {
    this.setData({
      picker: true
    })
  },

  closePicker() {
    this.setData({
      picker: false
    })
  },

  /**
   * 构建树结构
   * @param {*} all 
   * @param {*} id 
   */
  buildTree(all, id) {
    let tmps = all.filter((d) => d.parentId == id);
    if (tmps.length > 0) {
      tmps.forEach((it) => {
        it.children = this.buildTree(all, it.taskId);
      });
    }
    return tmps;
  },

  /**
   * 初始化计划
   */
  initPlanDatas() {
    findPlanDatas(app.globalData.useProjectId).then((res) => {
      let treeDatas = this.buildTree(res.data, 1);
      this.setData({
        planOptions: treeDatas
      })
    });
  },

  /**
   * 组件选中时会触发
   */
  handleClick: function (e) {
    let checkIds = e.detail.idList;
    if (checkIds.length > 0) {
      let planValue = checkIds[checkIds.length - 1];
      this.setData({
        picker: false
      })
      findRecursionPlan(planValue.planId).then(res => {
        if (res.data) {
          this.setData({
            "form.comId": res.data.comid,
            "form.planId": planValue.planId,
            "form.taskId": res.data.taskId,
            "form.taskUniqueId": res.data.taskUniqueId,
            "form.taskName": res.data.taskName,
            "form.bimId": res.data.bimId,
          });
        } else {
          this.setData({
            "form.comId": null,
            "form.taskId": null,
            "form.taskUniqueId": null,
            "form.taskName": null,
            "form.bimId": null,
          });
        }
      });
      findPreviousSchedule(planValue.planId).then((res) => {
        if (res.data) {
          this.setData({
            previousSchedule: res.data,
            "form.schedulePercent": res.data.schedulePercent
          });
        } else {
          this.setData({
            previousSchedule: null,
            "form.schedulePercent": 1
          });
        }
      });
    }
  },

  onChangeMinus(e) {
    this.setData({
      "form.schedulePercent": this.data.form.schedulePercent - 1
    });
  },
  onChangePlus(e) {
    this.setData({
      "form.schedulePercent": this.data.form.schedulePercent + 1
    });
  },

  onChangeBlur(e) {
    this.setData({
      "form.schedulePercent": e.detail.value
    });
  },

  //完成时间
  onInputTime(e) {
    this.setData({
      "form.finishDate": e.detail
    })
  },

  //进度描述
  onInputDescription(e) {
    this.setData({
      "form.description": e.detail.value
    })
  },

  // 上传图片
  onImagesArr(e) {
    this.setData({
      imageInfoData: e.detail
    })
  },

  /**
   * 数据保存
   */
  submitSave() {
    let _form = {
      ...this.data.form
    };
    let {
      imageInfoData
    } = this.data
    //数据效验
    if (!_form.projectId) {
      app.toast("数据异常,请刷新页面重试!")
      return false;
    }
    if (!_form.planId) {
      app.toast("请选择工程计划!")
      return false;
    }
    if (!_form.schedulePercent) {
      app.toast("请填写计划完成进度!")
      return false;
    } else {
      if (_form.schedulePercent == 100 && !_form.finishDate) {
        app.toast("请选择完成时间!")
        return false;
      }
    }
    if (!_form.description) {
      app.toast("请填写进度描述!")
      return false;
    }
    if (imageInfoData.length == 0) {
      app.toast("请上传施工现场作业图!")
      return false;
    }
    let fileUrls = [];
    this.setData({
      loadShow: true
    });
    let that = this;
    imageInfoData.forEach(async (item) => {
      //这里复杂的图片上传,改为同步上传,因为小程序只能上传一张图片
      let obj = await that.syncUploadImage(item);
      fileUrls.push(obj.data.data.url);
      //验证图片上传完毕
      if (fileUrls.length == imageInfoData.length) {
        _form.images = fileUrls.toString();
        submitPlanSchedule(_form).then(res => {
          this.setData({
            loadShow: false
          });
          if (res.code == 200) {
            app.toast("新增进度成功!")
            setTimeout(() => {
              wx.redirectTo({
                url: `../list/index`,
              })
            }, 200)
          }
        });
      }
    })
  },

  returnToPage: function () {
    /*关闭当前页面,跳转到其它页面。*/
    wx.redirectTo({
      url: `../list/index`,
    })
  },

  /**
   * 这里考虑上传图片异步问题,封装为同步
   */
  syncUploadImage(file) {
    let _baseUrl = config.baseUrl;
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: _baseUrl + "/file/upload", // 上传的服务器接口地址
        filePath: file,
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          'Authorization': 'Bearer ' + getToken()
        },
        name: "file", //上传的所需字段,后端提供
        formData: {},
        success: (res) => {
          // 上传完成操作
          const data = JSON.parse(res.data)
          resolve({
            data: data
          })
        },
        fail: (err) => {
          //上传失败:修改pedding为reject
          console.log("访问接口失败", err);
          wx.showToast({
            title: "网络出错,上传失败",
            icon: 'none',
            duration: 1000
          });
          reject(err)
        }
      });
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})