import create from 'dd-store'
import { saveFileInfo, addSchedule, uploadPermissions, previewPermissions } from '../../api/request.js'
import { throttle, debounce } from './../../utils/utils.js'
import pageStore from '../meetingDetail/store';

create.Page({
  store: pageStore,
  data: {
    fileInfos: null, //store
    description: '',//store
    action: ''
  },
  onLoad(query) {
    dd.setNavigationBar({
      title: '添加会议文件'
    });
    // 编辑的时候传action=update
    if (query && query.action == 'update') {
      this.setData({
        action: query.action
      });
      dd.setNavigationBar({
        title: '编辑会议文件'
      });
    }
  },
  onShow() {
  },
  // inputDes(event) {
  //   let value = event.detail.value
  //   this.setData({
  //     description: value
  //   })
  // },
  inputChange: debounce(function (e) {
    const value = e.detail.value;
    if (value) {
      this.store.data.description = value;
      this.update();
    }
  }, 1000),

  add() {
    const data = {
      ddUserId: getApp().globalData.userid,
      type: 'add',
      projectName: 'MING_MEETING'
    }
    uploadPermissions(data).then(res => {
      if (res.data.code === 0) {
        const _that = this
        dd.uploadAttachmentToDingTalk({
          image: { multiple: true, compress: true, max: 9, spaceId: res.data.data },
          space: { spaceId: res.data.data, compress: true, isCopy: 1, max: 9 },
          types: ["photo", "camera", "space"],
          success: (res) => {
            _that.store.data.fileInfos.push(...res.data)
            _that.update();
          },
          fail: (err) => {
          }
        })
      }
    })
  },

  // 保存的接口
  saveUpload: throttle(function () {
    const { fileInfos, oldFileInfos, description, oldDescription } = this.store.data;

    if (!fileInfos || (fileInfos && fileInfos.length == 0)) {
      dd.showToast({
        content: '请上传文件'
      })
      return;
    }

    //如果实际没有修改,不生成记录
    if (this.data.action == 'update') {
      if (oldFileInfos == JSON.stringify(fileInfos) && description == oldDescription) {
        return dd.navigateBack()
      }
    }

    const data = {
      resourceType: 'accessory',
      creatorId: getApp().globalData.userid,
      category: '2',
      scheduleId: this.store.data.scheduleId,
      groupId: this.store.data.groupId,
      uploader: getApp().globalData.userid,
      creatorInfo: getApp().globalData.userInfo,
      thirdStoreTenant: 'dingTalk',
      fileInfos: JSON.stringify(fileInfos),
      description: description,
      logType: 'schedule_accessory_add'
    }

    if (this.data.action == 'update') {
      data.logType = 'schedule_accessory_modify';
    }

    saveFileInfo(data).then(res => {
      this.store.data.isNeedReloadList = true;
      this.update();
      dd.navigateBack()
    })
  }, 1000)
});