//
//  YHInvitationWithGiftsSecondTableViewCell.swift
//  galaxy
//
//  Created by EDY on 2024/7/18.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHInvitationWithGiftsSecondTableViewCell: UITableViewCell {
    var centerView: UIView!
    var titleLeftImageView: UIImageView!
    var titleRightImageView: UIImageView!
    var titleImageView: UIImageView!
    var timeLabel: UILabel!
    var numberBgView: UIImageView!
    var lineImageView: UIImageView!
    var numberOneView: YHInvitationNumberItemView!
    var numberTwoView: YHInvitationNumberItemView!
    var numberThreeView: YHInvitationNumberItemView!
    var explainLabel: UILabel!
    var recommendLabel: UILabel!
    var recommendButton: UIButton!
    var peopleOneView: YHInvitationPeopleItemView!
    var peopleTwoView: YHInvitationPeopleItemView!
    var peopleThreeView: YHInvitationPeopleItemView!
    var peopleFourView: YHInvitationPeopleItemView!
    var peopleFiveView: YHInvitationPeopleItemView!
    var tableView: UITableView!
    var viewModel: YHInvitationWithGiftsViewModel = YHInvitationWithGiftsViewModel()
    var page = 1
    var list: [YHShareRecordListModel] = []
    var selectOne: Int?
    var selectTwo: Int?
    var startTime: String = ""
    var endTime: String = ""
    
    var headData: YHShareOverviewModel? {
        didSet {
            guard let model = headData else { return }
            if model.cycle.begin_date.count == 0 || model.cycle.end_date.count == 0 {
                timeLabel.text = "推荐周期：暂无（推荐好友签约后生成周期）"
            } else {
                timeLabel.text = "您的推荐周期：\(model.cycle.begin_date)至\(model.cycle.end_date)"
            }
            numberOneView.titleLabel.text = "\(model.register_count)"
            numberTwoView.titleLabel.text = "\(model.evaluated_count)"
            numberThreeView.titleLabel.text = "\(model.signed_up_count)"
        }
    }
    
    var tableData: YHShareRecordModel? {
        didSet {
            if tableData?.list.count == 0 {
                let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.width - 30, height: 40))
                label.text = "还未有推荐信息，快分享给好友吧～"
                label.textColor = UIColor.yhGreyColor
                label.font = UIFont.PFSC_M(ofSize: 12)
                label.textAlignment = .center
                label.layer.borderWidth = 1
                label.layer.borderColor = UIColor(hex: 0xebf4fe).cgColor
                label.layer.cornerRadius = kCornerRadius3
                label.layer.maskedCorners = [.layerMinXMaxYCorner,.layerMaxXMaxYCorner]
                self.tableView.tableFooterView = label
            } else {
                self.tableView.tableFooterView = UIView()
            }
            if tableData?.page_count == 1 {
                self.tableView.es.noticeNoMoreData()
                self.tableView.footer?.alpha = 1
            }
            self.list = tableData?.list ?? []
            self.tableView.reloadData()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        self.backgroundColor = UIColor(hex: 0xebf4fe)
        centerView = {
            let view = UIView()
            view.layer.cornerRadius = kCornerRadius3
            view.backgroundColor = .white
            return view
        }()
        contentView.addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(8)
            make.right.equalTo(-12)
            make.bottom.equalTo(-8)
        }
        
        titleLeftImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_second_left")
            return view
        }()
        centerView.addSubview(titleLeftImageView)
        titleLeftImageView.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(29)
            make.width.equalTo(110)
            make.height.equalTo(20)
        }
        
        titleRightImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_second_right")
            return view
        }()
        centerView.addSubview(titleRightImageView)
        titleRightImageView.snp.makeConstraints { make in
            make.width.equalTo(110)
            make.top.equalTo(29)
            make.right.equalTo(-15)
            make.height.equalTo(20)
        }
        
        titleImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_second_title")
            return view
        }()
        centerView.addSubview(titleImageView)
        titleImageView.snp.makeConstraints { make in
            make.width.equalTo(80)
            make.top.equalTo(29)
            make.centerX.equalToSuperview()
            make.height.equalTo(20)
        }
        
        timeLabel = {
            let view = UILabel()
            view.text = "您的推荐周期：2023-11-20 至2024-11-19"
            view.font = UIFont.PFSC_M(ofSize: 13)
            view.textColor = UIColor.yhGreyColor
            view.textAlignment = .center
            return view
        }()
        centerView.addSubview(timeLabel)
        timeLabel.snp.makeConstraints { make in
            make.width.equalTo(300)
            make.top.equalTo(63)
            make.centerX.equalToSuperview()
            make.height.equalTo(18)
        }
        
        numberBgView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_second_number_bg")
            return view
        }()
        centerView.addSubview(numberBgView)
        numberBgView.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(97)
            make.right.equalTo(-15)
            make.height.equalTo(78)
        }
        
        lineImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_second_line")
            return view
        }()
        centerView.addSubview(lineImageView)
        lineImageView.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(187)
            make.right.equalTo(-15)
            make.height.equalTo(1)
        }
        
        recommendLabel = {
            let label = UILabel()
            label.text = "推荐明细"
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor.mainTextColor
            return label
        }()
        centerView.addSubview(recommendLabel)
        recommendLabel.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(203)
            make.right.equalTo(-15)
            make.height.equalTo(21)
        }
        
        recommendButton = {
            let button = UIButton()
            button.setBackgroundImage(UIImage(named: "invitation_with_gifts_select_normal"), for: .normal)
            button.setBackgroundImage(UIImage(named: "invitation_with_gifts_select"), for: .selected)
            button.addTarget(self, action: #selector(selectItem), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(recommendButton)
        recommendButton.snp.makeConstraints { make in
            make.width.equalTo(47)
            make.top.equalTo(205)
            make.right.equalTo(-15)
            make.height.equalTo(18)
        }
        
        numberTwoView = {
            let view = YHInvitationNumberItemView()
            view.bottomLabel.text = "已测评"
            return view
        }()
        numberBgView.addSubview(numberTwoView)
        numberTwoView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.height.equalTo(78)
            make.width.equalTo(71)
        }
        
        numberOneView = {
            let view = YHInvitationNumberItemView()
            return view
        }()
        numberBgView.addSubview(numberOneView)
        numberOneView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(numberTwoView.snp.left).offset(-30)
            make.height.equalTo(78)
            make.width.equalTo(71)
        }
        
        numberThreeView = {
            let view = YHInvitationNumberItemView()
            view.bottomLabel.text = "已签约"
            return view
        }()
        numberBgView.addSubview(numberThreeView)
        numberThreeView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(numberTwoView.snp.right).offset(30)
            make.height.equalTo(78)
            make.width.equalTo(71)
        }
        
        let firstlineView = UIView()
        firstlineView.backgroundColor = .white
        numberBgView.addSubview(firstlineView)
        firstlineView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(numberTwoView.snp.left).offset(-14)
            make.height.equalTo(24)
            make.width.equalTo(1)
        }
    
        let lastlineView = UIView()
        lastlineView.backgroundColor = .white
        numberBgView.addSubview(lastlineView)
        lastlineView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(numberTwoView.snp.right).offset(14)
            make.height.equalTo(24)
            make.width.equalTo(1)
        }
        
        explainLabel = {
            let view = UILabel()
            view.text = "*积分发放及提取方式，详见规则"
            view.font = UIFont.PFSC_M(ofSize: 11)
            view.textColor = UIColor.mainTextColor50
            view.textAlignment = .center
            return view
        }()
        centerView.addSubview(explainLabel)
        explainLabel.snp.makeConstraints { make in
            make.width.equalTo(300)
            make.bottom.equalTo(-18)
            make.centerX.equalToSuperview()
            make.height.equalTo(18)
        }
        
        peopleOneView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.text = "被邀请人"
            view.layer.cornerRadius = kCornerRadius3
            view.layer.maskedCorners = [.layerMinXMinYCorner]
            return view
        }()
        centerView.addSubview(peopleOneView)
        peopleOneView.snp.makeConstraints { make in
            make.top.equalTo(239)
            make.left.equalTo(15)
            make.height.equalTo(37)
            make.width.equalTo(100)
        }
        
        peopleFiveView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.text = "签约"
            view.titleLabel.textAlignment = .center
            view.layer.cornerRadius = kCornerRadius3
            view.layer.maskedCorners = [.layerMaxXMinYCorner]
            view.titleLabel.snp.remakeConstraints { make in
                make.top.equalTo(10)
                make.height.equalTo(17)
                make.left.right.equalToSuperview()
            }
            return view
        }()
        centerView.addSubview(peopleFiveView)
        peopleFiveView.snp.makeConstraints { make in
            make.top.equalTo(239)
            make.right.equalTo(-15)
            make.height.equalTo(37)
            make.width.equalTo(38)
        }
        
        peopleFourView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.text = "测评"
            view.titleLabel.textAlignment = .center
            view.titleLabel.snp.remakeConstraints { make in
                make.top.equalTo(10)
                make.height.equalTo(17)
                make.left.right.equalToSuperview()
            }
            return view
        }()
        centerView.addSubview(peopleFourView)
        peopleFourView.snp.makeConstraints { make in
            make.top.equalTo(239)
            make.right.equalTo(peopleFiveView.snp.left).offset(-1)
            make.height.equalTo(37)
            make.width.equalTo(38)
        }
        
        peopleThreeView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.text = "注册"
            view.titleLabel.textAlignment = .center
            view.titleLabel.snp.remakeConstraints { make in
                make.top.equalTo(10)
                make.height.equalTo(17)
                make.left.right.equalToSuperview()
            }
            return view
        }()
        centerView.addSubview(peopleThreeView)
        peopleThreeView.snp.makeConstraints { make in
            make.top.equalTo(239)
            make.right.equalTo(peopleFourView.snp.left).offset(-1)
            make.height.equalTo(37)
            make.width.equalTo(38)
        }
        
        peopleTwoView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.text = "注册时间"
            return view
        }()
        centerView.addSubview(peopleTwoView)
        peopleTwoView.snp.makeConstraints { make in
            make.top.equalTo(239)
            make.right.equalTo(peopleThreeView.snp.left).offset(-1)
            make.height.equalTo(37)
            make.left.equalTo(peopleOneView.snp.right).offset(1)
        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.showsHorizontalScrollIndicator = false
            tableView.showsVerticalScrollIndicator = false
            tableView.dataSource = self
            tableView.delegate = self
            tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01))
            tableView.register(cellWithClass: YHInvitationWithGiftsPeopleTableViewCell.self)
            return tableView
        }()
        centerView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(276)
            make.bottom.equalTo(-46)
            make.left.equalTo(15)
            make.right.equalTo(-15)
        }
        tableView.es.addInfiniteScrolling {
            self.viewModel.postRecord(page: self.page + 1) {[weak self] success, error in
                guard let self = self else { return }
                self.page = self.page + 1
                self.tableView.es.stopLoadingMore()
                if self.viewModel.recordModel.page_count == self.page {
                    self.tableView.es.noticeNoMoreData()
                    self.tableView.footer?.alpha = 1
                }
                for item in self.viewModel.recordModel.list {
                    self.list.append(item)
                }
                self.tableView.reloadData()
            }
        }
        
    }

    @objc func selectItem() {
        YHInvitationWithGiftsSelectItemView.show(selectOne: selectOne ?? 100, selectTwo: selectTwo ?? 100, startTime: startTime, endTime: endTime) { [weak self] one, two, start, end in
            guard let self = self else { return }
            self.selectOne = one
            self.selectTwo = two
            self.startTime = start
            self.endTime = end
            if one == 100, two == 100 , start == "", end == "" {
                recommendButton.isSelected = false
                viewModel.startTime = ""
                viewModel.endTime = ""
                viewModel.state = two
            } else {
                recommendButton.isSelected = true
                if one == 0 {
                    viewModel.startTime = getOneMonthAgoDate()
                    viewModel.endTime = getCurrentDate()
                } else if one == 1 {
                    viewModel.startTime = getSixMonthsAgoDate()
                    viewModel.endTime = getCurrentDate()
                } else if one == 2 {
                    viewModel.startTime = getOneYearAgoDate()
                    viewModel.endTime = getCurrentDate()
                } else if one == 3 {
                    viewModel.startTime = start
                    viewModel.endTime = end
                } else {
                    viewModel.startTime = ""
                    viewModel.endTime = ""
                }
                viewModel.state = two
            }
            self.page = 1
            //请求刷新数据
            self.tableView.es.resetNoMoreData()
            self.viewModel.postRecord(page: 1) {[weak self] success, error in
                guard let self = self else { return }
                if self.viewModel.recordModel.page_count == 1 {
                    self.tableView.es.noticeNoMoreData()
                    self.tableView.footer?.alpha = 1
                }
                self.tableData = self.viewModel.recordModel
                self.tableView.reloadData()
            }
            self.viewModel.getOverviewRecord {[weak self] success, error in
                guard let self = self else { return }
                self.headData = self.viewModel.overviewModel
            }
        }
    }
    
    func getCurrentDate() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter.string(from: Date())
    }
     
    // 获取一年前的日期
    func getOneYearAgoDate() -> String {
        let calendar = Calendar.current
        let oneYearAgo = calendar.date(byAdding: .year, value: -1, to: Date())!
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter.string(from: oneYearAgo)
    }
     
    // 获取半年前的日期
    func getSixMonthsAgoDate() -> String {
        let calendar = Calendar.current
        let sixMonthsAgo = calendar.date(byAdding: .month, value: -6, to: Date())!
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter.string(from: sixMonthsAgo)
    }
     
    // 获取一个月前的日期
    func getOneMonthAgoDate() -> String {
        let calendar = Calendar.current
        let oneMonthAgo = calendar.date(byAdding: .month, value: -1, to: Date())!
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter.string(from: oneMonthAgo)
    }
}

