var app = getApp();
var that;
import { returnStr, setCache, getCache, _debounce, getRole } from '../../../utils/util'
Page({
  data: {
    detailsshow: false,
    apdList: [],
    detailsTIt: '',
    apDetails: {},
    apList: [],

    knowFrom: '',
    packId: 0, // 记录id
    assessID: 0, // 记录人
    planIndex: [], // 维度下标，指标下标
    isShowAdd: false, // 是否显示添加按钮

    isWt: false,
    titValue: '', // 执行计划名
    messageVal: '', // 备注
    bootBool: false,// 防止多次请求
    has_finish: 0,

    // 上传图标与附件
    img_fileList: [], // 图片附件
    isShowText: false,
    isShowDetil: false,//显示详情
    append: [],
  },
  onLoad() {
    that = this;
  },
  onShow() {
    this.setData({
      query: getCache('actionplanDetails')
    })
    this.init()
  },
  showDetil() {
    this.setData({
      isShowDetil: !this.data.isShowDetil
    })
  },
  showText() {
    this.setData({
      isShowText: !this.data.isShowText
    })
  },
  deleteImg(e) {
    if (this.data.append.length == 1) {
      this.setData({
        append: []
      })
      return false
    }
    let append = this.data.append;
    append.splice(e.target.dataset.index, 1)
    this.setData({
      append: append
    })
  },
  // 返回时刷新列表数据
  routeBack() {
    let query = getCache('actionplanList');
    if (query) {
      let data = {
        know: this.data.knowFrom,
        apList: this.data.apList,
        packId: this.data.packId,
        assessID: this.data.assessID,
        recordMemberIds: query.recordMemberIds ? query.recordMemberIds : []
      };
      setCache('actionplanList', data);
    }
  },
  save() {
    // 保存
    if (this.data.knowFrom == 'action') {
      // 执行计划
      this.saveAction('api/per/package/action');
    } else if (this.data.knowFrom == 'admnin') {
      // 管理记录
      this.saveAction('api/per/package/track');
    }
  },
  saveAction(urls) {
    if (this.data.bootBool) {
      return;
    }
    // 执行计划
    if (!this.data.titValue && this.data.titValue == '') {
      app.globalData.showToast('请输入标题');
      return;
    }
    let data = {
      package_employee_id: this.data.packId,
      index_id: this.data.apDetails.id,
      title: this.data.titValue,
      remark: this.data.messageVal,
      dimension_xb: this.data.planIndex[0],
      // images: JSON.stringify(images),
      append: JSON.stringify(this.data.append), //附件
      // appendName: '' //附件名称
    };
    this.setData({
      bootBool: true
    })
    app.$post(urls, data).then(res => {
        if (res.data.code == 1) {
          app.globalData.showToast('提交成功');
          this.setData({
            titValue: '',
            messageVal: '',
            append: [],
          })
          this.employeeDet();
        }
    })
    setTimeout(() => {
      this.setData({
        bootBool: false
      })
    }, 1000);
  },
  closeWt() {
    localStorage.setItem('isWt', true);
    this.isWt = false;
  },
  addThePlan(item) {
    if (!this.isShowAdd || this.has_finish) {
      return false
    }
    let data = {
      know: this.knowFrom,
      keys: JSON.stringify(item) || null,
      apList: JSON.stringify(this.apDetails),
      packId: this.packId,
      assessID: this.assessID,
      planIndex: this.planIndex[0] //维度下标
    };
    this.$setCache('addthePlan', data);
    // 添加
    this.$router.push({ name: 'addthePlan' });
  },
  bindTextAreaBlur: function (e) {
    this.setData({
      titValue: e.detail.value,
    });
  },
  bindTextAreaBlur2: function (e) {
    this.setData({
      messageVal: e.detail.value,
    });
  },
  employeeDet() {
    let params = {
      id: this.data.packId
    };
    app.$get('api/per/package/employee/info', params).then(res => {
      if (res.data.code == 1) {
        let data = res.data.data;
        this.setData({
          has_finish: data.has_finish
        })
        let dimension = data.dimension[this.data.planIndex[0]].index[this.data.planIndex[1]];
        this.setData({
          apList: JSON.stringify(data.dimension)
        })
        if (this.data.knowFrom == 'action') {
          // 执行计划
          if (dimension.schedule) {
            dimension.schedule.map(item => {
              if (app.globalData.usersList[item.employee_id]) {
                item.userName = app.globalData.usersList[item.employee_id] ? app.globalData.usersList[item.employee_id].name : ''
              }
            })
            this.setData({
              apdList: dimension.schedule
            })
          }
        } else if (this.data.knowFrom == 'admnin') {
          // 管理记录
          if (dimension.mamage_record) {
            dimension.mamage_record.map(item => {
              if (app.globalData.usersList[item.employee_id]) {
                item.userName = app.globalData.usersList[item.employee_id] ? app.globalData.usersList[item.employee_id].name : ''
              }
            })
            this.setData({
              apdList: dimension.mamage_record
            })
          }
        }
      }
      this.routeBack();
    })
  },
  init() {
    let query = this.data.query;
    let apList = JSON.parse(query.apList);
    this.setData({
      knowFrom: query.know,
      packId: query.packId,
      assessID: query.assessID,
      planIndex: apList.planIndex,
      apDetails: apList,
      append:this.data.append.length>0? this.data.append:[],
    })

    if (this.data.knowFrom == 'action') {
      if (this.data.assessID == app.globalData.userData.id) {
        this.setData({
          isShowAdd: true
        })
      }
      // 执行计划
      this.setData({
        detailsTIt: '执行计划'
      })
    } else if (this.data.knowFrom == 'admnin') {
      this.setData({//管理记录人判断
        isShowAdd: apList.isOperation
      })
      this.getSuperior(query.assessID);
      // this.$getEmployeeAll()[this.assessID].employee_detail.superior_list.some(item => {
      //   // 判断被考核人的上级是否包含登录者
      //   if (item.id == this.$getUserData_jx().id) {
      //     this.isShowAdd = true;
      //     return true;
      //   }
      // });
      if (app.globalData.userData.is_creator == 1) {
        // 如果是创始人也可以操作
        this.setData({
          isShowAdd: true
        })
      }
      if (app.getPermis(3)) {
        // 如果是子管理员并且管理范围权限为“全公司”
        this.setData({
          isShowAdd: true
        })
      }
      this.setData({
        detailsTIt: '管理记录'
      })
    }

    this.employeeDet();
  },
  // 判断是否当前被考核人的上级
  getSuperior(id) {
    app.$get('api/per/user/manager_list', { id_code: app.returnCode(id) }).then(res => {
      let superiorList = res.data.data; //被考核人上级
      superiorList.some(item => {
        if (item.id == app.globalData.userData.id) {
          this.setData({
            isShowAdd: true
          })
          return true
        }
      })
    });
  },
  showImg(e) {
    let item = e.target.dataset.item
    app.$get('api/drive/grant', { file_id: item.fileId }).then(res => {
      dd.previewFileInDingTalk({
        corpId: app.globalData.corpId,
        spaceId: item.spaceId,
        fileId: item.fileId,
        fileName: item.fileName,
        fileSize: item.fileSize,
        fileType: item.fileType,
      })
    })
  },
  openDetail(e) {
    let item = e.target.dataset.item
    if (!this.data.isShowAdd || this.data.has_finish) {
      return false
    }
    let data = {
      know: this.data.knowFrom,
      keys: JSON.stringify(item) || null,
      apList: JSON.stringify(this.data.apDetails),
      packId: this.data.packId,
      assessID: this.data.assessID,
      planIndex: this.data.planIndex[0] //维度下标
    };
    setCache('addthePlan', data);
    dd.navigateTo({
      url: `../addthePlan/addthePlan`
    })
  },
  //图片选择
  openImg(e) {
    let append = this.data.append;
    app.$get('api/drive/info').then(res => {
      let spaceId = res.data.data.space_id.toString()
      dd.uploadAttachmentToDingTalk({
        image: { multiple: true, compress: false, max: 5, spaceId: spaceId },
        space: { spaceId: spaceId, isCopy: 1, max: 5 },
        file: { spaceId: spaceId, max: 5 },
        types: ["photo", "file", "space"],//PC端仅支持["photo","file","space"]
        success: (res) => {
          append.push(...res.data);
          that.setData({
            append: append
          })
        },
        fail: (err) => {
          console.log(err)
        }
      })
    })


    return false
    var files = that.data.img_fileList;
    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 = that.data.img_fileList;
    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/ddJx/' + app.globalData.userData.site_id + "/" + app.globalData.day + '/' + that.random_string(32) + '.png';
        } else {
          var key = 'intesys/ddJx/' + 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(app.globalData.ALIOSS_URL + '/' + key)
              } else {
                files = [app.globalData.ALIOSS_URL + '/' + key];
              }
              that.setData({
                img_fileList: 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
  },
});
