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

import UIKit

// 选择项
class YHFormChoiceItem {
    
    var title:String
    // 是否被选中
    var isSelect:Bool
    
    init(title: String, isSelect: Bool) {
        self.title = title
        self.isSelect = isSelect
    }
}

class YHFormItemDoubleChoiceCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHFormItemDoubleChoiceCell"
    let horizonalGap = 18.0

    private let btnWidth = 70.0
    private let btnHeight = 32.0
    private let titleFont = UIFont.PFSC_R(ofSize: 14)
    private let btnTitleSelectColor = UIColor.brandMainColor
    private let btnTitleDefaultColor = UIColor.mainTextColor
    private let btnBgDefaultColor = UIColor.contentBkgColor
    private let btnBgSelectColor = UIColor.brandMainColor.withAlphaComponent(0.08)
    private let answerBaseTag  = 9527
    
    // 是否必须字段
    var isMust:Bool = false
    var answerBlock:(([YHFormChoiceItem], Int)->Void)?
    // 是否能点击两个按钮
    var enableEdit:Bool = true
    // 不能编辑时的提示语
    var disableEditTips:String?
    
    var title:String? {
        didSet {
            
            var titleStr = ""
            if let title = title, !title.isEmpty {
                let titleStr = (isMust ? ("*"+title) : title)
                let attributes: [NSAttributedString.Key: Any] = [
                    .font: UIFont.PFSC_R(ofSize: 14),
                    .foregroundColor: UIColor.mainTextColor]
                let questionAttrStr = NSMutableAttributedString(string: titleStr, attributes: attributes)
                if isMust {
                    let starRange = NSRange(location: 0, length: 1)
                    questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                }
                
                titleLabel.attributedText = questionAttrStr
            } else {
                titleLabel.attributedText = nil
            }
        }
    }
    
    // 必须传2个item的arr
    var answerArr:[YHFormChoiceItem]? {
        didSet {
            if let answerArr = answerArr, answerArr.count == 2 {
                
                for i in 0...1 {
                    let answerBtn = self.viewWithTag(answerBaseTag+i) as! UIButton
                    let item = answerArr[i]
                    answerBtn.setTitle(item.title, for: .normal)
                    updateAnswerButton(answerBtn, item.isSelect)
                }
            } else {
                // 重置所有答案状态
                for i in 0...1 {
                    let answerBtn = self.viewWithTag(answerBaseTag+i) as! UIButton
                    answerBtn.setTitle("", for: .normal)
                    updateAnswerButton(answerBtn, false)
                }
            }
        }
    }
    
    // 是否隐藏顶部分割线
    var isHiddenTopLine:Bool = false {
        didSet {
            topLine.isHidden = isHiddenTopLine
        }
    }
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .mainTextColor
        label.textAlignment = .left
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.lineBreakMode = .byCharWrapping
        return label
    }()
    
    private lazy var answer1Btn: UIButton = {
        
        let btn = UIButton()
        btn.setTitle("", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 14)
        btn.setTitleColor(btnTitleDefaultColor, for: .normal)
        btn.backgroundColor = btnBgDefaultColor
        btn.layer.cornerRadius = btnHeight/2.0
        btn.layer.masksToBounds = true
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.clear.cgColor
        btn.tag = answerBaseTag
        btn.addTarget(self, action: #selector(didClickResponseBtn(btn:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var answer2Btn: UIButton = {
        let btn = UIButton()
        btn.setTitle("", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 14)
        btn.setTitleColor(btnTitleDefaultColor, for: .normal)
        btn.backgroundColor = btnBgDefaultColor
        btn.layer.cornerRadius = btnHeight/2.0
        btn.layer.masksToBounds = true
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.clear.cgColor
        btn.tag = answerBaseTag+1
        btn.addTarget(self, action: #selector(didClickResponseBtn(btn:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var tipsLabel: UILabel = {
        let label = UILabel()
        label.textColor = .failColor
        label.textAlignment = .left
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.isHidden = true
        return label
    }()
    
    private lazy var topLine:UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()

    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func setupUI() {
        
        self.selectionStyle = .none
        contentView.backgroundColor = .white

        contentView.addSubview(titleLabel)
        contentView.addSubview(answer2Btn)
        contentView.addSubview(answer1Btn)
        contentView.addSubview(tipsLabel)
        contentView.addSubview(topLine)

        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(contentView.snp.top).offset(16)
            make.left.equalToSuperview().offset(horizonalGap)
            make.right.equalTo(answer1Btn.snp.left).offset(-8)
            make.height.greaterThanOrEqualTo(btnHeight)
        }
        
        answer1Btn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: btnWidth, height: btnHeight))
            make.right.equalTo(answer2Btn.snp.left).offset(-8)
            make.top.equalTo(answer2Btn)
        }
        
        answer2Btn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: btnWidth, height: btnHeight))
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(16)
        }
        
        topLine.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(horizonalGap)
            make.right.equalToSuperview().offset(-horizonalGap)
            make.height.equalTo(1.0)
            make.top.equalToSuperview()
        }
        tipsLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(horizonalGap)
            make.right.equalToSuperview().offset(-horizonalGap)
            make.top.equalTo(titleLabel.snp.bottom)
            make.bottom.equalToSuperview().offset(-16).priority(.medium)
        }
        setTips("", isShow: false)
    }
    
    func setTips(_ tips:String?, isShow:Bool) {
        tipsLabel.text = tips
        tipsLabel.isHidden = !isShow
    }
    
    // 更新答案按钮选中状态
    private func updateAnswerButton(_ btn:UIButton, _ isSelect:Bool) {
        btn.layer.borderColor = (isSelect ? btnTitleSelectColor : .clear).cgColor
        btn.setTitleColor((isSelect ? btnTitleSelectColor : btnTitleDefaultColor), for: .normal)
        btn.backgroundColor = (isSelect ? btnBgSelectColor : btnBgDefaultColor)
    }
    
    @objc func didClickResponseBtn(btn: UIButton) {
        
        if !enableEdit {
            if let tips = disableEditTips, !tips.isEmpty {
                YHHUD.flash(message: tips)
            } else {
                YHHUD.flash(message: "不可点击")
            }
            return
        }
        
        let selectIndex = btn.tag-answerBaseTag
        if let resultArr = answerArr, resultArr.count == 2 {
            
            for i in 0...1 {
                let item = resultArr[i]
                item.isSelect = (i == selectIndex)
            }
            answerArr = resultArr
            if let answerBlock = answerBlock {
                answerBlock(resultArr, selectIndex)
            }
        }
    }
}
