// nova-tourism/pages/my/my-order/my-refund/refund-good/index.js
let Parse = getApp().Parse;
const company = getApp().globalData.company
const uid = Parse.User.current()?.id
const dateF = require("../../../../../../utils/date")
const qiniuUploader = require("../../../../../../utils/qiniuUploader");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    order: null, //订单
    way: '退货退款', //退换方式
    wayList: [{
        name: '退货退款'
      },
      {
        name: '退款（无需退货）'
      },
      {
        name: '换货'
      },
      {
        name: '店内退换'
      },
    ], //可选退换方式
    cause: '不想要了', //原因
    causeList: [{
        name: '不想要了'
      },
      {
        name: '商品瑕疵'
      },
      {
        name: '少件漏发'
      },
      {
        name: '商家发错货'
      },
      {
        name: '其他原因'
      },
    ], //可选原因
    content: '', //描述
    tempFiles: [], //图片-本地
    refundImgs: [], //图片
    isShowWay: false, //选择退货方式弹框
    isShowCause: false, //选择原因弹框

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getToken()
    let {
      oid
    } = options
    console.log(options)
    this.setData({
      oid
    })
    this.getOrder()
  },
  /**上传图片 */
  getTemp() {
    let {
      tempFiles
    } = this.data
    let that = this
    wx.chooseMedia({
      count: 9,
      mediaType: 'image',
      success: (res) => {
        console.log(res)
        let tempPathList = res.tempFiles?.map(item => item.tempFilePath)
        that.setData({
          tempFiles: [...tempFiles, ...(tempPathList || [])]
        })
      }
    })
  },
  /**删除图片 */
  del(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      tempFiles
    } = this.data
    tempFiles.splice(index, 1)
    this.setData({
      tempFiles
    })
  },
  /** 获取token 上传图片所需*/
  async getToken() {
    let res = await Parse.Cloud.run('qiniu_uptoken', {
      company: company
    })
    this.setData({
      uptokenURL: res.uptoken,
      domain: res.domain,
      uploadURL: res.zoneUrl
    })
  },
  /**转换图片链接 */
  async upFileCall() {
    let {
      tempFiles
    } = this.data
    console.log(tempFiles)
    let that = this
    for (let i in tempFiles) {
      let item = tempFiles[i]
      await qiniuUploader.upload(
        item,
        async (res) => {
            let {
              refundImgs
            } = that.data
            console.log(res)
            refundImgs.push(res?.imageURL)
            that.setData({
              refundImgs
            })
          },
          (error) => {
            console.log("error: " + error);
          }, {
            region: "SCN",
            uploadURL: that.data.uploadURL,
            domain: that.data.domain,
            uptoken: that.data.uptokenURL,
          }
      );
    }
  },
  /**提交 */
  async submit() {
    let {
      content
    } = this.data
    if (!content) {
      wx.showToast({
        title: '请描述退款原因',
        icon: 'none'
      })
      return
    }
    wx.showLoading()
    let that = this
    await this.upFileCall()
    let interval = setInterval(async () => {
      if (that.data.refundImgs?.length == that.data.tempFiles?.length) {
        await that.saveOrder()
        clearInterval(interval)
      }
    }, 1000);
  },
  async saveOrder() {
    let {
      way,
      cause,
      content,
      refundImgs,
      orderParse
    } = this.data
    orderParse.set('status', '500')
    orderParse.set('content', `退换方式：${way}。原因：${cause}。描述：${content}`)
    orderParse.set('refundImgs', refundImgs || [])
    wx.hideLoading()
    try {
      await orderParse.save()
      await wx.showToast({
        title: '已提交退款申请',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 2,
        })
      }, 900);

    } catch (error) {
      wx.showToast({
        title: '出错了请检查后重试',
        icon: 'error'
      })
    }
  },



  /**获取订单 */
  async getOrder() {
    let {
      oid
    } = this.data
    let query = new Parse.Query('Order')
    query.include('targetObject')
    let d = await query.get(oid)
    let order = d?.toJSON()
    console.log(order)
    this.setData({
      order,
      orderParse: d
    })
  },
  closeWay() {
    this.setData({
      isShowWay: false
    });
  },
  openWay() {
    this.setData({
      isShowWay: true
    });
  },
  selectWay(event) {
    this.setData({
      way: event?.detail?.name || '退货退款'
    })
  },
  closeCause() {
    this.setData({
      isShowCause: false
    });
  },
  openCause() {
    this.setData({
      isShowCause: true
    });
  },
  selectCause(event) {
    this.setData({
      cause: event?.detail?.name || '不想要了'
    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})