// 必须传入price,show tradeNo 
// bind:payResult 返回支付状态
const CONFIG = require("../../config.js");
const Parse = getApp().Parse;
const company = getApp().globalData.company;
Component({
  behaviors: [],
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
    //支付价格 *必填
    price: {
      type: Number,
      value: 0,
    },
    //订单id Order表创建后id 
    orderId: {
      type: String,
    },
    //支付类型 
    orderType: {
      type: String,
      value: 'shopgoods'
    },
    //订单编号 *必填
    tradeNo: {
      type: String,
    },
    //显示公益金支付 Profile — bonus字段
    showBonus: {
      type: Boolean,
      value: false
    },
    //显示支付类型
    showType: {
      type: String,
      value: 'all'
    },
    profileId: {
      type: String
    }
  },
  data: {
    radio: "wxpay",
    isPay: false,
    balanceTitle:CONFIG.default.payBalanceTitle || '余额'
  },
  lifetimes: {
    created() {
    },
    attached() {},
    moved() {},
    detached() {},
  },
  pageLifetimes: {
    show: async function () {
      // 页面显示
    },
    hide: function () {
      // 页面被隐藏
      this.setData({
        show: false,
      });
    },
    resize: function (size) {
      // 页面尺寸变化
    },
  },
  methods: {
    onChange(event) {
      console.log(event)
      this.setData({
        radio: event.detail,
      });
      console.log(this.data.radio);
    },

    onClickHide() {
      this.setData({
        show: false
      });
      this.payResult("Cancel the payment", undefined);
    },

    /* 支付结果返回父组件 */
    payResult(state, no) {
      let {
        radio
      } = this.data
      this.triggerEvent("payResult", {
        params: state,
        no: no,
        type: radio
      });
    },

    pay() {
      if (this.data.isPay) {
        wx.showToast({
          title: '你已支付,请勿重复提交',
          icon: "none"
        })
        return
      }
      let payType = this.data.radio;
      switch (payType) {
        case "wxpay":
          console.log(this.properties.tradeNo)
          this.wxPay();
          break;
        case "balance":
          this.balance();
          break;
        case "bonus":
          this.bonusPay();
          break;
        case "offline":
          break;
      }
    },

    async wxPay() {
      let that = this;
      let Account = new Parse.Query("Account");
      Account.equalTo("user", Parse.User.current().id);
      Account.equalTo("company", company);
      let account = await Account.first();
      let AccountLog = Parse.Object.extend("AccountLog");
      let accountLog = new AccountLog();
      accountLog.set("assetType", "wxPay");
      accountLog.set("payType", "wxpay-wxapp");
      accountLog.set("assetCount", this.data.price);
      accountLog.set("desc", "微信支付");
      accountLog.set("orderType", this.data.orderType + "-wxpay");
      accountLog.set("orderNumber", this.properties.tradeNo);
      if (this.properties.orderId) accountLog.set("orderId", this.properties.orderId)
      accountLog.set("isVerified", false);
      accountLog.set("targetName", "system");
      if (account) {
        accountLog.set("fromAccount", account.toPointer());
      }
      accountLog.set("fromName", Parse.User.current().get("nickname"));
      accountLog.set("company", {
        __type: "Pointer",
        className: "Company",
        objectId: company,
      });
      let appId = getApp().globalData.appid;
      let openId = wx.getStorageSync("userInfo").openid;
      if(!openId && Parse.User.current().get("wxapp")){
        openId = Parse.User.current().get("wxapp")?.[appId]?.openid
      }
      let goodsTotalPrice = this.data.price;
      console.log(goodsTotalPrice)
      if(goodsTotalPrice == 0){
        this.updateLog(accountLog)
        return
      }
      wx.request({
        method: "POST",
        url: "https://server.fmode.cn/api/wxpay/neworder",
        data: {
          appid: appId,
          openid: openId,
          out_trade_no: that.properties.tradeNo,
          total_fee: goodsTotalPrice,
          company: company
        },
        success: (payres) => {
          console.log("Pay Params");
          console.log(payres);
          let payinfo = payres.data;
          wx.requestPayment({
            appId: appId,
            timeStamp: payinfo.timeStamp,
            nonceStr: payinfo.nonceStr,
            package: payinfo.package,
            signType: "MD5",
            paySign: payinfo.paySign,
            async success(data) {
              that.updateLog(accountLog)
              wx.showToast({
                title: "支付成功",
                icon: "success",
                duration: 1500,
              });
              that.setData({
                show: false
              })
            },
            fail(err) {
              that.payResult(err, that.properties.tradeNo);
              wx.showToast({
                title: "支付失败",
                icon: "error",
                duration: 1500,
              });
            },
            complete:(data) => {
              console.log(111,data)
            }
          });
        },
        fail: (err) => {
          wx.showToast({
            title: "支付失败",
            icon: "error",
            duration: 1500,
          });
          return false;
        },
        
      });
    },
    //支付成功更新log
    async updateLog(accountLog){
      this.payResult("ok", this.properties.tradeNo);
      accountLog.set("isVerified", true);
      await accountLog.save()
    },

    async sendOrder(tradeNo) {
      let that = this;
      let DramaOrderLog = Parse.Object.extend("UserAgentOrder");
      let current = Parse.User.current();
      let dramaOrderLog = new DramaOrderLog();
      dramaOrderLog.set("user", {
        __type: "Pointer",
        className: "_User",
        objectId: current.id,
      });
      dramaOrderLog.set("orderId", tradeNo);
      dramaOrderLog.set("company", {
        __type: "Pointer",
        className: "Company",
        objectId: getApp().globalData.company,
      });
      await dramaOrderLog.save();
    },
    async balance() {
      let { balanceTitle } = this.data
      let _this = this;
      try {
        let price = this.data.price
        let Account = new Parse.Query("Account");
        Account.equalTo("user", Parse.User.current().id);
        Account.equalTo("company", company);
        let account = await Account.first();
        console.log(account);
        if (!account.get("balance") || price > account.get("balance")) {
          wx.showToast({
            title: `${balanceTitle == '积分' ? '积分不足' : '余额不足,请充值'}`,
            icon: "none"
          })
          return
        }
        let AccountLog = Parse.Object.extend("AccountLog");
        let accountLog = new AccountLog();
        accountLog.set("assetType", "balance");
        accountLog.set("payType", "balance");
        accountLog.set("assetCount", this.data.price);
        accountLog.set("desc", `${balanceTitle}支付`);
        accountLog.set("orderType", this.data.orderType + "-balance");
        accountLog.set("orderNumber", this.properties.tradeNo);
        if (this.properties.orderId) accountLog.set("orderId", this.properties.orderId)
        accountLog.set("isVerified", false);
        accountLog.set("targetName", "system");
        if (account) {
          accountLog.set("fromAccount", account.toPointer());
        }
        accountLog.set("fromName", Parse.User.current().get("nickname"));
        accountLog.set("company", {
          __type: "Pointer",
          className: "Company",
          objectId: company,
        });
        accountLog.save()
          .then((res) => {
            res.set("isVerified", true);
            res.save().then((result) => {
              console.log(result)
              wx.showToast({
                title: "支付成功",
                icon: "success",
                duration: 1500,
              });
              _this.payResult("ok", this.properties.tradeNo);
            })
          })
      } catch (error) {
        console.log(error)
        wx.showToast({
          title: "支付失败",
          icon: "error",
          duration: 1500,
        });
        _this.payResult(error);
      }
      this.setData({
        isPay: true
      })
    },

    //公益金支付
    async bonusPay() {
      let _this = this;
      let {
        profileId
      } = this.data
      try {
        let data = await this.customSQL()
        console.log(data);
        if (data.code == 200) {
          let Account = new Parse.Query("Account");
          Account.equalTo("user", Parse.User.current().id);
          Account.equalTo("company", company);
          let account = await Account.first();
          let AccountLog = Parse.Object.extend("AccountLog");
          let accountLog = new AccountLog();
          accountLog.set("assetType", "bonus");
          accountLog.set("payType", "bonus");
          accountLog.set("assetCount", this.data.price);
          accountLog.set("desc", "公益金支付");
          accountLog.set("orderType", this.data.orderType + "-bonus");
          accountLog.set("orderNumber", this.properties.tradeNo);
          if (this.properties.orderId) accountLog.set("orderId", this.properties.orderId)
          accountLog.set("isVerified", true);
          accountLog.set("targetName", "system");
          if (!profileId && account) {
            accountLog.set("fromAccount", account.toPointer());
          }
          accountLog.set("fromName", Parse.User.current().get("nickname"));
          accountLog.set("company", {
            __type: "Pointer",
            className: "Company",
            objectId: company,
          });
          await accountLog.save()
          wx.showToast({
            title: data.msg,
            icon: 'none',
            image: '',
            duration: 1500,
            mask: false,
          });
          _this.payResult("ok", this.properties.tradeNo);
        }else{
          wx.showToast({
            title: data.msg,
            icon: 'none',
            image: '',
            duration: 1500,
            mask: false,
          });
        }
      } catch (err) {
        console.log(err)
        wx.showToast({
          title: "支付失败",
          icon: "error",
          duration: 1500,
        });
        _this.payResult(error);
      }
    },

    async customSQL() {
      let price = this.data.price
      let {
        profileId
      } = this.data
      let promise = await new Promise((resolve, rej) => {
        wx.request({
          url: "https://server.fmode.cn/api/food/bonus",
          data: {
            pid: profileId,
            price: price,
            company: company
          },
          method: "POST",
          success(data) {
            console.log(data);
            resolve(data.data)
          },
          fail(err) {
            rej(err);
          },
        });
      });
      return promise;
    },
  },

  observers: {
    show: function (show) {
      console.log(show)
    }
  }
});