//
//  YHSheetPickerView.swift
//  galaxy
//
//  Created by edy on 2024/2/22.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

// 【 用法  Usage】
/*
 
 // (1) 直接传index 此处的index是后台的数值，并非行数
 YHSheetPickerView.show(type: .occupation, selectIndex:0) {
     [weak self] selectItem in
     guard let self = self else { return }
 }
 
 // (2) 直接传字符串值
 YHSheetPickerView.show(type: .occupation, selectTitle:"在职") {
     [weak self] selectItem in
     guard let self = self else { return }
 }
 
 // 如何扩展新类型
  1、YHSheetPickerViewType添加一个新类型
  2、dataSource这个字典中添加新类型对应的数组即可
 */

import UIKit

class YHSheetPickerView: UIView {

    let type: YHSheetPickerViewType
    // 选择的行
    var selectRow:Int = 0
    private var selectBlock:((YHSheetPickerViewItem)->Void)?

    var title: String? {
        didSet {
            titleLabel.text = title
        }
    }
    
    lazy var pickerView:UIPickerView = {
        let view = UIPickerView()
        view.dataSource = self
        view.delegate = self
        return view
    }()
    
    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var topView:UIView = {
        let view = UIView()
        view.addSubview(titleLabel)
        view.addSubview(cancelBtn)
        view.addSubview(confirmBtn)
        view.addSubview(topLineView)
        titleLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        cancelBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(21)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSizeMake(30, 20))
        }
        confirmBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-21)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSizeMake(30, 20))
        }
        topLineView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(21)
            make.right.equalToSuperview().offset(-21)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }

        return view
    }()
    
    lazy var topLineView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#F0F0F0")
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_M(ofSize: 17)
        label.text = "请选择"
        return label
    }()
    
    lazy var cancelBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("取消".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(UIColor.mainTextColor, for: .normal)
        btn.addTarget(self, action: #selector(didClickCancelButton), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    lazy var confirmBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("确定".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(UIColor.brandMainColor, for: .normal)
        btn.addTarget(self, action: #selector(didClickConfirmButton), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(type: YHSheetPickerViewType) {
        self.type = type
        super.init(frame: UIScreen.main.bounds)
        self.createUI()
    }
    
    func show() {
        showSelectRow()
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    func showSelectRow() {
        if let arr = Self.dataSource[type], selectRow < arr.count {
            pickerView.selectRow(selectRow, inComponent: 0, animated: true)

        } else {
            selectRow = 0
            pickerView.selectRow(0, inComponent: 0, animated: true)
        }
    }
    
    static func show(type:YHSheetPickerViewType, selectIndex:Int,  callBack: @escaping ((YHSheetPickerViewItem)->Void)) {
        
        let picker = YHSheetPickerView(type: type)
        picker.selectRow = picker.getRowOfPickerViewItem(index: selectIndex)
        picker.selectBlock = callBack
        picker.show()
    }
    
    static func show(type:YHSheetPickerViewType, selectTitle:String?, callBack: @escaping ((YHSheetPickerViewItem)->Void)) {

        let picker = YHSheetPickerView(type: type)
        picker.selectRow = picker.getRowOfPickerViewItem(title:selectTitle)
        picker.selectBlock = callBack
        picker.show()
    }

    static var dataSource:[YHSheetPickerViewType: [YHSheetPickerViewItem]] =
         [
            // 默认无
            .none:[],
            
            // 学位
            .degree:
                [YHSheetPickerViewItem(title:"学士学位".local, index:1),
                 YHSheetPickerViewItem(title:"硕士学位".local, index:2),
                 YHSheetPickerViewItem(title:"博士学位".local, index:3)
                ],
            
            // 学位2
            .educationDegree:
                [YHSheetPickerViewItem(title:"无学位(专科)".local, index:0),
                 YHSheetPickerViewItem(title:"无学位(本科)".local, index:1),
                 YHSheetPickerViewItem(title:"无学位(硕士)".local, index:2),
                 YHSheetPickerViewItem(title:"无学位(博士)".local, index:3),
                 YHSheetPickerViewItem(title:"学士学位".local, index:4),
                 YHSheetPickerViewItem(title:"硕士学位".local, index:5),
                 YHSheetPickerViewItem(title:"博士学位".local, index:6)
                ],

            
            // 婚姻
            .marriage:
                [YHSheetPickerViewItem(title:"已婚".local, index:1),
                 YHSheetPickerViewItem(title:"未婚".local, index:0),
                 YHSheetPickerViewItem(title:"分居".local, index:2),
                 YHSheetPickerViewItem(title:"离婚".local, index:3),
                 YHSheetPickerViewItem(title:"丧偶".local, index:4),
                ],
    
            // 教育
            .educationStyle:
                [YHSheetPickerViewItem(title:"全日制".local, index:0),
                 YHSheetPickerViewItem(title:"兼读制".local, index:1),
                 YHSheetPickerViewItem(title:"全日制（遥距课程）".local, index:2),
                 YHSheetPickerViewItem(title:"兼读制（遥距课程）".local, index:3),
                 ],
           
            // 职业
            .occupation:
                [YHSheetPickerViewItem(title:"在职".local, index:0),
                 YHSheetPickerViewItem(title:"退休".local, index:1),
                 YHSheetPickerViewItem(title:"无业".local, index:2),
                 YHSheetPickerViewItem(title:"学生".local, index:3),
                 ],
                            
            // 职业2
            .profession:
                [YHSheetPickerViewItem(title:"企业管理者 (高级管理者)".local, index:0),
                 YHSheetPickerViewItem(title:"企业管理者 (包括初、中级层管理者)".local, index:1),
                 YHSheetPickerViewItem(title:"自主创业 (有实际运营的公司)".local, index:2),
                 YHSheetPickerViewItem(title:"普通职员 (办公室/写字楼)".local, index:3),
                 YHSheetPickerViewItem(title:"专业人员 (医生/教师/律师/记者/文体)".local, index:4),
                 YHSheetPickerViewItem(title:"个体经营/承包商".local, index:5),
                 YHSheetPickerViewItem(title:"政府机关干部/公务人员".local, index:6),
                 YHSheetPickerViewItem(title:"在校学生".local, index:7),
                 YHSheetPickerViewItem(title:"家庭主妇".local, index:8),
                 YHSheetPickerViewItem(title:"退休人员".local, index:9),
                 YHSheetPickerViewItem(title:"应届毕业生".local, index:10),
                 YHSheetPickerViewItem(title:"其他".local, index:11),
                ],
                
            // 性别
            .gender:
                [YHSheetPickerViewItem(title:"男".local, index:1),
                 YHSheetPickerViewItem(title:"女".local, index:2),
                ],
            
             // 证件
            .certificate:
                [YHSheetPickerViewItem(title:"护照".local, index:3),
                 YHSheetPickerViewItem(title:"外交护照".local, index:4),
                 YHSheetPickerViewItem(title:"公务护照".local, index:5),
                 YHSheetPickerViewItem(title:"中国发无国籍旅游证件".local, index:6),
                 YHSheetPickerViewItem(title:"旅游通行证".local, index:7),
                 YHSheetPickerViewItem(title:"联合国通行证".local, index:8),
                 YHSheetPickerViewItem(title:"其他无国籍旅行证件".local, index:9),
                 YHSheetPickerViewItem(title:"其他".local, index:10),
                ],
            
            // 在港身份
            .identity:
                [YHSheetPickerViewItem(title:"学生".local, index:0),
                 YHSheetPickerViewItem(title:"就业".local, index:1),
                 YHSheetPickerViewItem(title:"居留".local, index:2),
                 YHSheetPickerViewItem(title:"访问".local, index:3),
                 YHSheetPickerViewItem(title:"其他".local, index:4),
                ],
              
            // 是否拥有学位
            .ownDegree:
                 [YHSheetPickerViewItem(title:"无学位".local, index:0),
                  YHSheetPickerViewItem(title:"有学位".local, index:1),
                ],
                
            // 学位颁发地区
            .degreeLocation:
                [YHSheetPickerViewItem(title:"国内 (颁发)".local, index:1),
                 YHSheetPickerViewItem(title:"国外 (颁发)".local, index:2),
                ],
    
            // 专业证书
            .professionCertificate:
                [YHSheetPickerViewItem(title:"CFA(注册金融分析师)".local, index:0),
                 YHSheetPickerViewItem(title:"CFP(CFP证书是目前世界上权威的权威理财顾问认证项目之一)".local, index:1),
                 YHSheetPickerViewItem(title:"FRM(金融风险管理师)".local, index:2),
                 YHSheetPickerViewItem(title:"FIA(保险精算师)".local, index:3),
                 YHSheetPickerViewItem(title:"CPA(注册会计师)".local, index:4),
                 YHSheetPickerViewItem(title:"CIIA(注册国际投资分析师)".local, index:5),
                 YHSheetPickerViewItem(title:"RFC(财务顾问师)".local, index:6),
                 YHSheetPickerViewItem(title:"ACCA(特许公认会计师)".local, index:7),
                 YHSheetPickerViewItem(title:"CIA(国际注册内部审计师)".local, index:8),
                 YHSheetPickerViewItem(title:"CMA(美国管理会计师)".local, index:9),
                 YHSheetPickerViewItem(title:"CQF(国际数量金融工程认证)".local, index:10),
                 YHSheetPickerViewItem(title:"CIMA(管理会计师考试)".local, index:11),
                 YHSheetPickerViewItem(title:"The Associate Chartered Accountant(英国皇家特许会计师)".local, index:12),
                 YHSheetPickerViewItem(title:"FCA(Fellow Chartered Accountant)".local, index:13),
                ],
                           
            // 学位类型
            .degreeCategory:
                [YHSheetPickerViewItem(title:"会计/金融".local, index:0),
                 YHSheetPickerViewItem(title:"艺术及人文/文学".local, index:1),
                 YHSheetPickerViewItem(title:"工商管理".local, index:2),
                 YHSheetPickerViewItem(title:"经济学".local, index:3),
                 YHSheetPickerViewItem(title:"工程学".local, index:4),
                 YHSheetPickerViewItem(title:"咨询科技/电子及软件工程/数据科学".local, index:5),
                 YHSheetPickerViewItem(title:"法律".local, index:6),
                 YHSheetPickerViewItem(title:"生命科学及医学".local, index:7),
                 YHSheetPickerViewItem(title:"管理学".local, index:8),
                 YHSheetPickerViewItem(title:"理学".local, index:9),
                 YHSheetPickerViewItem(title:"社会科学".local, index:10),
                 YHSheetPickerViewItem(title:"其他".local, index:11),
                ],
        ]
    
    func createUI() {
    
        self.addSubview(blackMaskView)
        self.addSubview(whiteContentView)
        whiteContentView.addSubview(topView)
        whiteContentView.addSubview(pickerView)
        
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect:bounds,byRoundingCorners: corner,cornerRadii:CGSizeMake(8.0, 8.0))
        let layer = CAShapeLayer()
        layer.frame = whiteContentView.bounds
        layer.path = path.cgPath
        whiteContentView.layer.mask = layer
        
        if let title = title {
            titleLabel.text = title
        } else {
            titleLabel.text = getTitle(type: type)
        }
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        var whiteContentHeight = 322.0
        if self.type == .educationDegree
            || self.type == .marriage
            || self.type == .profession
            || self.type == .certificate
            || self.type == .identity
            || self.type == .professionCertificate
            || self.type == .degreeCategory 
        {
            whiteContentHeight = 411.0
        }
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(whiteContentHeight)
        }
        
        topView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(52)
        }
        
        pickerView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
}

