var app = getApp();
var that;
import { returnStr, setCache, getCache, _debounce, getRole } from '../../../utils/util'
Page({
  data: {
    apDetails: {
      name: '技术部量化指标1_（50%）',
      standard: '完成50万，100分<br/>技术部量化标准1',
      weight: 50,
      target: '100 万'
    },
    detailsshow: false,
    titValue: '', // 执行计划名
    messageVal: '', // 备注

    knowFrom: '',
    detailsTIt: '',
    packId: 0, // 记录ID
    keyszb: {},
    arrlist: false,
    bootBool: false, // 防止多次请求
    isShowAdd: false, // 是否可操作
    assessID: 0,
    planIndex: [],
    // 上传图标与附件
    // img_fileList: [],
    appendObj: {
      append: '',
      append_name: ''
    },
    isShowDetil: false,
    append: [],
  },
  onLoad() {
    that = this;
    dd.setNavigationBar({ title: "编辑管理记录" });
  },
  onShow() {
    this.setData({
      rout: getCache('addthePlan')
    })
    this.init()
  },
  showDetil() {
    this.setData({
      isShowDetil: !this.data.isShowDetil
    })
  },
  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,
      })
    })
  },
  deleteList() {
    dd.confirm({
      title: this.data.knowFrom == 'action' ? '删除计划' : '删除记录',
      content: '确认删除' + this.data.detailsTIt + ' ：' + this.data.titValue + '',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          if (this.data.knowFrom == 'action') {
            // 执行计划
            this.deLists('api/per/package/action/del', 'action');
          } else if (this.data.knowFrom == 'admnin') {
            // 管理记录
            this.deLists('api/per/package/track/del', 'admnin');
          }
        }
      },
    });
  },
  deLists(urls, name) {
    let data = {
      package_employee_id: this.data.packId,
      index_id: this.data.apDetails.id,
      dimension_xb: this.data.planIndex
    };
    if (name == 'action') {
      data.action_id = this.data.keyszb.id;
    } else if (name == 'admnin') {
      if (this.data.keyszb.employee_id != app.globalData.userData.id) {
        app.globalData.showToast('不能删除其他管理者的管理记录！');
        return false;
      }
      data.track_id = this.data.keyszb.id;
    }
    app.$post(urls, data).then(res => {
      if (res.data.code == 1) {
        app.globalData.showToast('删除成功');
        this.routerBak();
      }
    });
  },
  save() {
    // 保存
    if (this.data.knowFrom == 'action') {
      // 执行计划
      this.saveAction('api/per/package/action');
    } else if (this.data.knowFrom == 'admnin') {
      // 管理记录
      this.saveAction('api/per/package/track');
    }
  },
  routerBak() {
    var page = getCurrentPages()[getCurrentPages().length - 2]//上一个页面的数据
    if(page){
      page.employeeDet()
    }
    dd.navigateBack({
      delta: 1
    })
  },
  saveAction(urls) {
    if (this.data.bootBool) {
      return;
    }
    // 执行计划
    if (!this.data.titValue && this.data.titValue == '') {
      app.globalData.showToast('请输入标题');
      return;
    }
    // let images = [];
    // this.data.img_fileList.forEach(item => {
    //   let str = item.split("/")
    //   images.push(
    //     { name: str[str.length - 1], url: item }
    //   )
    // })
    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,
      // images: JSON.stringify(images),
      append: JSON.stringify(this.data.append), //附件
      // appendName: '' //附件名称
    };
    if (this.data.arrlist) {
      if (this.data.knowFrom == 'admnin') {
        if (this.data.keyszb.employee_id != app.globalData.userData.id) {
          app.globalData.showToast('不能编辑其他管理者的管理记录！');
          return false;
        }
        data.track_id = this.data.keyszb.id;
      } else {
        data.action_id = this.data.keyszb.id;
      }
    }
    this.setData({
      bootBool: true
    })
    app.$post(urls, data).then(res => {
        if (res.data.code == 1) {
          app.globalData.showToast('提交成功');
          this.routerBak();
        }
    })
    setTimeout(() => {
        this.setData({
          bootBool: false
        })
    }, 1000);
  },
  bindTextAreaBlur: function (e) {
    this.setData({
      titValue: e.detail.value,
    });
  },
  bindTextAreaBlur2: function (e) {
    this.setData({
      messageVal: e.detail.value,
    });
  },
  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
    })
  },
  init() {
    let rout = this.data.rout;
    this.setData({
      planIndex: rout.planIndex,
      assessID: rout.assessID,
      keyszb: JSON.parse(rout.keys),
    })
    if (this.data.keyszb) {
      this.setData({
        arrlist: true,
        titValue: this.data.keyszb.title,
        messageVal: this.data.keyszb.remark,
        append:this.data.append.length>0? this.data.append:this.data.keyszb.append,
      })
    } else {
      this.setData({
        arrlist: false
      })
    }
    this.setData({
      knowFrom: rout.know
    })
    let apList = JSON.parse(rout.apList);
    this.setData({
      apDetails: apList,
      packId: rout.packId
    })
    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(rout.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: '管理记录',
      })
    }
  },
    // 判断是否当前被考核人的上级
  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
        }
      })
    });
  },
  //图片选择
  openImg(e) {
    let append = this.data.append;
    app.$get('api/drive/info').then(res => {
      let spaceId = res.data.data.space_id
      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) => {
          console.log(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
  },
});
