// 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
  },
  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.openDocument({
      filePath: this.data.tempFile.path,
      fileType: "pdf"
    })
  },
  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) {
      promiseUpload({
        cloudPath: `contract/${this.data.username}/${this.data.name}/${this.data.tempFile.name}`,
        filePath: this.data.tempFile.path,
      }).then(res => {
        request("contract/add", {
          username: this.data.username,
          name: this.data.name,
          type: this.data.type,
          files: [res.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(() => {
        wx.hideLoading()
      })
    } else {
      Promise.all(this.data.originFiles.map(v => {
        return promiseUpload({
          cloudPath: `contract/${this.data.username}/${this.data.name}/${v.name}`,
          filePath: v.url,
        })
      })).then(res => {
        console.log(res)
        request("contract/add", {
          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(() => {
        wx.hideLoading()
      })

    }

  },
  validate() {
    if (this.data.username === "") {
      wx.showToast({
        title: '请选择账号',
        icon: "none"
      })
      return false
    } else 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
    })
  })
}