fix
无故事王国
2024-03-04 54c6ef0be42d9f2e49a344fd69f231cb6df43797
WanPai/Root/Course/VC/CourseDetailApplyVC.swift
@@ -1,9 +1,9 @@
   //
   //  CourseDetailApplyVC.swift
   //  WanPai
   //
   //  Created by 杨锴 on 2023/6/9.
   //
//
//  CourseDetailApplyVC.swift
//  WanPai
//
//  Created by 杨锴 on 2023/6/9.
//
import UIKit
import JQTools
@@ -11,557 +11,550 @@
class CourseDetailApplyVC: BaseVC {
   @IBOutlet weak var collectionView: UICollectionView!
   @IBOutlet weak var cons_collectHei: NSLayoutConstraint!
   @IBOutlet weak var btn_addStudent: QMUIButton!
   @IBOutlet weak var tableView: UITableView!
   @IBOutlet weak var cons_collHei: NSLayoutConstraint!
   @IBOutlet weak var cons_tableHei: NSLayoutConstraint!
   @IBOutlet weak var btn_coupon: TapBtn!
            @IBOutlet weak var collectionView: UICollectionView!
            @IBOutlet weak var cons_collectHei: NSLayoutConstraint!
            @IBOutlet weak var btn_addStudent: QMUIButton!
            @IBOutlet weak var tableView: UITableView!
            @IBOutlet weak var cons_collHei: NSLayoutConstraint!
            @IBOutlet weak var cons_tableHei: NSLayoutConstraint!
            @IBOutlet weak var btn_coupon: TapBtn!
   @IBOutlet weak var view_banner: CommonBannerView!
   @IBOutlet weak var label_title: UILabel!
   @IBOutlet weak var label_listenWeek: UILabel!
   @IBOutlet weak var label_listenTime: UILabel!
   @IBOutlet weak var label_store: UILabel!
   @IBOutlet weak var label_address: UILabel!
            @IBOutlet weak var view_banner: CommonBannerView!
            @IBOutlet weak var label_title: UILabel!
            @IBOutlet weak var label_listenWeek: UILabel!
            @IBOutlet weak var label_listenTime: UILabel!
            @IBOutlet weak var label_store: UILabel!
            @IBOutlet weak var label_address: UILabel!
   @IBOutlet weak var label_price: UILabel!
   @IBOutlet weak var label_originPrice: UILabel!
   @IBOutlet weak var label_vipPrice: UILabel!
   @IBOutlet weak var label_coin: UILabel!
//   @IBOutlet weak var btn_hasCoupon: TapBtn!
   @IBOutlet weak var btn_couponInfo: UIButton!
   @IBOutlet weak var label_courseType: UILabel!
            @IBOutlet weak var label_price: UILabel!
            @IBOutlet weak var label_originPrice: UILabel!
            @IBOutlet weak var label_vipPrice: UILabel!
            @IBOutlet weak var label_coin: UILabel!
            //   @IBOutlet weak var btn_hasCoupon: TapBtn!
            @IBOutlet weak var btn_couponInfo: UIButton!
            @IBOutlet weak var label_courseType: UILabel!
   @IBOutlet weak var view_vaildTime: UIView!
   @IBOutlet weak var label_vaild: UILabel!
   @IBOutlet weak var studentTableView: UITableView!
   @IBOutlet weak var view_packageList: UIView!
   @IBOutlet weak var btn_handleBtn: UIButton!
   @IBOutlet weak var view_teach: UIView!
   @IBOutlet weak var label_couponInfo: UILabel!
   private var detailModel:CourseDetailModel?
   private var selectClassIndex:Int = 0
   private var CellW:Double!
   private var CellH:Double!
   private var studentModels = [CourseDetailStudentModel]()
   private var couponModels = [CouponInfoModel]()
   private var selectCouponModel:CouponInfoModel?
   private var classHours:Int?
//   private var signUpCourseModel:SignUpCourseItemModel?
   private var signUpModel:SignUpCourseItemDetailModel?
            @IBOutlet weak var view_vaildTime: UIView!
            @IBOutlet weak var label_vaild: UILabel!
            @IBOutlet weak var studentTableView: UITableView!
            @IBOutlet weak var view_packageList: UIView!
            @IBOutlet weak var btn_handleBtn: UIButton!
            @IBOutlet weak var view_teach: UIView!
            @IBOutlet weak var label_couponInfo: UILabel!
   override func viewDidLoad() {
      super.viewDidLoad()
      title = "运动营详情"
            private var detailModel:CourseDetailModel?
            private var selectClassIndex:Int = 0
            private var CellW:Double!
            private var CellH:Double!
            private var studentModels = [CourseDetailStudentModel]()
            private var couponModels = [CouponInfoModel]()
            private var selectCouponModel:CouponInfoModel?
            private var classHours:Int?
            //   private var signUpCourseModel:SignUpCourseItemModel?
            private var signUpModel:SignUpCourseItemDetailModel?
      if let m = detailModel{
         label_title.text = m.name
         label_listenWeek.text = "每" + m.weeks.joined(separator: "、")
         label_listenTime.text = m.times.joined(separator: "|")
         label_store.text = m.storeName
         label_address.text = m.storeAddress
         label_vaild.text = m.time
         label_courseType.text = m.type.strTitle
            override func viewDidLoad() {
                        super.viewDidLoad()
                        title = "运动营详情"
         if classHours != nil{
            let temp = detailModel?.list.filter({$0.classHours == classHours!}) ?? []
            detailModel?.list = temp
         }
                        if let m = detailModel{
                                    label_title.text = m.name
                                    label_listenWeek.text = "每" + m.weeks.joined(separator: "、")
                                    label_listenTime.text = m.times.joined(separator: "|")
                                    label_store.text = m.storeName
                                    label_address.text = m.storeAddress
                                    label_vaild.text = m.time
                                    label_courseType.text = m.type.strTitle
//         //默认选择传递过来的课时数
//         for (index,clas) in m.list.enumerated(){
//            if clas.classHours == classHours{
//               selectClassIndex = index;break
//            }
//         }
                                    if classHours != nil{
                                                let temp = detailModel?.list.filter({$0.classHours == classHours!}) ?? []
                                                detailModel?.list = temp
                                    }
         switch m.type {
            case .vocation:
               label_vaild.text = m.time
               view_vaildTime.isHidden = false
               view_packageList.isHidden = true
            case .experience:
               label_vaild.text = "购买当天有效"
               view_vaildTime.isHidden = false
               view_packageList.isHidden = true
            default:
               view_vaildTime.isHidden = true
         }
                                    switch m.type {
                                                case .vocation:
                                                            label_vaild.text = m.time
                                                            view_vaildTime.isHidden = false
                                                            view_packageList.isHidden = true
                                                case .experience:
                                                            label_vaild.text = "购买当天有效"
                                                            view_vaildTime.isHidden = false
                                                            view_packageList.isHidden = true
                                                default:
                                                            view_vaildTime.isHidden = true
                                    }
         if m.student?.id != 0{
            studentModels.append(m.student!)
         }
                                    if m.student?.id != 0{
                                                studentModels.append(m.student!)
                                    }
         cons_collHei.constant = ceil(Double(m.list.count) / 3.0) * CellH + floor(Double(m.list.count) / 3.0) * 21.0
         collectionView.reloadData()
                                    cons_collHei.constant = ceil(Double(m.list.count) / 3.0) * CellH + floor(Double(m.list.count) / 3.0) * 21.0
                                    collectionView.reloadData()
         cons_tableHei.constant = CGFloat(studentModels.count * 87)
         tableView.reloadData()
                                    cons_tableHei.constant = CGFloat(studentModels.count * 87)
                                    tableView.reloadData()
         let imgs = m.detailDrawing.components(separatedBy: ",")
         var items = [CommonBannerModel]()
         for (index,img) in imgs.enumerated(){
            items.append(CommonBannerModel(index: index,resource: img,mediaType: .imageUrl))
         }
         view_banner.setItems(items: items)
      }
      if let m = signUpModel{
         classHours = m.chooseHours
         detailModel?.list = m.list.filter({$0.classHours == classHours})
         if m.payStatus == .unPayment{
            btn_handleBtn.setTitle("待支付", for: .normal)
            btn_addStudent.isHidden = true
            btn_coupon.isHidden = true
            studentModels.removeAll()
            Services.queryStudentList().subscribe(onNext: {[weak self] data in
               guard let weakSelf = self else { return }
               if let students = data.data{
                  for stu in students{
                     if m.stuIds.contains(where: {$0 == stu.id}){
                        weakSelf.studentModels.append(stu)
                        weakSelf.cons_tableHei.constant = CGFloat(weakSelf.studentModels.count * 87)
                        weakSelf.tableView.reloadData()
                     }
                  }
               }
            }).disposed(by: disposeBag)
         }
         if m.payStatus == .paymented{
            btn_handleBtn.setTitle("续课", for: .normal)
            btn_addStudent.isHidden = true
         }
      }
      queryCouponInfo {[weak self] () in
         guard let weakSelf = self else { return }
         self?.changePrice(weakSelf.selectClassIndex)
      }
   }
   override func setUI() {
      btn_coupon.isHidden = true
      CellW = (JQ_ScreenW - 155) / 3.0
      CellH = CellW * 0.439
      cons_tableHei.constant = 76
      collectionView.delegate = self
      collectionView.dataSource = self
      collectionView.register(UINib(nibName: "Common_1_CCell", bundle: nil), forCellWithReuseIdentifier: "_Common_1_CCell")
      studentTableView.dataSource = self
      studentTableView.separatorStyle = .none
      studentTableView.register(UINib(nibName: "StudentInfoTCell", bundle: nil), forCellReuseIdentifier: "_StudentInfoTCell")
      btn_addStudent.imagePosition = .right
      btn_addStudent.spacingBetweenImageAndTitle = 3
   }
   init(detailModel:CourseDetailModel,signUpModel:SignUpCourseItemDetailModel? = nil,classHours:Int? = nil) {
      super.init(nibName: nil, bundle: nil)
      self.detailModel = detailModel
      self.signUpModel = signUpModel
      self.classHours = classHours
   }
   required init?(coder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
   }
   override func setRx() {
      NotificationCenter.default.rx.notification(StudentUpdate_Nofi).take(until: self.rx.deallocated).subscribe {[weak self] noti in
         guard let weakSelf = self else { return }
            //重新唤起添加学生
         weakSelf.studentAction(weakSelf.btn_addStudent)
      }.disposed(by: disposeBag)
      NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] noti in
         self?.selectCouponModel = nil
         self?.btn_couponInfo.setTitle("去选择", for: .normal)
         self?.queryCouponInfo {[weak self] () in
            guard let weakSelf = self else { return }
            weakSelf.changePrice(weakSelf.selectClassIndex)
         }
      }).disposed(by: disposeBag)
   }
   @IBAction func couponAction(_ sender: TapBtn) {
      CouponChooseView.show(couponModels,defaultModel: selectCouponModel) {[weak self] m in
         guard let weakSelf = self else { return }
         weakSelf.selectCouponModel = m
         guard m != nil else {
            weakSelf.btn_couponInfo.setTitle("去选择", for: .normal);return
         }
         weakSelf.btn_couponInfo.setTitle("-\(m!.favorable.currency())", for: .normal)
         weakSelf.changePrice(weakSelf.selectClassIndex)
      }
   }
   @IBAction func studentAction(_ sender: QMUIButton) {
      StudentChooseView.show(itemType: .course, defaultStu: studentModels) { [weak self] studs in
         guard let weakSelf = self else { return }
         weakSelf.studentModels = studs as! [CourseDetailStudentModel]
         weakSelf.tableView.reloadData()
         weakSelf.cons_tableHei.constant = CGFloat((weakSelf.studentModels.count) * 87)
         weakSelf.changePrice(weakSelf.selectClassIndex)
      } needAddClouse: { [weak self] () in
         let vc = AddStudentVC(type: .course)
         self?.push(vc: vc)
      }
   }
   @IBAction func paymentAction(_ sender: UIButton) {
      guard detailModel != nil else {return}
      guard studentModels.count != 0 else {alertError(msg: "请选择运动营成员");return}
      StoresInfoView.show(detailModel!) { [weak self] status in
         guard let weakSelf = self else { return }
         if status{
            if var model = weakSelf.detailModel?.list[weakSelf.selectClassIndex]{
               //续课时价格
               if let list = weakSelf.signUpModel?.list{
                  model = list[weakSelf.selectClassIndex]
               }
               var price:Double = 0
                  //是否是会员
               if weakSelf.detailModel?.isVip == 1 && model.vipPrice != 0{
                  price = model.vipPrice
               }else{
                  price = model.paymentPrice
               }
               //计算人数总价
               price = price * Double(weakSelf.studentModels.count)
               //减去优惠
               var discountPrice = price - (weakSelf.selectCouponModel?.favorable ?? 0)
               var coin = model.playPaiCoin * weakSelf.studentModels.count
               //待支付订单 ,取最终订单金额
               if weakSelf.signUpModel?.payStatus == .unPayment{
                  discountPrice = weakSelf.signUpModel?.payPrice ?? 0
                  coin = weakSelf.signUpModel?.coinPrice ?? 0
               }
               PaymentView.show(enumType: .course, money: (ali:discountPrice,wx:discountPrice,coin:coin,course:nil,integral:nil)) { [weak self] payType in
                  guard let weakSelf = self else { return }
                  var resultPayPrice:Double = 0
                  switch payType {
                     case .aliPay,.wechat:
                        resultPayPrice = price
                        //待支付订单单独处理
                        if weakSelf.signUpModel?.payStatus == .unPayment{
                           resultPayPrice = weakSelf.signUpModel?.payPrice ?? 0
                                    let imgs = m.detailDrawing.components(separatedBy: ",")
                                    var items = [CommonBannerModel]()
                                    for (index,img) in imgs.enumerated(){
                                                items.append(CommonBannerModel(index: index,resource: img,mediaType: .imageUrl))
                                    }
                                    view_banner.setItems(items: items)
                        }
                     case .coin:
                        resultPayPrice = Double(coin)
                     default:break
                  }
                        if let m = signUpModel{
                                    classHours = m.chooseHours
                                    detailModel?.list = m.list.filter({$0.classHours == classHours})
                  Services.courcePayment(conponId: weakSelf.selectCouponModel?.id, courseConfigId: model.id, id: weakSelf.detailModel!.id, price: resultPayPrice, payType: payType, stuId: weakSelf.studentModels.map({$0.id}),orderId: weakSelf.signUpModel?.coursePayId).subscribe(onNext: { data in
                     if data.code == 200{
                        switch payType {
                           case .aliPay:
                              YYPaymentManager.shared.sendPaymentRequest(YYAlipayRequest(orderString: data.data!.orderString)) { [weak self] result in
                                 switch result {
                                    case .success:
                                       let vc = PaymentResultVC(result: .success, objType: .courseApply,handleVC: self,courseConfigId: model.id)
                                       vc.isExtend = self?.signUpModel?.payStatus == .paymented
                                       self?.push(vc: vc)
                                    case .cancel:
                                       alert(msg: "已取消")
                                    case .failure(_):
                                       let vc = PaymentResultVC(result: .fail("支付失败",0), objType: .courseApply)
                                       self?.push(vc: vc)
                                 }
                              }
                           case .wechat:
                              self?.navigationController?.popViewController(animated: false)
                              break
                           case .coin:
                              let vc = PaymentResultVC(result: .success, objType: .courseApply,handleVC: self,courseConfigId: model.id)
                              vc.isExtend = self?.signUpModel?.payStatus == .paymented
                              self?.push(vc: vc)
                           default:break
                                    if m.payStatus == .unPayment{
                                                btn_handleBtn.setTitle("待支付", for: .normal)
                                                btn_addStudent.isHidden = true
                                                btn_coupon.isHidden = true
                                                studentModels.removeAll()
                                                Services.queryStudentList().subscribe(onNext: {[weak self] data in
                                                            guard let weakSelf = self else { return }
                                                            if let students = data.data{
                                                                        for stu in students{
                                                                                    if m.stuIds.contains(where: {$0 == stu.id}){
                                                                                                weakSelf.studentModels.append(stu)
                                                                                                weakSelf.cons_tableHei.constant = CGFloat(weakSelf.studentModels.count * 87)
                                                                                                weakSelf.tableView.reloadData()
                                                                                    }
                                                                        }
                                                            }
                                                }).disposed(by: disposeBag)
                                    }
                                    if m.payStatus == .paymented{
                                                btn_handleBtn.setTitle("续课", for: .normal)
                                                btn_addStudent.isHidden = true
                                    }
                        }
                     }else{
                        alertError(msg: data.msg)
                     }
                  },onError: { error in
                     if let er = error as? NetworkRequest.NetRequestError{
                        switch er {
                           case .Other(let code,let string):
                              let vc = PaymentResultVC(result: .fail(string,code), objType: .courseApply,handleVC: nil)
                              self?.push(vc: vc)
                           default:
                              let vc = PaymentResultVC(result: .fail("支付失败",0), objType: .courseApply,handleVC: nil)
                              self?.push(vc: vc)
                        queryCouponInfo {[weak self] () in
                                    guard let weakSelf = self else { return }
                                    self?.changePrice(weakSelf.selectClassIndex)
                        }
                     }
                  }).disposed(by: weakSelf.disposeBag)
               }
            }
         }else{
            self?.navigationController?.popToRootViewController(animated: true)
            NotificationCenter.default.post(name: ChooseHomeStore_Noti, object: nil)
         }
      }
   }
      //计算价格
   private func changePrice(_ index:Int){
      //待支付订单,终止后续
      if signUpModel?.payStatus == .unPayment{
         label_price.isHidden = true
         label_originPrice.isHidden = signUpModel!.payPrice == signUpModel!.orinPrice
         label_vipPrice.isHidden = true
         label_coin.isHidden = true
         let originPrice = signUpModel!.orinPrice - signUpModel!.payPrice
         label_originPrice.attributedText = AttributedStringbuilder.build().add(string: originPrice.currency(), withFont: UIFont.systemFont(ofSize: 16, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F").withAlphaComponent(0.58)).delLine(color: UIColor(hexStr: "#3F3F3F").withAlphaComponent(0.58)).mutableAttributedString
         if signUpModel?.coinPrice != 0{
            label_coin.isHidden = false
            label_coin.attributedText = AttributedStringbuilder.build()
               .add(string: "玩湃币:", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F"))
               .add(string: "\(signUpModel!.coinPrice)币", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#F21313")).mutableAttributedString
         }
         if signUpModel?.payPrice != 0{
            label_price.isHidden = false
            label_price.text = (signUpModel!.payPrice).currency()
         }
         return
      }
      if let subM = detailModel?.list[index]{
         var studentCount:Int = 0
         if studentModels.count == 0{
            studentCount = 1
         }else{
            studentCount = studentModels.count
         }
         switch subM.payType {
            case .coin:
               label_price.text = ""
               label_price.isHidden = true
               label_originPrice.isHidden = true
               label_vipPrice.isHidden = true
               label_coin.isHidden = false
                  //纯玩湃币没有优惠券项
               btn_coupon.isHidden = true
               label_coin.isHidden = false
                  //玩湃币
               label_coin.attributedText = AttributedStringbuilder.build()
                  .add(string: "玩湃币:", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F"))
                  .add(string: "\(subM.playPaiCoin * studentCount)币", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#F21313")).mutableAttributedString
            case .cash:
               fallthrough
            case .cashCoin:
               if subM.originalPrice == 0 || subM.originalPrice == subM.paymentPrice{
                  label_originPrice.isHidden = true
               }else{
                  label_originPrice.isHidden = false
               }
                  //               label_originPrice.isHidden = (subM.paymentPrice == subM.originalPrice && subM.paymentPrice != 0 && subM.originalPrice != 0)
               label_coin.isHidden = subM.payType == .cash
                  //玩湃币
               label_coin.attributedText = AttributedStringbuilder.build()
                  .add(string: "玩湃币:", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F"))
                  .add(string: "\(subM.playPaiCoin * studentCount)币", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#F21313")).mutableAttributedString
                  //原价
               let attribute = AttributedStringbuilder.build().add(string: (subM.originalPrice * Double(studentCount)).currency(), withFont: UIFont.systemFont(ofSize: 16, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F").withAlphaComponent(0.58)).delLine(color: UIColor(hexStr: "#3F3F3F").withAlphaComponent(0.58))
               label_originPrice.attributedText = attribute.mutableAttributedString
               if UserInfoModel.get()?.isVip == 1{
                  if subM.payType != .coin{
                        //会员
                     label_vipPrice.isHidden = true
                     if subM.paymentPrice < subM.vipPrice && subM.paymentPrice != 0{
                        label_price.text = (subM.paymentPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                     }else if subM.vipPrice < subM.paymentPrice && subM.vipPrice != 0{
                        label_price.text = (subM.vipPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                     }else if subM.vipPrice != 0 &&  subM.paymentPrice != 0{
                        let price = min(subM.vipPrice, subM.paymentPrice)
                        label_price.text = (price *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                     }else{
                        label_price.text = (subM.paymentPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                     }
                  }
               }else{
                  if subM.payType != .coin{
                        //非会员
                     label_vipPrice.isHidden = subM.vipPrice == 0 || subM.vipPrice == subM.paymentPrice
                     let vipAttribute = AttributedStringbuilder.build()
                        .add(string: "会员价:", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F"))
                        .add(string: (subM.vipPrice *  Double(studentCount)).currency(), withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#F21313"))
                     label_vipPrice.attributedText = vipAttribute.mutableAttributedString
                     if subM.originalPrice != 0 && subM.paymentPrice == 0{
                        label_price.text = (subM.originalPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                     }else if subM.originalPrice == 0 && subM.paymentPrice != 0{
                        label_price.text = (subM.paymentPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                     }else if subM.originalPrice != 0 && subM.paymentPrice != 0{
                        var money = min(subM.originalPrice,subM.paymentPrice)
                        money = money - (selectCouponModel?.favorable ?? 0)
                        label_price.text = (money *  Double(studentCount)).currency()
                     }else{
                        label_price.text = (subM.originalPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                     }
                  }
               }
         }
         if detailModel?.type == .experience{
            if subM.paymentPrice != 0{
               label_price.text = subM.paymentPrice.currency()
               label_price.isHidden = false
            }
            view_teach.isHidden = true
            label_originPrice.isHidden = true
            label_vipPrice.isHidden = true
         }
            override func setUI() {
            //         if label_originPrice.isHidden && label_vipPrice.isHidden && label_coin.isHidden{
            //            label_coin.alpha = 0
            //         }
      }
   }
                        btn_coupon.isHidden = true
                        CellW = (JQ_ScreenW - 155) / 3.0
                        CellH = CellW * 0.439
      //查询优惠券
   private func queryCouponInfo(complete:(()->Void)? = nil){
      if let subM = detailModel?.list[selectClassIndex]{
                        cons_tableHei.constant = 76
         var price:Double?
         switch subM.payType{
            case .cash,.cashCoin:
               price = subM.originalPrice == 0 ? subM.vipPrice : subM.originalPrice
            case .coin:
               price = Double(subM.playPaiCoin)
         }
                        collectionView.delegate = self
                        collectionView.dataSource = self
                        collectionView.register(UINib(nibName: "Common_1_CCell", bundle: nil), forCellWithReuseIdentifier: "_Common_1_CCell")
         guard price != nil else {
            LogError("会员优惠价格出现问题:nil");return
         }
                        studentTableView.dataSource = self
                        studentTableView.separatorStyle = .none
                        studentTableView.register(UINib(nibName: "StudentInfoTCell", bundle: nil), forCellReuseIdentifier: "_StudentInfoTCell")
         Services.queryAvaiableCopons(id: detailModel!.id, price: price!).subscribe(onNext: { [weak self] data in
            guard let weakSelf = self else { return }
            self?.btn_coupon.isHidden = (data.data?.count ?? 0) == 0 || weakSelf.signUpModel?.payStatus == .unPayment
            self?.couponModels = data.data ?? []
            self?.label_couponInfo.isHidden = (data.data?.count ?? 0) == 0
            self?.label_couponInfo.text = String(format: "(%ld张可用)",data.data?.count ?? 0)
               //重新获取优惠券,在切换套餐时触发
            if let selectCoupon = self?.selectCouponModel{
               if !weakSelf.couponModels.contains(where: {$0.id == selectCoupon.id}){
                  weakSelf.selectCouponModel = nil
                  weakSelf.btn_couponInfo.setTitle("去选择", for: .normal)
               }
                        btn_addStudent.imagePosition = .right
                        btn_addStudent.spacingBetweenImageAndTitle = 3
            }
            complete?()
         }).disposed(by: disposeBag)
      }
   }
   override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      let w = String.jq_getWidth(text: detailModel?.type.strTitle ?? "", height: 25, font: 14) + 16
      label_courseType.jq_addCorners(corner: [.topLeft,.bottomLeft], radius: 4, width: w, height: 25)
   }
            init(detailModel:CourseDetailModel,signUpModel:SignUpCourseItemDetailModel? = nil,classHours:Int? = nil) {
                        super.init(nibName: nil, bundle: nil)
                        self.detailModel = detailModel
                        self.signUpModel = signUpModel
                        self.classHours = classHours
            }
            required init?(coder: NSCoder) {
                        fatalError("init(coder:) has not been implemented")
            }
            override func setRx() {
                        NotificationCenter.default.rx.notification(StudentUpdate_Nofi).take(until: self.rx.deallocated).subscribe {[weak self] noti in
                                    guard let weakSelf = self else { return }
                                    //重新唤起添加学生
                                    weakSelf.studentAction(weakSelf.btn_addStudent)
                        }.disposed(by: disposeBag)
                        NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] noti in
                                    self?.selectCouponModel = nil
                                    self?.btn_couponInfo.setTitle("去选择", for: .normal)
                                    self?.queryCouponInfo {[weak self] () in
                                                guard let weakSelf = self else { return }
                                                weakSelf.changePrice(weakSelf.selectClassIndex)
                                    }
                        }).disposed(by: disposeBag)
            }
            @IBAction func couponAction(_ sender: TapBtn) {
                        CouponChooseView.show(couponModels,defaultModel: selectCouponModel) {[weak self] m in
                                    guard let weakSelf = self else { return }
                                    weakSelf.selectCouponModel = m
                                    guard m != nil else {
                                                weakSelf.btn_couponInfo.setTitle("去选择", for: .normal);return
                                    }
                                    weakSelf.btn_couponInfo.setTitle("-\(m!.favorable.currency())", for: .normal)
                                    weakSelf.changePrice(weakSelf.selectClassIndex)
                        }
            }
            @IBAction func studentAction(_ sender: QMUIButton) {
                        StudentChooseView.show(itemType: .course, defaultStu: studentModels) { [weak self] studs in
                                    guard let weakSelf = self else { return }
                                    weakSelf.studentModels = studs as! [CourseDetailStudentModel]
                                    weakSelf.tableView.reloadData()
                                    weakSelf.cons_tableHei.constant = CGFloat((weakSelf.studentModels.count) * 87)
                                    weakSelf.changePrice(weakSelf.selectClassIndex)
                        } needAddClouse: { [weak self] () in
                                    let vc = AddStudentVC(type: .course)
                                    self?.push(vc: vc)
                        }
            }
            @IBAction func paymentAction(_ sender: UIButton) {
                        guard detailModel != nil else {return}
                        guard studentModels.count != 0 else {alertError(msg: "请选择运动营成员");return}
                        StoresInfoView.show(detailModel!) { [weak self] status in
                                    guard let weakSelf = self else { return }
                                    if status{
                                                if var model = weakSelf.detailModel?.list[weakSelf.selectClassIndex]{
                                                            //续课时价格
                                                            if let list = weakSelf.signUpModel?.list{
                                                                        model = list[weakSelf.selectClassIndex]
                                                            }
                                                            var price:Double = 0
                                                            //是否是会员
                                                            if weakSelf.detailModel?.isVip == 1 && model.vipPrice != 0{
                                                                        price = model.vipPrice
                                                            }else{
                                                                        price = model.paymentPrice
                                                            }
                                                            //计算人数总价
                                                            price = price * Double(weakSelf.studentModels.count)
                                                            //减去优惠
                                                            var discountPrice = price - (weakSelf.selectCouponModel?.favorable ?? 0)
                                                            var coin = model.playPaiCoin * weakSelf.studentModels.count
                                                            //待支付订单 ,取最终订单金额
                                                            if weakSelf.signUpModel?.payStatus == .unPayment{
                                                                        discountPrice = weakSelf.signUpModel?.payPrice ?? 0
                                                                        coin = weakSelf.signUpModel?.coinPrice ?? 0
                                                            }
                                                            PaymentView.show(enumType: .course, money: (ali:discountPrice,wx:discountPrice,coin:coin,course:nil,integral:nil)) { [weak self] payType in
                                                                        guard let weakSelf = self else { return }
                                                                        var resultPayPrice:Double = 0
                                                                        switch payType {
                                                                                    case .aliPay,.wechat:
                                                                                                resultPayPrice = price
                                                                                                //待支付订单单独处理
                                                                                                if weakSelf.signUpModel?.payStatus == .unPayment{
                                                                                                            resultPayPrice = weakSelf.signUpModel?.payPrice ?? 0
                                                                                                }
                                                                                    case .coin:
                                                                                                resultPayPrice = Double(coin)
                                                                                    default:break
                                                                        }
                                                                        Services.courcePayment(conponId: weakSelf.selectCouponModel?.id, courseConfigId: model.id, id: weakSelf.detailModel!.id, price: resultPayPrice, payType: payType, stuId: weakSelf.studentModels.map({$0.id}),orderId: weakSelf.signUpModel?.coursePayId).subscribe(onNext: { data in
                                                                                    if data.code == 200{
                                                                                                switch payType {
                                                                                                            case .aliPay:
                                                                                                                        YYPaymentManager.shared.sendPaymentRequest(YYAlipayRequest(orderString: data.data!.orderString)) { [weak self] result in
                                                                                                                                    switch result {
                                                                                                                                                case .success:
                                                                                                                                                            let vc = PaymentResultVC(result: .success, objType: .courseApply,handleVC: self,courseConfigId: model.id)
                                                                                                                                                            vc.isExtend = self?.signUpModel?.payStatus == .paymented
                                                                                                                                                            self?.push(vc: vc)
                                                                                                                                                case .cancel:
                                                                                                                                                            alert(msg: "已取消")
                                                                                                                                                case .failure(_):
                                                                                                                                                            let vc = PaymentResultVC(result: .fail("支付失败",0), objType: .courseApply)
                                                                                                                                                            self?.push(vc: vc)
                                                                                                                                    }
                                                                                                                        }
                                                                                                            case .wechat:
                                                                                                                        self?.navigationController?.popViewController(animated: false)
                                                                                                                        break
                                                                                                            case .coin:
                                                                                                                        let vc = PaymentResultVC(result: .success, objType: .courseApply,handleVC: self,courseConfigId: model.id)
                                                                                                                        vc.isExtend = self?.signUpModel?.payStatus == .paymented
                                                                                                                        self?.push(vc: vc)
                                                                                                            default:break
                                                                                                }
                                                                                    }else{
                                                                                                alertError(msg: data.msg)
                                                                                    }
                                                                        },onError: { error in
                                                                                    if let er = error as? NetworkRequest.NetRequestError{
                                                                                                switch er {
                                                                                                            case .Other(let code,let string):
                                                                                                                        let vc = PaymentResultVC(result: .fail(string,code), objType: .courseApply,handleVC: nil)
                                                                                                                        self?.push(vc: vc)
                                                                                                            default:
                                                                                                                        let vc = PaymentResultVC(result: .fail("支付失败",0), objType: .courseApply,handleVC: nil)
                                                                                                                        self?.push(vc: vc)
                                                                                                }
                                                                                    }
                                                                        }).disposed(by: weakSelf.disposeBag)
                                                            }
                                                }
                                    }else{
                                                self?.navigationController?.popToRootViewController(animated: true)
                                                NotificationCenter.default.post(name: ChooseHomeStore_Noti, object: nil)
                                    }
                        }
            }
            //计算价格
            private func changePrice(_ index:Int){
                        //待支付订单,终止后续
                        if signUpModel?.payStatus == .unPayment{
                                    label_price.isHidden = true
                                    label_originPrice.isHidden = signUpModel!.payPrice == signUpModel!.orinPrice
                                    label_vipPrice.isHidden = true
                                    label_coin.isHidden = true
                                    let originPrice = signUpModel!.orinPrice - signUpModel!.payPrice
                                    label_originPrice.attributedText = AttributedStringbuilder.build().add(string: originPrice.currency(), withFont: UIFont.systemFont(ofSize: 16, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F").withAlphaComponent(0.58)).delLine(color: UIColor(hexStr: "#3F3F3F").withAlphaComponent(0.58)).mutableAttributedString
                                    if signUpModel?.coinPrice != 0{
                                                label_coin.isHidden = false
                                                label_coin.attributedText = AttributedStringbuilder.build()
                                                            .add(string: "玩湃币:", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F"))
                                                            .add(string: "\(signUpModel!.coinPrice)币", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#F21313")).mutableAttributedString
                                    }
                                    if signUpModel?.payPrice != 0{
                                                label_price.isHidden = false
                                                label_price.text = (signUpModel!.payPrice).currency()
                                    }
                                    return
                        }
                        if let subM = detailModel?.list[index]{
                                    var studentCount:Int = 0
                                    if studentModels.count == 0{
                                                studentCount = 1
                                    }else{
                                                studentCount = studentModels.count
                                    }
                                    switch subM.payType {
                                                case .coin:
                                                            label_price.text = ""
                                                            label_price.isHidden = true
                                                            label_originPrice.isHidden = true
                                                            label_vipPrice.isHidden = true
                                                            label_coin.isHidden = false
                                                            //纯玩湃币没有优惠券项
                                                            btn_coupon.isHidden = true
                                                            label_coin.isHidden = false
                                                            //玩湃币
                                                            label_coin.attributedText = AttributedStringbuilder.build()
                                                                        .add(string: "玩湃币:", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F"))
                                                                        .add(string: "\(subM.playPaiCoin * studentCount)币", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#F21313")).mutableAttributedString
                                                case .cash:
                                                            fallthrough
                                                case .cashCoin:
                                                            if subM.originalPrice == 0 || subM.originalPrice == subM.paymentPrice{
                                                                        label_originPrice.isHidden = true
                                                            }else{
                                                                        label_originPrice.isHidden = false
                                                            }
                                                            //               label_originPrice.isHidden = (subM.paymentPrice == subM.originalPrice && subM.paymentPrice != 0 && subM.originalPrice != 0)
                                                            label_coin.isHidden = subM.payType == .cash
                                                            //玩湃币
                                                            label_coin.attributedText = AttributedStringbuilder.build()
                                                                        .add(string: "玩湃币:", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F"))
                                                                        .add(string: "\(subM.playPaiCoin * studentCount)币", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#F21313")).mutableAttributedString
                                                            //原价
                                                            let attribute = AttributedStringbuilder.build().add(string: (subM.originalPrice * Double(studentCount)).currency(), withFont: UIFont.systemFont(ofSize: 16, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F").withAlphaComponent(0.58)).delLine(color: UIColor(hexStr: "#3F3F3F").withAlphaComponent(0.58))
                                                            label_originPrice.attributedText = attribute.mutableAttributedString
                                                            if UserInfoModel.get()?.isVip == 1{
                                                                        if subM.payType != .coin{
                                                                                    //会员
                                                                                    label_vipPrice.isHidden = true
                                                                                    if subM.paymentPrice < subM.vipPrice && subM.paymentPrice != 0{
                                                                                                label_price.text = (subM.paymentPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                                                                                    }else if subM.vipPrice < subM.paymentPrice && subM.vipPrice != 0{
                                                                                                label_price.text = (subM.vipPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                                                                                    }else if subM.vipPrice != 0 &&  subM.paymentPrice != 0{
                                                                                                let price = min(subM.vipPrice, subM.paymentPrice)
                                                                                                label_price.text = (price *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                                                                                    }else{
                                                                                                label_price.text = (subM.paymentPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                                                                                    }
                                                                        }
                                                            }else{
                                                                        if subM.payType != .coin{
                                                                                    //非会员
                                                                                    label_vipPrice.isHidden = subM.vipPrice == 0 || subM.vipPrice == subM.paymentPrice
                                                                                    let vipAttribute = AttributedStringbuilder.build()
                                                                                                .add(string: "会员价:", withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#3F3F3F"))
                                                                                                .add(string: (subM.vipPrice *  Double(studentCount)).currency(), withFont: UIFont.systemFont(ofSize: 14, weight: .semibold), withColor: UIColor(hexStr: "#F21313"))
                                                                                    label_vipPrice.attributedText = vipAttribute.mutableAttributedString
                                                                                    if subM.originalPrice != 0 && subM.paymentPrice == 0{
                                                                                                label_price.text = (subM.originalPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                                                                                    }else if subM.originalPrice == 0 && subM.paymentPrice != 0{
                                                                                                label_price.text = (subM.paymentPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                                                                                    }else if subM.originalPrice != 0 && subM.paymentPrice != 0{
                                                                                                var money = min(subM.originalPrice,subM.paymentPrice)
                                                                                                money = money - (selectCouponModel?.favorable ?? 0)
                                                                                                label_price.text = (money *  Double(studentCount)).currency()
                                                                                    }else{
                                                                                                label_price.text = (subM.originalPrice *  Double(studentCount) - (selectCouponModel?.favorable ?? 0)).currency()
                                                                                    }
                                                                        }
                                                            }
                                    }
                                    if detailModel?.type == .experience{
                                                if subM.paymentPrice != 0{
                                                            label_price.text = subM.paymentPrice.currency()
                                                            label_price.isHidden = false
                                                }
                                                view_teach.isHidden = true
                                                label_originPrice.isHidden = true
                                                label_vipPrice.isHidden = true
                                    }
                                    //         if label_originPrice.isHidden && label_vipPrice.isHidden && label_coin.isHidden{
                                    //            label_coin.alpha = 0
                                    //         }
                        }
            }
            //查询优惠券
            private func queryCouponInfo(complete:(()->Void)? = nil){
                        if let subM = detailModel?.list[selectClassIndex]{
                                    var price:Double?
                                    switch subM.payType{
                                                case .cash,.cashCoin:
                                                            price = subM.originalPrice == 0 ? subM.vipPrice : subM.originalPrice
                                                case .coin:
                                                            price = Double(subM.playPaiCoin)
                                    }
                                    guard price != nil else {
                                                LogError("会员优惠价格出现问题:nil");return
                                    }
                                    Services.queryAvaiableCopons(id: detailModel!.id, price: price!).subscribe(onNext: { [weak self] data in
                                                guard let weakSelf = self else { return }
                                                self?.btn_coupon.isHidden = (data.data?.count ?? 0) == 0 || weakSelf.signUpModel?.payStatus == .unPayment
                                                self?.couponModels = data.data ?? []
                                                self?.label_couponInfo.isHidden = (data.data?.count ?? 0) == 0
                                                self?.label_couponInfo.text = String(format: "(%ld张可用)",data.data?.count ?? 0)
                                                //重新获取优惠券,在切换套餐时触发
                                                if let selectCoupon = self?.selectCouponModel{
                                                            if !weakSelf.couponModels.contains(where: {$0.id == selectCoupon.id}){
                                                                        weakSelf.selectCouponModel = nil
                                                                        weakSelf.btn_couponInfo.setTitle("去选择", for: .normal)
                                                            }
                                                }
                                                complete?()
                                    }).disposed(by: disposeBag)
                        }
            }
            override func viewDidLayoutSubviews() {
                        super.viewDidLayoutSubviews()
                        let w = String.jq_getWidth(text: detailModel?.type.strTitle ?? "", height: 25, font: 14) + 16
                        label_courseType.jq_addCorners(corner: [.topLeft,.bottomLeft], radius: 4, width: w, height: 25)
            }
}
extension CourseDetailApplyVC:UICollectionViewDelegate{
   func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      selectClassIndex = indexPath.row
      collectionView.reloadData()
      queryCouponInfo {[weak self] () in
         self?.changePrice(indexPath.row)
      }
   }
            func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
                        selectClassIndex = indexPath.row
                        collectionView.reloadData()
                        queryCouponInfo {[weak self] () in
                                    self?.changePrice(indexPath.row)
                        }
            }
}
extension CourseDetailApplyVC:UICollectionViewDataSource{
   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let m = detailModel!.list[indexPath.row]
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_Common_1_CCell", for: indexPath) as! Common_1_CCell
      cell.isSelected = indexPath.row == selectClassIndex
      cell.courseDetailListModel = m
      return cell
   }
            func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                        let m = detailModel!.list[indexPath.row]
                        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_Common_1_CCell", for: indexPath) as! Common_1_CCell
                        cell.isSelected = indexPath.row == selectClassIndex
                        cell.courseDetailListModel = m
                        return cell
            }
   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      return detailModel?.list.count ?? 0
   }
            func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
                        return detailModel?.list.count ?? 0
            }
}
extension CourseDetailApplyVC:UICollectionViewDelegateFlowLayout{
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
      return 21
   }
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
                        return 21
            }
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
      return 21
   }
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
                        return 21
            }
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
      return CGSize(width: CellW, height: CellH)
   }
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                        return CGSize(width: CellW, height: CellH)
            }
}
extension CourseDetailApplyVC:UITableViewDataSource{
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return studentModels.count
   }
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                        return studentModels.count
            }
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "_StudentInfoTCell") as! StudentInfoTCell
      cell.indexPath = indexPath
      cell.studentModel = studentModels[indexPath.row]
      cell.deleClouse = { [weak self] index in
         guard let weakSelf = self else { return }
         if weakSelf.studentModels.count > 1{
            tableView.beginUpdates()
            weakSelf.studentModels.remove(at: index)
            tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .right)
            tableView.endUpdates()
            weakSelf.cons_tableHei.constant = CGFloat((weakSelf.studentModels.count) * 87)
            tableView.reloadData()
            weakSelf.changePrice(weakSelf.selectClassIndex)
         }else{
            alert(msg: "至少选择一位运动营成员")
         }
      }
      cell.btn_handle.isHidden = signUpModel != nil
      return cell
   }
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                        let cell = tableView.dequeueReusableCell(withIdentifier: "_StudentInfoTCell") as! StudentInfoTCell
                        cell.indexPath = indexPath
                        cell.studentModel = studentModels[indexPath.row]
                        cell.deleClouse = { [weak self] index in
                                    guard let weakSelf = self else { return }
                                    if weakSelf.studentModels.count > 1{
                                                tableView.beginUpdates()
                                                weakSelf.studentModels.remove(at: index)
                                                tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .right)
                                                tableView.endUpdates()
                                                weakSelf.cons_tableHei.constant = CGFloat((weakSelf.studentModels.count) * 87)
                                                tableView.reloadData()
                                                weakSelf.changePrice(weakSelf.selectClassIndex)
                                    }else{
                                                alert(msg: "至少选择一位运动营成员")
                                    }
                        }
                        cell.btn_handle.isHidden = signUpModel != nil
                        return cell
            }
}