const util = require('../../../utils/util.js');
const app = getApp();
Page({
  data: {
    reasonData: [],
    current: 1,
    imgPath: util.config.imgPath,
    datas: {},
    reason: '',
    showtext: false,
    mask: false,
    refundBack: '',
    refundpwd: '',
    orderid: '',
    status: '',
    groupId: '',
    reasonList: [],
    reasonIndex: 0,
    default: "请选择 >",
    // 控制sku
    showSku: false,
    refundShow: false,
    oid: "",
    orderInfo: {},
    codeShow: false,
    query: {
      orderid: '',
      otype: 0,
      presellStatus: 0
    },
    showGoodsRecom: false,
    index: 0,
    changeMeal_oid: "",
    type: 0,
    // 支付宝户号绑定内容
    AlipayNum: "",
    // 支付宝账号绑定内容
    accountNum: "",
    // 银行卡户名
    carName: "",
    // 银行名称
    bankName: "",
    // 银行卡号
    BankcardNo: "",
    // 银行开户行
    Bankofdeposit: "",
    password:''
  },
  isOK() {
    this.setData({
      codeShow: false
    })
  },
  // 二维码弹框
  showCode() {
    console.log("执行");
    this.setData({
      showSku: false,
      codeShow: true
    })
  },
  // 换场次中点击退款条例
  showFund() {
    this.setData({
      showSku: false,
      refundShow: true,
      type: this.data.orderInfo.refundRule
    })
  },
  changedeposit(e) {
    this.setData({
      Bankofdeposit: e.detail.value
    })
  },
  ChangeBankcardNo(e) {
    this.setData({
      BankcardNo: e.detail.value
    })
  },
  closeRefund() {
    this.setData({
      refundShow: false
    })
  },
  changeName(e) {
    this.setData({
      bankName: e.detail.value
    })
  },
  changebankName(e) {
    this.setData({
      carName: e.detail.value
    })
  },
  changeaccount(e) {
    this.setData({
      accountNum: e.detail.value
    })
  },
  changeAlipay(e) {
    // console.log(e.detail.value);
    this.setData({
      AlipayNum: e.detail.value
    })
  },
  showProp() {
    // if(this.data.orderInfo.refundRule==1){
    //   this.data.type=this.data.orderInfo.refundRule
    // }
    // console.log(this.data.orderInfo);
    console.log(this.data.orderInfo.refundRule);
    this.setData({
      refundShow: true,
      type: this.data.orderInfo.refundRule
      // type:3
    })
  },
  // 关闭弹框
  closeSku() {
    this.setData({
      showSku: false,
      changeMeal_oid: ''
    });
  },
  //  点击换场次
  confirmChange(e) {
    console.log(this.data.orderInfo);
    let that = this,
      data = {};
    data.newAlipayId = e.detail ? e.detail : '';
    data.oid = that.data.changeMeal_oid;
    console.log(data);
    util.ajax({
      func: "v2/order/getRefundPriceByOid",
      data: {
        oid: that.data.info.subOrders[that.data.index].oid,
      }
    }, function (res) {
      data.priceInfo = that.data.orderInfo
      data.password = that.data.password
      console.log(data);
      if (res.code == 0) {
        util.ajax({
          func: "v2/order/change/audit",
          data,
          method: 'POST',
          load: false
        }, function (res) {
          if (res.code == 0) {
            util.showTips('已发起申请，请耐心等待宝大大审核~');
            that.setData({
              showSku: false,
              changeMeal_oid: ''
            })
            that.getData1();
          } else {
            console.log(data);
            util.showTips(res.reason);
          }
        })
      } else if (res.code == -10) {
        util.showTips('不满足更换场次要求，请联系宝大大处理');
      } else {
        console.log(data);
        util.showTips(res.reason);
      }
    })
  },
  // 退款换场次
  changeMeals(e) {
    console.log(this.data.info.subOrders[this.data.index]);
    let status = this.data.info.subOrders[this.data.index].changeStatus,
      oid = this.data.info.subOrders[this.data.index].oid;
    if (status == 1) {
      util.showTips('已提交申请，请耐心等待宝大大审核~');
      return false;
    } else {
      let that = this
      this.OrderInfo(oid)
      this.setData({
        showSku: true,
        changeMeal_oid: oid
      });
      console.log(this.data.changeMeal_oid);
    }
  },
  //   获取换场次信息
  getData1(val) {
    let that = this;
    let data = {};
    if (!util.isEmpty(that.data.orderid)) {
      data.orderid = that.data.orderid;
    }
    if (!util.isEmpty((val || that.data.presellStatus))) {
      data.presellStatus = val || that.data.presellStatus
    }
    if (!util.isEmpty(that.data.otype)) {
      data.otype = that.data.otype
    }
    console.log(data);
    util.ajax({
      func: "v2/order/detail",
      data,
      load: false
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        let datas = res.data;
        datas.timeContrast = util.timeContrast(datas.stopBuy);
        if (!util.isEmpty(datas.mailAddress)) {
          var info = datas.mailAddress.split(" ");
          datas.mail = {};
          datas.mail.name = info[0] || "";
          datas.mail.postMobile = info[1] || "";
          datas.mail.province = info[2] || "";
          datas.mail.address = datas.mail.province.replace("/", "") + info[3];
        }
        if (datas.comment) {
          datas.comment.tag = datas.comment.content.match(/#([^#]+)#/g) ? datas.comment.content.match(/#([^#]+)#/g).join("") : '';
          datas.comment.content = datas.comment.content.replace(/#([^#]+)#/g, "").replace(/<br\/>/g, '\n');
          if (datas.comment.additionalComment.content) {
            datas.comment.additionalComment.content = datas.comment.additionalComment.content.replace(/<br\/>/g, '\n')
          }
        }
        if (datas.saleTime && datas.presellPaymentDeadline) {
          datas.startTime = util.formatDate(util.formatUnixtimestamp(datas.saleTime), 'MM月dd日 hh:mm', false);
          datas.endTime = util.formatDate(util.formatUnixtimestamp(datas.presellPaymentDeadline), 'MM月dd日 hh:mm', false);
        }
        let num = 0,
          length = (datas.groupinfo.discount && !util.isEmpty(datas.groupinfo.discount.users)) ? datas.groupinfo.discount.users.length : 0;
        if (length > 0) {
          datas.groupinfo.discount.users.forEach(el => {
            num = el.status == 4 ? num++ : num;
            if (el.status == 4) {
              num++;
            }
            that.setData({
              iconView: num == 0 ? false : true
            });
          });
        }
        that.setData({
          info: datas
        });
        // console.log(that.data.info.subOrders[that.data.index].changeStatus);
        that.getGoodsRecommend()
        if (datas.groupinfo.gstatus == 0 && datas.groupinfo.discount && datas.groupinfo.discount.status == 0 && datas.groupinfo.discount.deadline > 0) {
          that.data.info.groupinfo.discount.deadline = that.data.info.groupinfo.discount.deadline - new Date().getTime();
          that.updateTime();
        }
      } else
        util.showTips(res.reason);
    });
  },
  getGoodsRecommend() {
    let that = this;
    util.getGoodsRecommend(this.data.info.aid).then(res => {
      that.setData({
        showGoodsRecom: res
      })
    })
  },
  // 获取订单信息
  OrderInfo(oid) {
    console.log(this.data.oid);
    let that = this
    util.ajax({
      func: "v2/order/getRefundPriceByOid",
      data: {
        "oid": that.data.oid
      }
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        that.setData({
          orderInfo: res.data,
          changeMeal_oid: oid
        })
      } else if (res.code == -10) {
        util.showTips('不满足更换场次要求，请联系宝大大处理');
        that.setData({
          showSku: false,
          changeMeal_oid: oid
        });
      } else {
        util.showTips(res.reason)
      }
    })
  },
  onLoad(options) {
    console.log(options);
    this.setData({
      index: options.index,
      oid: options.oid,
      refundpwd: options.refundpwd,
      orderid: options.orderid,
      status: options.refundStatus,
      groupId: options.groupid || '',
      password:options.refundpwd
    });

    if (options.atype != "1") {
      this.OrderInfo()
    } else {
      this.setData({
        atype: options.atype
      })
    }
    let reasonData = [],
      current = 1;
    if (this.data.status == 15) {
      current = 4;
    }
    this.setData({
      current
    })
    this.getData();


  },
  onShow() {

    if (this.data.atype != "1") {
      this.OrderInfo()
      this.getData1()
    }

  },
  // 切换退款原因
  changeReason(e) {
    console.log(e.detail.value);
    console.log(this.data.reasonData[e.detail.value].type == 0);
    if (this.data.reasonData[e.detail.value].type == 0) {
      this.setData({
        showtext: true
      })
    } else {
      this.setData({
        showtext: false
      })
    }
    this.data.reasonIndex = e.detail.value
    this.setData({
      reasonIndex: this.data.reasonIndex,
      default: this.data.reasonList[this.data.reasonIndex]
    });
  },
  getData() {
    let that = this;
    let current = 0
    util.ajax({
      func: "v2/order/detail",
      data: {
        "orderid": that.data.orderid,
        "otype": 0,
        "password": that.data.refundpwd || "",
      }
    }, function (res) {
      if (res.code == 0) {
        let reasonData = [];
        if (res.data.atype == '1') { //电商
          reasonData = [{
              type: 5,
              txt: '不喜欢/不想要'
            },
            {
              type: 6,
              txt: '质量问题'
            },
            {
              type: 0,
              txt: '其他原因'
            }
          ];
        } else {
          if (that.data.status == 15) {
            reasonData = [{
              type: 4,
              txt: '候补退款'
            }], current = 4;
          } else {
            reasonData = [{
                type: 1,
                txt: '行程有变'
              },
              {
                type: 2,
                txt: '买多了/买错了'
              },
              {
                type: 3,
                txt: '孩子突发身体原因'
              },
              {
                type: 0,
                txt: '其他原因'
              }
            ];

          }
        }
        reasonData.forEach(item => {
          console.log(item);
          that.data.reasonList.push(item.txt)
        })
        if (reasonData.length == 1) {
          that.data.default = "候补退款"
        }
        that.setData({
          default: that.data.default,
          datas: res.data,
          reasonData,
          current: reasonData[0].type,
          reasonList: that.data.reasonList
        });
      }
    })
  },
  backBtn() {
    wx.redirectTo({
      url: '/pages/order/index/order?otype=2'
    })
  },
  confirm(e) {
    console.log(e);
    this.setData({
      reason: e.detail.value
    });
  },
  bindreason(e) {
    console.log(e);
    this.setData({
      current: e.currentTarget.dataset.type
    });
  },
  img() {
    this.data.datas.logo = '/images/noimg.png';
    this.setData({
      datas: this.data.datas
    });
  },
  refundRequest() {
    let that = this,
      reason = this.data.reason,
      current = this.data.current;
    console.log(current);
    let type = 0
    if (this.data.default == "行程有变") {
      type = 1
    } else if (this.data.default == "买多了/买错了") {
      type = 2
    } else if (this.data.default == "孩子突发身体原因") {
      type = 3
    } else if (this.data.default == "其他原因") {
      type = 0

    } else if (this.data.default == "候补退款") {
      type = 4
    } else if (this.data.default == "质量问题") {
      type = 6
    } else if (this.data.default == "不喜欢/不想要") {
      type = 5
    }
    if (this.data.default == "请选择 >" || type == -1) {
      util.showTips("请选择退款原因")
      return false
    }
    if (this.data.showtext == true && util.isEmpty(reason)) {
      util.showTips("请填写退款原因")
      return false
    }
    if (current == 0 && reason == '') {
      util.showTips('请输入退款原因。');
      return false;
    }
    if (this.data.dayBeforeStart <= 0) {
      util.showTips("活动已开始，无法提交退款申请")
      wx.navigateBack({
        delta: 1,
      })
      return
    }
    if (this.data.current == 1 && this.data.orderInfo.overdue == 1) {
      if (util.isEmpty(this.data.AlipayNum)) {
        util.showTips("支付宝户号不能为空")
        return
      }
      if (util.isEmpty(this.data.accountNum)) {
        util.showTips("支付宝账号不能为空")
        return
      }
    } else if (this.data.current == 2 && this.data.orderInfo.overdue == 1) {
      if (util.isEmpty(this.data.carName)) {
        util.showTips("卡户名不能为空")
        return
      }
      if (util.isEmpty(this.data.bankName)) {
        util.showTips("银行名称不能为空")
        return
      }
      if (util.isEmpty(this.data.BankcardNo)) {
        util.showTips("银行卡号不能为空")
        return
      }
      if (util.isEmpty(this.data.Bankofdeposit)) {
        util.showTips("开户行不能为空")
        return
      }
    }
    let desc = ""
    if (this.data.current == 1) {
      desc = "支付宝"
    } else if (this.data.current == 2) {
      desc = "银行卡"
    }
    console.log(that.data.orderInfo);
    util.ajax({
      func: "order/commit_refund",
      data: {
        "reasonType": type,
        "reason": reason,
        "orderid": that.data.orderid,
        "password": that.data.refundpwd || "",
        "type": '0',
        "priceInfo": that.data.orderInfo,

        "receiveAccount": that.data.orderInfo.overdue == 0 ? '' : (that.data.current == 1 ? "支付宝" + "    " + that.data.AlipayNum + "    " + that.data.accountNum : "银行卡" + "    " + that.data.carName + "    " + that.data.bankName + "    " + that.data.BankcardNo + "    " + that.data.Bankofdeposit)
      },
      method: "POST"
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        wx.setStorageSync('_REFUND_', 'REFUND');
        that.setData({
          refundBack: res.reason,
          mask: true
        })
      } else if (res.code == -10) {
        wx.showModal({
          title: "提示",
          content: res.reason,
          success(res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1,
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        });
      } else if (res.code == -11) {
        wx.showModal({
          title: "提示",
          content: res.reason,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              that.onLoad({
                index: that.data.index,
                oid: that.data.oid,
                refundpwd: that.data.refundpwd,
                orderid: that.data.orderid,
                status: that.data.refundStatus,
                groupId: that.data.groupid || ''
              })
              // that.onReady()
            }
          }
        });
      } else {
        wx.showModal({
          title: "提示",
          content: res.reason,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        });
      }
    });
  },
  onReady() {

  }
})