// pages/addPontract/index.js
import Message from 'tdesign-miniprogram/message/index';
import {
  request
} from "../../utils/request.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    test: {
      size: 'large',
      block: true
    },
    type: 0,
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    originFiles: [],
    tempFile: {},
    name: "",
    username: "",
    users: [],
    userVisible: false,
    item: {}
  },
  onLoad(e) {
    const item = JSON.parse(e.item)
    const type = item.type
    const l = item.fileIds[0].split("/");
    const pdfFileName = l[l.length - 1]
    this.setData({
      item,
      name: item.text,
      username: item.username,
      type,
      tempFile: type === 0 ? {
        name: pdfFileName,
        path: item.fileIds[0]
      } : {},
      originFiles: type === 1 ?
        item.fileIds.map(v => ({
          url: v
        })) : []
    })
  },
  onShow() {
    request("user/get").then(res => {
      this.setData({
        users: res.data.map(v => ({
          id: v._id,
          label: v.username,
          isAdmin: v.isAdmin,
          value: v.username
        }))
      })
    })
  },
  onUserPicker() {
    this.setData({
      userVisible: true
    })
  },
  onUserPickerCancel() {
    this.setData({
      userVisible: false
    })
  },
  onColumnChange(e) {
    console.log(e)
    this.setData({
      userVisible: false,
      username: e.detail.value[0],
    })
  },
  onChange(e) {
    this.setData({
      originFiles: [],
      tempFile: {},
      type: e.detail.value
    });
  },
  selectPdf() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ["pdf"],
      success: (res) => {
        this.setData({
          tempFile: res.tempFiles[0]
        })
      }
    })
  },
  openFile() {
    wx.cloud.downloadFile({
      fileID: this.data.tempFile.path,
      success: function (res) {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath,
          fileType: "pdf"
        })
      },
      fail: console.log
    })
  },
  handleSuccess(e) {
    const {
      files
    } = e.detail;
    this.setData({
      originFiles: files,
    });
  },
  handleRemove(e) {
    const {
      index
    } = e.detail;
    const {
      originFiles
    } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleDrop(e) {
    const {
      files
    } = e.detail;
    this.setData({
      originFiles: files,
    });
  },
  async createContract() {
    if (!this.validate()) {
      return
    }
    wx.showLoading({
      title: '',
    });

    if (this.data.type === 0) {
      try {
        const file = this.data.item.fileIds[0]
        if (this.data.tempFile.path !== this.data.item.fileIds[0]) {
          const res = await promiseUpload({
            cloudPath: `contract/${this.data.username}/${this.data.name}/${this.data.tempFile.name}`,
            filePath: this.data.tempFile.path,
          })
          file = res.fileID
        }
        request("contract/update", {
          id: this.data.item.id,
          username: this.data.username,
          name: this.data.name,
          type: this.data.type,
          files: [file]
        }).then(res => {
          const list = getCurrentPages()
          Message.success({
            context: list[list.length - 2],
            offset: [20, 32],
            duration: 2000,
            content: '编辑成功',
          });
          wx.navigateBack()
        }).finally(res => {
          wx.hideLoading()
        })
      } catch (err) {
        console.log(err)
        wx.hideLoading()
      }


    } else {
      try {

        const res = await Promise.all(this.data.originFiles.map(v => {
          if (v.url.startsWith("cloud")) {
            return Promise.resolve({
              fileID: v.url
            })
          }
          return promiseUpload({
            cloudPath: `contract/${this.data.username}/${this.data.name}/${v.name}`,
            filePath: v.url,
          })
        }))
        request("contract/update", {
          id: this.data.item.id,
          username: this.data.username,
          name: this.data.name,
          type: this.data.type,
          files: res.map(v => v.fileID)
        }).then(res => {
          const list = getCurrentPages()
          Message.success({
            context: list[list.length - 2],
            offset: [20, 32],
            duration: 2000,
            content: '编辑成功',
          });
          wx.navigateBack()
        }).finally(res => {
          wx.hideLoading()
        })
      } catch (err) {
        console.log(err)
        wx.hideLoading()
      }
    }

  },
  validate() {
    if (this.data.name === "") {
      wx.showToast({
        title: '合同名称不能为空',
        icon: "none"
      })
      return false
    } else {
      if (this.data.type === 0) {
        console.log(this.data.tempFile.path)
        if (!this.data.tempFile.path || this.data.tempFile.path === "") {
          wx.showToast({
            title: '请上传PDF文件',
            icon: "none"
          })
          return false
        }
      } else {
        if (this.data.originFiles.length === 0) {
          wx.showToast({
            title: '请上传图片',
            icon: "none"
          })
          return false
        }
      }
      return true
    }
  }
})

const promiseUpload = (config = {}) => {
  return new Promise((resolve, reject) => {
    wx.cloud.uploadFile({
      ...config,
      success: resolve,
      fail: reject
    })
  })
}