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

import UIKit
import AttributedString
import IQKeyboardManagerSwift

struct YHOtherPickerViewItemData {
    let title: String
    let subTitle: String
    let index: String
}

class YHOtherPickerView: UIView {
    private var type: YHOtherPickerViewType  = .none
    var arrData: [YHOtherPickerViewItemData] = []
    
    var selectTitle: String = "" {
        didSet {
            var selectIndex = 0
            for i in 0..<arrData.count {
                let model = arrData[i]
                if model.title == selectTitle {
                    selectIndex = i
                }
                if model.index == selectTitle {
                    selectIndex = i
                }
            }
            pickerView.selectRow(selectIndex, inComponent: 0, animated: false)
            userSelectedItem = arrData[selectIndex]
            pickerView.reloadAllComponents()
        }
    }
    private var selectBlock: ((YHOtherPickerViewItemData) -> Void)? // 回调
    private var userSelectedItem: YHOtherPickerViewItemData? // 用户选择的item
    
    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)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(kMargin)
            make.height.equalTo(24)
            make.centerX.equalToSuperview()
        }
        cancelBtn.snp.makeConstraints { make in
            make.left.equalTo(kMargin)
            make.width.height.equalTo(44)
            make.centerY.equalTo(titleLabel.snp.centerY)
        }
        cancelBtn.titleLabel?.textAlignment = .left
        
        confirmBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-kMargin)
            make.width.height.equalTo(44)
            make.centerY.equalTo(titleLabel.snp.centerY)
        }
        confirmBtn.titleLabel?.textAlignment = .right
        
        let line = UIView()
        line.backgroundColor = .separatorColor
        view.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalTo(21)
            make.right.equalTo(-21)
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
        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)
        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)
        return btn
    }()
    
    init(type: YHOtherPickerViewType, _ dataSource: [YHOtherPickerViewItemData] = []) {
        super.init(frame: UIScreen.main.bounds)
        self.createUI()
        self.arrData = dataSource
        self.type = type
        initDataSource()
        
        if arrData.count > 0 {
            userSelectedItem = arrData[0]
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    static func show(type: YHOtherPickerViewType, selectTitle: String = "", _ dataSource: [YHOtherPickerViewItemData] = [], callBack: @escaping ((YHOtherPickerViewItemData) -> Void)) {
        
        IQKeyboardManager.shared.resignFirstResponder()
        
        let picker = YHOtherPickerView(type: type, dataSource)
        picker.selectBlock = callBack
        picker.show()
        picker.selectTitle = selectTitle
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    func createUI() {
        
        addSubview(blackMaskView)
        addSubview(whiteContentView)
        whiteContentView.addSubview(topView)
        whiteContentView.addSubview(pickerView)
        
        if let title = title {
            titleLabel.text = title
        } else {
            titleLabel.text = getTitle(type: type)
        }
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(412)
        }
        
        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()
        }
        
        whiteContentView.layoutIfNeeded()
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: kCornerRadius6, height: kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = whiteContentView.bounds
        layer.path = path.cgPath
        whiteContentView.layer.mask = layer
    }
    
    @objc func didClickCancelButton() {
        dismiss()
    }
    
    @objc func didClickConfirmButton() {
        let index = pickerView.selectedRow(inComponent: 0)
        userSelectedItem = arrData[index]
        if let item = userSelectedItem {
            selectBlock?(item)
        }
        dismiss()
    }
    
    func getTitle(type: YHOtherPickerViewType) -> String {
        switch type {
        case .language:
            return "选择语言能力"
        case .professionalSkill:
            return "选择专业技能行业"
        case .nature:
            return "用人单位性质"
        case .certificate:
            return "工作证明"
        case .structure:
            return "行政架构层级"
        case .level:
            return "职位水平类别"
        case .prove:
            return "高管证明文件"
        case .idType:
            return "选择证件类别"
        case .travelIdType:
            return "选择证件类别"
        case .sex:
            return "选择性别"
        case .marry:
            return "选择婚姻状况"
        case .constellation:
            return "选择星座"
        case .selectAddress:
            return "选择国家地区"
        case .field:
            return "选择经验领域"
        case .myCompany:
            return "选择可提供的在职公司"
        case .position:
            return "选择职位界别"
        default:
            return "请选择"
        }
    }
}

