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

import UIKit
import AttributedString

enum YHOtherPickerViewType: Int {
    // 按自然顺序递增
    case none = 0
    // 语言能力
    case language
    // 专业技能行业
    case professionalSkill
    // 用人单位性质
    case nature
    // 工作证明文件
    case certificate
    // 行政架构层级
    case structure
    // 职位水平类别
    case level
    // 高管证明文件
    case prove
}


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

class YHOtherPickerView: UIView {
    private var type : YHOtherPickerViewType  = .none
    var arrData : [YHOtherPickerViewItemData] = []
    
    private var selectType:YHFormPickerViewSubType?
    //    private var selectTitle:String? {
    //        didSet {
    //            let type:YHFormPickerViewSubType = getSubType(selectTitle)
    //            selectType = type
    //        }
    //    }
    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.edges.equalToSuperview()
        }
        cancelBtn.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.width.equalTo(60)
        }
        confirmBtn.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.width.equalTo(60)
        }
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize: 16)
        label.text = "请选择"
        return label
    }()
    
    lazy var cancelBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("取消".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(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_R(ofSize: 14)
        btn.setTitleColor(UIColor(hex: 0x4487F9), for: .normal)
        btn.addTarget(self, action: #selector(didClickConfirmButton), for: .touchUpInside)
        return btn
    }()
    
    
    init(type: YHOtherPickerViewType) {
        super.init(frame: UIScreen.main.bounds)
        self.createUI()
        self.type = type
        initDataSource()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func show() {
        //        showSelectType(&selectType)
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    static func show(type:YHOtherPickerViewType, selectType:YHFormPickerViewSubType? = nil,  callBack: @escaping ((YHOtherPickerViewItemData)->Void)) {
        
        let picker = YHOtherPickerView(type: type)
        //                picker.selectType = selectType
        picker.selectBlock = callBack
        
        picker.show()
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    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(16.0, 16.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()
        }
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(KScreenHeight*2/3.0)
        }
        
        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()
        }
    }
    
    @objc func didClickCancelButton() {
        dismiss()
    }
    
    @objc func didClickConfirmButton() {
        if let item = userSelectedItem  {
            selectBlock?(item)
        }
        dismiss()
    }
    
    func showSelectType(_ selectType: inout YHFormPickerViewSubType?) {
        // 处理从外部传入的选中第几行的参数
        // 是否找到选中行数据
        //        var selectIndex:Int = -1
        //        if let selectType = selectType, let arr = dataDict[type], !arr.isEmpty {
        //            for (index, item) in arr.enumerated() {
        //                if selectType.index == item.type.index {
        //                    selectIndex = index
        //                    break
        //                }
        //            }
        //        }
        //
        //        if selectIndex != -1 { // 找到了选择行
        //            pickerView.selectRow(selectIndex, inComponent: 0, animated: true)
        //        } else { // 未找到选中行数据则滚动至第一行
        //            if dataDict[type]?.isEmpty == true { return }
        //            if let arr = dataDict[type], !arr.isEmpty {
        //                let item = arr[0]
        //                selectType = item.type
        //                pickerView.selectRow(0, inComponent: 0, animated: true)
        //            }
        //        }
    }
    
    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 "高管证明文件"
        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, titleForRow row: Int, forComponent component: Int) -> String? {
    //        if 0 <= row && row < arrData.count {
    //            let item :YHOtherPickerViewItemData = arrData[row]
    //            return item.title
    //        }
    //        return ""
    //    }
    
    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:
            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:
            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(hex: 0x4487F9, alpha: 0.06)
            }
            return label
            
        default:
            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(hex: 0x4487F9, alpha: 0.06)
            }
            return label
            
        }
        
        
    }
}

extension YHOtherPickerView {
    func initDataSource() {
        //根据type 构建对应的数据源
        switch type {
        case .language:
            let arr = YHOtherInfoFillViewModel.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 = YHOtherInfoFillViewModel.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 = YHOtherInfoFillViewModel.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 = YHOtherInfoFillViewModel.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 = YHOtherInfoFillViewModel.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 = YHOtherInfoFillViewModel.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 = YHOtherInfoFillViewModel.arrProve
            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
        }
    }
}