extension YHInvitationWithGiftsSecondTableViewCell: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
     
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHInvitationWithGiftsPeopleTableViewCell.self)
        cell.dataSource = list[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
}

class YHInvitationWithGiftsPeopleTableViewCell: UITableViewCell {
    var peopleOneView: YHInvitationPeopleItemView!
    var peopleTwoView: YHInvitationPeopleItemView!
    var peopleThreeView: YHInvitationPeopleItemView!
    var peopleFourView: YHInvitationPeopleItemView!
    var peopleFiveView: YHInvitationPeopleItemView!
    var dataSource: YHShareRecordListModel? {
        didSet {
            guard let dataSource = dataSource else { return }
            peopleOneView.titleLabel.text = dataSource.mobile
            peopleTwoView.titleLabel.text = dataSource.register_time
            if dataSource.is_registered {
                peopleThreeView.bgImageView.image = UIImage(named: "invitation_with_gifts_people_true")
            } else {
                peopleThreeView.bgImageView.image = UIImage(named: "invitation_with_gifts_people_false")
            }
            if dataSource.is_evaluated {
                peopleFourView.bgImageView.image = UIImage(named: "invitation_with_gifts_people_true")
            } else {
                peopleFourView.bgImageView.image = UIImage(named: "invitation_with_gifts_people_false")
            }
            if dataSource.is_signed_up {
                peopleFiveView.bgImageView.image = UIImage(named: "invitation_with_gifts_people_true")
            } else {
                peopleFiveView.bgImageView.image = UIImage(named: "invitation_with_gifts_people_false")
            }
        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        self.backgroundColor = UIColor(hex: 0xebf4fe)
        peopleOneView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.text = "188****8888"
            view.backgroundColor = .white
            return view
        }()
        contentView.addSubview(peopleOneView)
        peopleOneView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(1)
            make.bottom.equalTo(-1)
            make.width.equalTo(99)
        }
        