extension YHSheetPickerView {
    
    @objc func didClickCancelButton() {
        dismiss()
    }
    
    @objc func didClickConfirmButton() {
        if let selectItem = getPickerViewItem(row:selectRow), let selectBlock = selectBlock {
            selectBlock(selectItem)
            dismiss()
        }
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
}

extension YHSheetPickerView {
    
    func getTitle(type: YHSheetPickerViewType)-> String {
        
        switch type {
        case .none:
            return ""
        case .degree:
            return "选择学位"
        case .educationDegree:
            return "选择学位"
        case .marriage:
            return "选择婚姻状况"
        case .educationStyle:
            return "选择授课形式"
        case .occupation:
            return "选择职业"
        case .gender:
            return "选择性别"
        case .certificate:
            return "选择证件"
        case .identity:
            return "选择在港身份"
        case .ownDegree:
            return "选择是否拥有学位"
        case .degreeLocation:
            return "选择学位"
        case .profession:
            return "选择职业"
        case .professionCertificate:
            return "选择证书名称"
        case .degreeCategory:
            return "选择学位类型"
        }
    }
    
    
    // 返回所在行的数据
    func getPickerViewItem(row:Int) -> YHSheetPickerViewItem? {
        if let arr = Self.dataSource[type] {
            for (index, item) in arr.enumerated() {
                if index == row {
                    return item
                }
            }
        }
        return nil
    }
    