extension YHOtherPickerView: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return arrData.count
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if 0 <= row && row < arrData.count {
            let item: YHOtherPickerViewItemData = arrData[row]
            print(item)
            
            userSelectedItem = item
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        
        switch type {
        case .nature, .certificate, .structure, .level, .prove, .idType, .sex, .marry, .constellation, .field, .myCompany, .position:
            return 50
        default:
            return 70
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        
        switch type {
        case  .nature, .certificate, .structure, .level, .prove, .idType, .travelIdType, .sex, .marry, .constellation, .selectAddress, .field, .myCompany, .position:
            let label = UILabel()
            label.textColor = UIColor.mainTextColor
            label.font = UIFont.PFSC_M(ofSize: 14)
            label.textAlignment = .center
            let item: YHOtherPickerViewItemData = arrData[row]
            let a: ASAttributedString = .init(NSAttributedString(string: item.title), .font(UIFont.PFSC_M(ofSize: 14)), .foreground(UIColor.mainTextColor))
            label.attributed.text = a
            
            // 选中背景色
            if #available(iOS 14.0, *), pickerView.subviews.count > 1 {
                pickerView.subviews[1].backgroundColor = UIColor.brandMainColor6
            }
            return label
            
        default:
            let view = UIView()
            let label = UILabel()
            label.textColor = UIColor.mainTextColor
            label.font = UIFont.PFSC_M(ofSize: 14)
            label.numberOfLines = 0
            if 0 <= row && row < arrData.count {
                let item: YHOtherPickerViewItemData = arrData[row]
                if item.subTitle.count > 0 {
                    let a: ASAttributedString = .init(NSAttributedString(string: (item.title + "\n")), .font(UIFont.PFSC_M(ofSize: 14)), .foreground(UIColor.mainTextColor))
                    let b: ASAttributedString = .init(NSAttributedString(string: item.subTitle), .font(UIFont.PFSC_R(ofSize: 11)), .foreground(UIColor.labelTextColor2))
                    label.attributed.text = a + b
                    
                } else {
                    let a: ASAttributedString = .init(NSAttributedString(string: item.title), .font(UIFont.PFSC_M(ofSize: 14)), .foreground(UIColor.mainTextColor))
                    label.attributed.text = a
                }
            }
            
            // 选中背景色
            if #available(iOS 14.0, *), pickerView.subviews.count > 1 {
                pickerView.subviews[1].backgroundColor = UIColor.brandMainColor6
            }
            view.addSubview(label)
            label.snp.makeConstraints { make in
                make.top.bottom.equalToSuperview()
                make.left.equalTo(16)
                make.right.equalTo(-16)
            }
            return view
            
        }
        
    }
}

extension YHOtherPickerView {
    func initDataSource() {
        // 根据type 构建对应的数据源
        switch type {
        case .language:
            let arr = YHConstantArrayData.arrLanguage
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: item["dec"] ?? "-", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
            return
        case .professionalSkill:
            
            let arr = YHConstantArrayData.arrSkill
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: item["dec"] ?? "-", index: item["value"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
            
            return
        case .nature:
            let arr = YHConstantArrayData.arrNature
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .certificate:
            let arr = YHConstantArrayData.arrCertificate
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .structure:
            let arr = YHConstantArrayData.arrStructure
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .level:
            let arr = YHConstantArrayData.arrLevel
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .prove:
            let arr = YHConstantArrayData.arrProve
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .idType:
            let arr = YHConstantArrayData.arrIdType
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .travelIdType:
            let arr = YHConstantArrayData.arrTravelIdType
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .sex:
            let arr = YHConstantArrayData.arrSex
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .marry:
            let arr = YHConstantArrayData.arrMarry
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .constellation:
            let arr = YHConstantArrayData.arrDegreeConstellation
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .selectAddress:
            let arr = YHConstantArrayData.arrSelectAddress
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .field:
            let arr = YHConstantArrayData.arrSelectField
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        case .position:
            let arr = YHConstantArrayData.arrposition
            arrData.removeAll()
            arr.forEach { item in
                let model = YHOtherPickerViewItemData(title: item["title"] ?? "-", subTitle: "", index: item["id"] ?? "-")
                arrData.append(model)
            }
            title = getTitle(type: type)
        default:
            return
        }
    }
}