        peopleFiveView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.isHidden = true
            view.bgImageView.isHidden = false
            view.backgroundColor = .white
            return view
        }()
        contentView.addSubview(peopleFiveView)
        peopleFiveView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.right.equalTo(-1)
            make.bottom.equalTo(-1)
            make.width.equalTo(37)
        }
        
        peopleFourView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.isHidden = true
            view.bgImageView.isHidden = false
            view.backgroundColor = .white
            return view
        }()
        contentView.addSubview(peopleFourView)
        peopleFourView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.right.equalTo(peopleFiveView.snp.left).offset(-1)
            make.bottom.equalTo(-1)
            make.width.equalTo(38)
        }
        
        peopleThreeView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.isHidden = true
            view.bgImageView.isHidden = false
            view.bgImageView.image = UIImage(named: "invitation_with_gifts_people_false")
            view.backgroundColor = .white
            return view
        }()
        contentView.addSubview(peopleThreeView)
        peopleThreeView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.right.equalTo(peopleFourView.snp.left).offset(-1)
            make.bottom.equalTo(-1)
            make.width.equalTo(38)
        }
        
        peopleTwoView = {
            let view = YHInvitationPeopleItemView()
            view.titleLabel.text = "2024-06-09"
            view.backgroundColor = .white
            return view
        }()
        contentView.addSubview(peopleTwoView)
        peopleTwoView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.right.equalTo(peopleThreeView.snp.left).offset(-1)
            make.bottom.equalTo(-1)
            make.left.equalTo(peopleOneView.snp.right).offset(1)
        }
    }

}