    // 返回对应index的数据所在行
    func getRowOfPickerViewItem(index:Int) -> Int {
        if let arr = Self.dataSource[type] {
            for (row, item) in arr.enumerated() {
                if item.index == index {
                    return row
                }
            }
        }
        return 0
    }
    
    // 返回对应标题的数据所在行
    func getRowOfPickerViewItem(title:String?) -> Int {
        
        guard let title = title else { return 0 }
        if let arr = Self.dataSource[type] {
            for (row, item) in arr.enumerated() {
                if item.title == title {
                    return row
                }
            }
        }
        return 0
    }
    
    // 根据index获取item
    static func getItem(type:YHSheetPickerViewType, index:Int)-> YHSheetPickerViewItem? {
        if let arr = dataSource[type], arr.count > 0 {
            for item in arr {
                if item.index == index {
                    return item
                }
            }
        }
        return nil
    }
    
    // 根据名称获取item
    static func getItem(type:YHSheetPickerViewType, title:String)-> YHSheetPickerViewItem? {
        if let arr = dataSource[type], arr.count > 0 {
            for item in arr {
                if item.title == title {
                    return item
                }
            }
        }
        return nil
    }
}

// MARK: - UIPickerViewDelegate
extension YHSheetPickerView: UIPickerViewDelegate, UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if let arr = Self.dataSource[type], !arr.isEmpty {
            return arr.count
        }
        return 0
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if let arr = Self.dataSource[type] {
            if 0 <= row && row < arr.count {
                let item :YHSheetPickerViewItem = arr[row]
                return item.title
            }
        }
        return ""
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if let arr = Self.dataSource[type] {
            if 0 <= row && row < arr.count {
                let item :YHSheetPickerViewItem = arr[row]
                print(item.title)
                selectRow = row
                //刷新picker，看上面的代理
                pickerView.reloadComponent(component)
            }
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return KScreenWidth - 16*2
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        if self.type == .professionCertificate {
            return 62.0
        }
        return 42.0
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textAlignment = .center
        label.numberOfLines = 2
        label.text = ""
        if let arr = Self.dataSource[type] {
            if 0 <= row && row < arr.count {
                let item :YHSheetPickerViewItem = arr[row]
                label.text = item.title
            }
        }
        if selectRow == row {
            label.font = UIFont.PFSC_M(ofSize: 14)

        } else {
            label.font = UIFont.PFSC_R(ofSize: 14)
        }
            
        // 选中背景色
        if #available(iOS 14.0, *), pickerView.subviews.count > 1 {
           pickerView.subviews[1].backgroundColor = UIColor.brandMainColor6
        }
        return label
    }
}
