//
//  YHDatePickView.swift
//  galaxy
//
//  Created by EDY on 2024/1/30.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//


import UIKit
///  view的三种状态,控制tableView展示效果与数据
enum YHLocationPickViewTableViewType {
    case provinces  //省份
    case city       //城市
}

class YHAddressPickView: UIView {
    /// 返回数据回调
    public var backLocationString: ((String,String,String,String) -> Void)?
    /// 退出回调
    public var backOnClickCancel: (() -> Void)?
    /// title选中以及下滑线颜色
    public var selectColor: UIColor

    private var tableViewType: YHLocationPickViewTableViewType = .provinces {
        didSet {
            switch tableViewType {
            case .provinces:
                /// 选择省份时,有上面的热门城市view.没有滚动选择type的titleScrollView.没有已选择label.
                self.tableView.tableHeaderView = tableViewHeaderView
                self.tableView.frame = CGRect(x: 0, y: 42, width: UIScreen.main.bounds.width, height: 458)
                self.titleSV.isHidden = true
                self.leftLabel.isHidden = true
                /// 将所有选中数据清空
                self.provincesModel = nil
                self.selectedProvince = ""
                self.selectedCity = ""
                self.selectedArea = ""
                self.cityModel = nil
                // 将titleSV中所有button的title重置
                // 并将第一个button设置为选中状态,已保证选择城市后button下的横线有滚动效果.
                for button in buttonArr {
                    button.setTitle("请选择", for: .normal)
                    button.isSelected = false
                    if button.tag == 0 {
                        button.isSelected = true
                    }
                }
                self.underLine.center = CGPoint(x: self.buttonArr[1].center.x, y: self.underLine.center.y)
                self.dataArray = locationModel?.provincesArray.map({ model in
                    model.provincesName
                })
                self.tableView.reloadData()
            case .city:
                /// 选择城市时没有热门城市view,并将titleSV显示出来
                self.tableView.tableHeaderView = UIView()
                self.tableView.frame = CGRect(x: 0, y: 136, width: UIScreen.main.bounds.width, height: 367)
                self.titleSV.isHidden = false
                self.leftLabel.isHidden = false
                /// 将省份选择保留,将城市与地区数据清空
                self.selectedCity = ""
                self.selectedArea = ""
                self.cityModel = nil
                /// 通过修改titleSV中button的选中状态来修改它的颜色
                for button in buttonArr {
                    button.isSelected = false
                    if button.tag != 0 {
                        button.setTitle("请选择", for: .normal)
                    }
                    if button.tag == 1 {
                        button.isSelected = true
                    }
                }
                /// 滚动titleSV中button下滚动的Line
                UIView.animate(withDuration: 0.3, animations: {() -> Void in
                    self.underLine.center = CGPoint(x: self.buttonArr[1].center.x, y: self.underLine.center.y)
                })
                self.dataArray = provincesModel?.cityArray.map({ model in
                    model.cityName
                })
                self.tableView.reloadData()
            }
        }
    }
    /// titleSV上的三个button,通过array保存,更好操作
    private var buttonArr = [UIButton]()
    /// 已选中的省份
    private var selectedProvince = ""{
        didSet {
            /// 当选中赋值时,将titleSV上第一个button.title改为省份名
            for button in buttonArr where button.tag == 0 {
                    button.setTitle(selectedProvince, for: .normal)
            }
        }
    }
    /// 已选中城市
    private var selectedCity = ""{
        didSet {
            /// 当选中赋值时,将titleSV上第二个button.title改为城市名
            for button in buttonArr where button.tag == 1 {
                    button.setTitle(selectedCity, for: .normal)
            }
        }
    }
    private var selectedArea = ""
    /// 总城市数据
    private var locationModel: YHCountryModel?
    /// 省份数据
    private var provincesModel: YHProvincesModel?
    /// 城市数据
    private var cityModel: YHCityModel?
    /// 当前tableView使用的数据源
    private var dataArray: [String]?
    private let titleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: (UIScreen.main.bounds.width - 100) / 2, y: 9, width: 100, height: 24))
        label.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
        label.text = "选择国家地区"
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 16)
        return label
    }()
    private let rightCancelButton: UIButton = {
        let button = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 42, y: 11, width: 18, height: 18))
        button.setImage(UIImage(named: "BaseVC_cancel"), for: .normal)
        return button
    }()
    private let leftLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 24, y: 43, width: 40, height: 18))
        label.text = "已选择"
        label.textColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 12)
        label.isHidden = true
        return label
    }()
    /// 热门城市数组,可修改,若修改数量需要修改下方tableViewHeaderView.frame;若修改城市需要修改onClickHotCity()方法来实现点击跳转功能
    private let hotCityArray = ["北京","上海","广州","深圳","杭州","南京","苏州","天津","武汉","长沙","重庆","成都"]
    private lazy var tableViewHeaderView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 160))
        let label = UILabel(frame: CGRect(x: 24, y: 0, width: 50, height: 18))
        label.textColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 12)
        label.text = "热门城市"
        view.addSubview(label)
        for i in 0..<12 {
            let button: UIButton = UIButton(frame: CGRect(x: CGFloat(24 + 80 * (i % 4)), y: CGFloat(28 + 40 * (i / 4)), width: 80, height: 40))
            button.setTitle(hotCityArray[i], for: .normal)
            button.setTitleColor(UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1), for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            button.addTarget(self, action: #selector(onClickHotCity(sender:)), for: .touchUpInside)
            button.tag = i
            view.addSubview(button)
        }
        return view
    }()
    /// 上方选择省份城市地区的滚动scrollView
    private var titleSV: UIScrollView!
    /// titleSV上button下的滚动线
    private var underLine = UIView()
    private var tableView = UITableView(frame: CGRect(x: 0, y:42 , width: UIScreen.main.bounds.width, height: 458))

    init(frame: CGRect, selectColor: UIColor, selectedProvince: String? = nil, selectedCity: String? = nil) {
        self.selectColor = selectColor
        super.init(frame: frame)
        initLocationData()
        drawMyView()
        setHotCityData(province: selectedProvince, city: selectedCity)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func drawMyView() {
        self.backgroundColor = UIColor.white
        buildTitleScrollView()
        drawTableView()
        self.addSubview(titleLabel)
        self.addSubview(rightCancelButton)
        rightCancelButton.addTarget(self, action: #selector(onClickCancelButton), for: .touchUpInside)
        self.addSubview(leftLabel)
    }
    private func buildTitleScrollView() {
        if titleSV != nil {
            titleSV.removeFromSuperview()
        }
        buttonArr = []
        titleSV = UIScrollView(frame: CGRect(x: 0, y: 72, width: UIScreen.main.bounds.width, height: 44))
        self.underLine = UIView(frame: CGRect(x: 0, y: 40, width: 30, height: 2))
        self.underLine.backgroundColor = selectColor
        for i in 0..<2 {
            let button = UIButton(frame: CGRect(x: 24 + CGFloat(i) * (UIScreen.main.bounds.width - 47) / 2, y: 0, width: UIScreen.main.bounds.width / 3, height: 44))
            button.tag = Int(i)
            if i == 1 {
                button.isSelected = true
                underLine.center.x = button.center.x
            }
            button.setTitle("请选择", for: .normal)
            button.setTitleColor(UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1), for: .normal)
            button.setTitleColor(selectColor, for: .selected)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            button.titleLabel?.adjustsFontSizeToFitWidth = true
            button.addTarget(self, action: #selector(onClickTitlebutton(sender:)), for: .touchUpInside)
            buttonArr.append(button)
            titleSV.addSubview(button)
        }
        titleSV.showsVerticalScrollIndicator = false
        titleSV.addSubview(self.underLine)
        titleSV.contentSize = CGSize(width: UIScreen.main.bounds.width, height: 44)
        titleSV.isHidden = true
        self.addSubview(titleSV)
    }
    private func drawTableView() {
        self.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.tableHeaderView = tableViewHeaderView
        tableView.showsVerticalScrollIndicator = false
        tableView.register(YHAddressPickViewTableViewCell.self, forCellReuseIdentifier: YHAddressPickViewTableViewCell.identifier)
        tableView.register(YHAddressPickViewFirstTableViewCell.self, forCellReuseIdentifier: YHAddressPickViewFirstTableViewCell.identifier)
    }
    /// 退出
    @objc private func onClickCancelButton() {
        if self.backOnClickCancel != nil {
            backOnClickCancel!()
        }
    }
    @objc private func onClickHotCity(sender: UIButton) {

        let hotProvince = ["北京市","上海市","广东省","广东省","浙江省","江苏省","江苏省","天津市","湖北省","湖南省","重庆市","四川省"]
        let hotCity = ["北京市","上海市","广州市","深圳市","杭州市","南京市","苏州市","天津市","武汉市","长沙市","重庆市","成都市"]
        let tag = sender.tag
        setHotCityData(province: hotProvince[tag], city: hotCity[tag])
    }
    /// 选择view.type
    @objc private func onClickTitlebutton(sender: UIButton) {
        guard !sender.isSelected else { return }
        switch sender.tag {
        case 0:
            self.tableViewType = .provinces
        case 1:
            self.tableViewType = .city
        default:
            break
        }
    }
    /// 点击热门城市中的城市
    private func setHotCityData(province: String?,city: String?) {
        if let province = province {
           if let provincesModel = self.locationModel?.provincesArray.first(where: { model in
                model.provincesName == province
           }) {
            self.provincesModel = provincesModel
            self.selectedProvince = province
            self.tableViewType = .city
            if let city = city {
              if let cityModel = self.provincesModel?.cityArray.first(where: { model in
                    model.cityName == city
              }) {
                self.cityModel = cityModel
                self.selectedCity = city
              }
            }
           }
        }
        
        let selectLocation = selectedProvince + " " + selectedCity + " " + selectedArea
        if backLocationString != nil {
            backLocationString!(selectLocation,selectedProvince,selectedCity,selectedArea)
        }
    }
    /// 从area.plist获取全部地区数据
    private func initLocationData() {
        guard let dic = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "area", ofType: "plist") ?? "") as? [String:[String]] else {
            return
        }
        locationModel = YHCountryModel(dic: dic)
        dataArray = locationModel?.provincesArray.map({$0.provincesName})
    }
}
// MARK: - tableViewDelegate
extension YHAddressPickView: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (self.dataArray?.count)! + 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier:  YHAddressPickViewFirstTableViewCell.identifier) as? YHAddressPickViewFirstTableViewCell else {
                return YHAddressPickViewFirstTableViewCell()
            }
            cell.label.text = "请选择"
            return cell
        }
        guard let cell = tableView.dequeueReusableCell(withIdentifier:  YHAddressPickViewTableViewCell.identifier) as? YHAddressPickViewTableViewCell else {
            return YHAddressPickViewTableViewCell()
        }
        cell.label.text = self.dataArray?[indexPath.row - 1]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.row != 0 else { return }
        switch tableViewType {
        case .provinces:
            /// 当前为选择省份状态时,保存选中省份,刷新状态为选择城市
            selectedProvince = self.locationModel?.provincesArray[indexPath.row - 1].provincesName ?? ""
            self.provincesModel = self.locationModel?.provincesArray.first(where: {$0.provincesName == selectedProvince})
            self.tableViewType = .city
        case .city:
            /// 当前为选择城市状态时,保存选中城市,刷新状态为选择地区
            selectedCity = (self.provincesModel?.cityArray[indexPath.row - 1])?.cityName ?? ""
            self.cityModel = self.provincesModel?.cityArray.first(where: {$0.cityName == selectedCity})
            let selectLocation = selectedProvince + " " + selectedCity + " " + selectedArea
            if backLocationString != nil {
                backLocationString!(selectLocation,selectedProvince,selectedCity,selectedArea)
            }
        }

    }
}
