//
//  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: 72, width: UIScreen.main.bounds.width, height: 516)
                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: 146, width: UIScreen.main.bounds.width, height: 417)
                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 - 150) / 2, y: 16, width: 150, height: 24))
        label.textColor = UIColor.mainTextColor
        label.text = "选择省市地区"
        label.textAlignment = .center
        label.font = UIFont.PFSC_M(ofSize: 17)
        return label
    }()
    private let rightCancelButton: UIButton = {
        let button = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 43, y: 16, width: 24, height: 24))
        button.setImage(UIImage(named: "address_close"), for: .normal)
        return button
    }()
    private let leftLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 24, y: 72, width: 100, height: 18))
        label.text = "已选择"
        label.textColor = UIColor.mainTextColor
        label.font = UIFont.PFSC_M(ofSize: 14)
        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: 120))
        let label = UILabel(frame: CGRect(x: 24, y: 0, width: 100, height: 18))
        label.textColor = UIColor.mainTextColor
        label.font = UIFont.PFSC_M(ofSize: 14)
        label.text = "热门城市"
        view.addSubview(label)
        for i in 0..<8 {
            let button: UIButton = UIButton(frame: CGRect(x: CGFloat(20 + 86 * (i % 4)), y: CGFloat(28 + 40 * (i / 4)), width: 74, height: 32))
            button.setTitle(hotCityArray[i], for: .normal)
            button.setTitleColor(UIColor.mainTextColor, for: .normal)
            button.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
            button.addTarget(self, action: #selector(onClickHotCity(sender:)), for: .touchUpInside)
            button.layer.cornerRadius = kCornerRadius3
            button.backgroundColor = UIColor.contentBkgColor
            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:72 , width: UIScreen.main.bounds.width, height: 516))

    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)
        let lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(21)
            make.top.equalTo(52)
            make.height.equalTo(1)
            make.right.equalTo(-21)
        }
        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: 92, width: UIScreen.main.bounds.width, height: 44))
//        self.underLine = UIView(frame: CGRect(x: 0, y: 40, width: 30, height: 2))
//        self.underLine.backgroundColor = UIColor.brandMainColor
        for i in 0..<2 {
            let button = UIButton(frame: CGRect(x: 21 + CGFloat(i) * 86, y: 10, width: 74, height: 32))
            button.tag = Int(i)
            button.setTitle("请选择", for: .normal)
            button.setTitleColor(UIColor.mainTextColor, for: .normal)
            button.setTitleColor(UIColor.brandMainColor, for: .selected)
            button.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
            button.titleLabel?.adjustsFontSizeToFitWidth = true
            button.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
            button.setBackgroundColor(color: UIColor.brandMainColor.withAlphaComponent(0.08), forState: .selected)
            button.layer.borderColor = UIColor.brandMainColor.cgColor
            button.layer.borderWidth = 0
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(onClickTitlebutton(sender:)), for: .touchUpInside)
            if i == 1 {
                button.isSelected = true
                button.layer.borderWidth = 1
//                underLine.center.x = button.center.x
            }
            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 {
            locationModel = nil
            dataArray = []
            
            return
        }
        locationModel = YHCountryModel(dic: dic)
        if let model = locationModel {
            dataArray = model.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)
            }
        }

    }
}
