//
//  YHWorkExperienceCompanySelectIView.swift
//  galaxy
//
//  Created by EDY on 2024/11/18.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHWorkExperienceCompanySelectView: UIView {
    private var selectBlock: (() -> Void)? // 回调

    var centerView: UIView!
    var titleLabel: UILabel!
    var closeButton: UIButton!
    var sureButton: UIButton!
    var tableView: UITableView!
    var viewModel = YHWorkExperienceCompanyViewModel()
    var orderId: Int = 0
    var workId: Int = 0 {
        didSet {
            getData()
        }
    }
    var model: YHWorkExperienceCompanyModel = YHWorkExperienceCompanyModel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.5, alpha: 0.1)
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.delegate = self
        addGestureRecognizer(tap)
        setView()
    }
    
    func getData() {
        viewModel.requestWorkQuestionDetail(workId, orderId) {[weak self] _, _ in
            guard let self = self else { return }
            self.model = viewModel.model
            self.tableView.reloadData()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setView() {
        backgroundColor = UIColor(hex: 0x000000, alpha: 0.5)
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(724)
        }
        
        titleLabel = {
            let label = UILabel()
            label.text = "公司基本情况"
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.textAlignment = .center
            label.text = "公司基本情况"
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.height.equalTo(24)
            make.width.equalTo(200)
            make.centerX.equalToSuperview()
        }
        
        closeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "my_cer_sheet_close"), for: .normal)
            button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.height.width.equalTo(24)
            make.top.equalTo(16)
        }
        
        sureButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("确定", for: .normal)
            button.setTitleColor(UIColor.white, for: .normal)
            button.backgroundColor = UIColor.brandMainColor
            button.layer.cornerRadius = 3
            button.addTarget(self, action: #selector(sure), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(sureButton)
        sureButton.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.height.equalTo(48)
            make.left.equalTo(16)
            make.bottom.equalTo(-42)
        }
                
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.estimatedSectionHeaderHeight = 14
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .contentBkgColor
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHCompanySelectFileCell.self)
            tableView.register(cellWithClass: YHCompanyReasonFileCell.self)
            return tableView
        }()
        centerView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(53)
            make.bottom.equalTo(-98)
            make.left.right.equalToSuperview()
        }
        
        centerView.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 = centerView.bounds
        layer.path = path.cgPath
        centerView.layer.mask = layer
    }
    
    @objc private func handleTap(_ sender: AnyObject?) {
        dismiss()
    }
    
    static func show(workId: Int, orderId: Int, callBack: @escaping (() -> Void)) {
        let view = YHWorkExperienceCompanySelectView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.orderId = orderId
        view.workId = workId
        view.selectBlock = callBack
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
    
    @objc func dismiss() {
        removeFromSuperview()
    }
    
    @objc func sure() {
        if canNext() {
            model.order_id = orderId
            model.work_id = workId
            viewModel.saveWorkQuestion(model: model) {[weak self] _, _ in
                guard let self = self else { return }
                self.selectBlock?()
                dismiss()
            }
        } else {
            YHHUD.flash(message: "请完善公司基本情况")
        }
    }
    
    func canNext() -> Bool {
        guard model.is_ipo_company != 0 else { return false}
        if model.is_ipo_company == 1 {
            guard model.has_ipo_company_equity != 0 else { return false }
            if model.has_ipo_company_equity == 1 {
                guard model.has_ipo_sales_reached != 0 else { return false }
                if model.has_ipo_sales_reached == 1 {
                    guard model.company_location != "" else { return false }
                    guard model.has_provide_certificate != 0 else { return false }
                } else {
                    guard model.has_provide_certificate != 0 else { return false }
                }
            }
        } else {
            guard model.has_company_equity != 0 else { return false }
            if model.has_company_equity == 1 {
                guard model.has_sales_reached != 0 else { return false }
                if model.has_sales_reached == 1 {
                    guard model.company_location != "" else { return false }
                    guard model.has_provide_certificate != 0 else { return false }
                }
            }
        }
        return true
    }
}

extension YHWorkExperienceCompanySelectView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view == self {
            return true
        }
        return false
    }
}

extension YHWorkExperienceCompanySelectView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if model.company_location.count != 0 || (model.is_ipo_company == 1 && model.has_ipo_company_equity == 1 && model.has_ipo_sales_reached == 2 ) {
            return 2
        }
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHCompanyReasonFileCell.self)
            cell.model = model
            cell.selectBlock = { [weak self] model in
                guard let self = self else { return }
                self.model = model
                self.tableView.reloadData()
            }
            return cell
        }
        let cell = tableView.dequeueReusableCell(withClass: YHCompanySelectFileCell.self)
        cell.model = model
        cell.selectBlock = { [weak self] model in
            guard let self = self else { return }
            self.model = model
            self.tableView.reloadData()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 14))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 14
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

class YHCompanySelectFileCell: UITableViewCell {
    
    typealias SelectBlock = (_ select: YHWorkExperienceCompanyModel) -> Void
    var selectBlock: SelectBlock?
    var selectItem: [Int] = [] {
        didSet {
            updateAllViews()
        }
    }
    var centerView: UIView!
    var titleLabel: UILabel!
    var subTitleLabel: UILabel!
    var mainItemView: UIView!
    var model: YHWorkExperienceCompanyModel = YHWorkExperienceCompanyModel() {
        didSet {
            var i = 0
            var temp = 5
            for item in dataSource {
                if item == model.company_location {
                    temp = i
                }
                i += 1
            }
            selectItem = [temp]
        }
    }
    var dataSource: [String] = ["内地", "香港", "澳门", "境外"]
    
    var messageDataSource: [String] = ["公司是否为上市公司", "您目前是否拥有此公司10%以上股权", "您目前是否拥有此公司50%以上股权", "公司全年盈利达港币 500 万元或以上(或等值外币）", "请选择您的公司所在地："]

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        backgroundColor = .clear
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius6
            return view
        }()
        contentView.addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.bottom.equalToSuperview()
        }
        
        titleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.text = "主申请人公司"
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(16)
            make.height.equalTo(20)
            make.right.equalTo(-18)
        }
        
        mainItemView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        centerView.addSubview(mainItemView)
        mainItemView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-16)
            make.top.equalTo(52)
        }
        
    }
    
    // swiftlint:disable function_body_length
    // swiftlint:disable cyclomatic_complexity
    func updateAllViews() {
        mainItemView.removeSubviews()
        for j in 0..<messageDataSource.count {
            let lineView = {
                let label = UIView()
                label.backgroundColor = UIColor.separatorColor
                return label
            }()
            centerView.addSubview(lineView)
            lineView.snp.makeConstraints { make in
                make.height.equalTo(1)
                make.left.equalTo(18)
                make.right.equalTo(-18)
                if j == 0 {
                    make.top.equalTo(52)
                } else {
                    let view = mainItemView.viewWithTag(2000 + j - 1)
                    make.top.equalTo(view?.snp.bottom ?? mainItemView.snp.bottom).offset(15)
                }
            }
            let titleLabel = {
                let label = UILabel()
//                label.attributed.text = dataSource?[i]
                label.numberOfLines = 0
                let str = "*" + messageDataSource[j]
                let attributes: [NSAttributedString.Key: Any] = [
                    .font: UIFont.PFSC_R(ofSize: 14),
                    .foregroundColor: UIColor(hex: 0xd5dad1)
                ]
                let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                let starRange = NSRange(location: 0, length: 1)
                questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                label.attributedText = questionAttrStr
                label.tag = 2000 + j
                return label
            }()
            mainItemView.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { make in
                make.top.equalTo(lineView.snp.bottom).offset(15)
                make.left.equalTo(18)
                make.width.equalTo(106)
                if j == 4 {
                    make.width.equalTo(400)
                }
            }
            
            if j == 4 {
                for i in 0..<dataSource.count {
                    let bgviewButton = {
                        let view = UIButton()
                        view.backgroundColor = UIColor.contentBkgColor
                        view.layer.cornerRadius = 3
                        view.layer.borderColor = UIColor.brandMainColor.cgColor
                        view.addTarget(self, action: #selector(agreeClick(sender:)), for: .touchUpInside)
                        view.tag = 20000 + i
                        return view
                    }()
                    mainItemView.addSubview(bgviewButton)
                    
                    let agreeButton = {
                        let button = UIImageView()
                        button.image = UIImage(named: "service_privacy_disagree_glay")
                        button.tag = 10000 + i
                        if selectItem.contains(i) {
                            button.image = UIImage(named: "service_privacy_agree")
                        } else {
                            button.image = UIImage(named: "service_privacy_disagree_glay")
                        }
                        button.isUserInteractionEnabled = false
                        
                        return button
                    }()
                    mainItemView.addSubview(agreeButton)
                    agreeButton.snp.makeConstraints { make in
                        if i == 0 {
                            make.top.equalTo(titleLabel.snp.bottom).offset(32)
                        } else {
                            let view = mainItemView.viewWithTag(1000 + i - 1)
                            make.top.equalTo(view?.snp.bottom ?? mainItemView.snp.bottom).offset(48)
                        }
                        make.left.equalTo(34)
                        make.height.equalTo(13)
                        make.width.equalTo(13)
                    }
                    
                    let subTitleLabel = {
                        let label = UILabel()
                        label.text = dataSource[i]
                        label.numberOfLines = 0
                        label.tag = 1000 + i
                        label.textColor = UIColor(hex: 0xd5dad1)
                        label.font = UIFont.PFSC_R(ofSize: 14)
                        label.isUserInteractionEnabled = false
                        return label
                    }()
                    mainItemView.addSubview(subTitleLabel)
                    subTitleLabel.snp.makeConstraints { make in
                        make.top.equalTo(agreeButton.snp.top).offset(-3)
                        make.left.equalTo(56)
                        make.right.equalTo(-35)
                        if i == (dataSource.count) - 1 {
                            make.bottom.equalToSuperview().offset(-16)
                        }
                    }
                    
                    bgviewButton.snp.makeConstraints { make in
                        make.top.equalTo(subTitleLabel.snp.top).offset(-16)
                        make.bottom.equalTo(subTitleLabel.snp.bottom).offset(16)
                        make.left.equalTo(18)
                        make.right.equalTo(-18)
                    }
                    
                    if (model.has_ipo_company_equity == 1 && model.is_ipo_company == 1 && model.has_ipo_sales_reached == 1) || (model.has_company_equity == 1 && model.is_ipo_company == 2 && model.has_sales_reached == 1) {
                        let str = "*" + messageDataSource[j]
                        let attributes: [NSAttributedString.Key: Any] = [
                            .font: UIFont.PFSC_R(ofSize: 14),
                            .foregroundColor: UIColor.mainTextColor
                        ]
                        let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                        let starRange = NSRange(location: 0, length: 1)
                        questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                        titleLabel.attributedText = questionAttrStr
                        if selectItem.contains(i) {
                            bgviewButton.layer.borderWidth = 1
                            bgviewButton.backgroundColor = UIColor(hex: 0xebf0f9)
                            agreeButton.image = UIImage(named: "service_privacy_agree")
                            subTitleLabel.textColor = UIColor.mainTextColor
                        } else {
                            bgviewButton.layer.borderWidth = 0
                            bgviewButton.backgroundColor = UIColor.contentBkgColor
                            agreeButton.image = UIImage(named: "service_privacy_disagree_glay")
                            subTitleLabel.textColor = UIColor.mainTextColor
                        }
                    }
                }
            } else {
                let rightButton = {
                    let button = UIButton(type: .custom)
                    button.setTitleColor(UIColor.brandMainColor, for: .selected)
                    button.setTitleColor(UIColor(hex: 0xd5dad1), for: .normal)
                    button.setBackgroundColor(color: UIColor.brandMainColor.withAlphaComponent(0.08), forState: .selected)
                    button.setBackgroundColor(color: UIColor(hex: 0xf5f6f8), forState: .normal)
                    button.setTitle("否", for: .normal)
                    button.layer.cornerRadius = 16
                    button.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
                    button.layer.borderColor = UIColor.brandMainColor.cgColor
                    button.addTarget(self, action: #selector(rightClick(sender:)), for: .touchUpInside)
                    button.tag = 3000 + j
                    return button
                }()
                mainItemView.addSubview(rightButton)
                rightButton.snp.makeConstraints { make in
                    make.right.equalTo(-18)
                    make.centerY.equalTo(titleLabel.snp.centerY)
                    make.height.equalTo(32)
                    make.width.equalTo(74)
                }
                
                let leftButton = {
                    let button = UIButton(type: .custom)
                    button.setBackgroundColor(color: UIColor.brandMainColor.withAlphaComponent(0.08), forState: .selected)
                    button.setBackgroundColor(color: UIColor(hex: 0xf5f6f8), forState: .normal)
                    button.setTitleColor(UIColor.brandMainColor, for: .selected)
                    button.setTitleColor(UIColor(hex: 0xd5dad1), for: .normal)
                    button.layer.cornerRadius = 16
                    button.setTitle("是", for: .normal)
                    button.layer.borderColor = UIColor.brandMainColor.cgColor
                    button.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
                    button.addTarget(self, action: #selector(leftClick(sender:)), for: .touchUpInside)
                    button.tag = 4000 + j
                    return button
                }()
                mainItemView.addSubview(leftButton)
                leftButton.snp.makeConstraints { make in
                    make.right.equalTo(rightButton.snp.left).offset(-12)
                    make.centerY.equalTo(titleLabel.snp.centerY)
                    make.height.equalTo(32)
                    make.width.equalTo(74)
                }
                // 数据源刷新
                if j == 0 {
                    let str = "*" + messageDataSource[j]
                    let attributes: [NSAttributedString.Key: Any] = [
                        .font: UIFont.PFSC_R(ofSize: 14),
                        .foregroundColor: UIColor.mainTextColor
                    ]
                    let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                    let starRange = NSRange(location: 0, length: 1)
                    questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                    titleLabel.attributedText = questionAttrStr
                    leftButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                    leftButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                    rightButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                    rightButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                    if model.is_ipo_company == 0 {
                        leftButton.isSelected = false
                        rightButton.isSelected = false
                        leftButton.layer.borderWidth = 0
                        rightButton.layer.borderWidth = 0
                    }
                    if model.is_ipo_company == 1 {
                        leftButton.isSelected = true
                        rightButton.isSelected = false
                        leftButton.layer.borderWidth = 1
                        rightButton.layer.borderWidth = 0
                    }
                    if model.is_ipo_company == 2 {
                        rightButton.isSelected = true
                        leftButton.isSelected = false
                        leftButton.layer.borderWidth = 0
                        rightButton.layer.borderWidth = 1
                    }
                }
                if j == 1 {
                    if model.is_ipo_company == 1 {
                        let str = "*" + messageDataSource[j]
                        let attributes: [NSAttributedString.Key: Any] = [
                            .font: UIFont.PFSC_R(ofSize: 14),
                            .foregroundColor: UIColor.mainTextColor
                        ]
                        let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                        let starRange = NSRange(location: 0, length: 1)
                        questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                        titleLabel.attributedText = questionAttrStr
                        leftButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                        leftButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                        rightButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                        rightButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                        if model.has_ipo_company_equity == 0 {
                            leftButton.isSelected = false
                            rightButton.isSelected = false
                            leftButton.layer.borderWidth = 0
                            rightButton.layer.borderWidth = 0
                        }
                        if model.has_ipo_company_equity == 1 {
                            leftButton.isSelected = true
                            rightButton.isSelected = false
                            leftButton.layer.borderWidth = 1
                            rightButton.layer.borderWidth = 0
                        }
                        if model.has_ipo_company_equity == 2 {
                            rightButton.isSelected = true
                            leftButton.isSelected = false
                            leftButton.layer.borderWidth = 0
                            rightButton.layer.borderWidth = 1
                        }
                    }
                }
                if j == 2 {
                    if model.is_ipo_company == 2 {
                        let str = "*" + messageDataSource[j]
                        let attributes: [NSAttributedString.Key: Any] = [
                            .font: UIFont.PFSC_R(ofSize: 14),
                            .foregroundColor: UIColor.mainTextColor
                        ]
                        let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                        let starRange = NSRange(location: 0, length: 1)
                        questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                        titleLabel.attributedText = questionAttrStr
                        leftButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                        leftButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                        rightButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                        rightButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                        if model.has_company_equity == 0 {
                            leftButton.isSelected = false
                            rightButton.isSelected = false
                            leftButton.layer.borderWidth = 0
                            rightButton.layer.borderWidth = 0
                        }
                        if model.has_company_equity == 1 {
                            leftButton.isSelected = true
                            rightButton.isSelected = false
                            leftButton.layer.borderWidth = 1
                            rightButton.layer.borderWidth = 0
                        }
                        if model.has_company_equity == 2 {
                            rightButton.isSelected = true
                            leftButton.isSelected = false
                            leftButton.layer.borderWidth = 0
                            rightButton.layer.borderWidth = 1
                        }
                    }
                }
                if j == 3 {
                    if model.is_ipo_company == 1 && model.has_ipo_company_equity == 1 {
                        let str = "*" + messageDataSource[j]
                        let attributes: [NSAttributedString.Key: Any] = [
                            .font: UIFont.PFSC_R(ofSize: 14),
                            .foregroundColor: UIColor.mainTextColor
                        ]
                        let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                        let starRange = NSRange(location: 0, length: 1)
                        questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                        titleLabel.attributedText = questionAttrStr
                        leftButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                        leftButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                        rightButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                        rightButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                        if model.has_ipo_sales_reached == 0 {
                            leftButton.isSelected = false
                            rightButton.isSelected = false
                            leftButton.layer.borderWidth = 0
                            rightButton.layer.borderWidth = 0
                        }
                        if model.has_ipo_sales_reached == 1 {
                            leftButton.isSelected = true
                            rightButton.isSelected = false
                            leftButton.layer.borderWidth = 1
                            rightButton.layer.borderWidth = 0
                        }
                        if model.has_ipo_sales_reached == 2 {
                            rightButton.isSelected = true
                            leftButton.isSelected = false
                            leftButton.layer.borderWidth = 0
                            rightButton.layer.borderWidth = 1
                        }
                    }
                    if model.is_ipo_company == 2 && model.has_company_equity == 1 {
                        let str = "*" + messageDataSource[j]
                        let attributes: [NSAttributedString.Key: Any] = [
                            .font: UIFont.PFSC_R(ofSize: 14),
                            .foregroundColor: UIColor.mainTextColor
                        ]
                        let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                        let starRange = NSRange(location: 0, length: 1)
                        questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                        titleLabel.attributedText = questionAttrStr
                        leftButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                        leftButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                        rightButton.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                        rightButton.setTitleColor(UIColor.mainTextColor, for: .normal)
                        if model.has_sales_reached == 0 {
                            leftButton.isSelected = false
                            rightButton.isSelected = false
                            leftButton.layer.borderWidth = 0
                            rightButton.layer.borderWidth = 0
                        }
                        if model.has_sales_reached == 1 {
                            leftButton.isSelected = true
                            rightButton.isSelected = false
                            leftButton.layer.borderWidth = 1
                            rightButton.layer.borderWidth = 0
                        }
                        if model.has_sales_reached == 2 {
                            rightButton.isSelected = true
                            leftButton.isSelected = false
                            leftButton.layer.borderWidth = 0
                            rightButton.layer.borderWidth = 1
                        }
                    }
                }
            }
        }
    }
    // swiftlint:enable function_body_length
    // swiftlint:enable cyclomatic_complexity
    
    @objc func agreeClick(sender: UIButton) {
        if (model.has_ipo_company_equity == 1 && model.is_ipo_company == 1 && model.has_ipo_sales_reached == 1)||(model.has_company_equity == 1 && model.is_ipo_company == 2 && model.has_sales_reached == 1) {
            selectItem.removeAll()
            selectItem.append(sender.tag - 20000)
            sender.isSelected = !sender.isSelected
            for i in 0..<(dataSource.count) {
                if i == sender.tag - 20000 {
                    let view = mainItemView.viewWithTag(i + 20000)
                    view?.layer.borderWidth = 1
                    view?.backgroundColor = UIColor(hex: 0xebf0f9)
                    guard let subview = mainItemView.viewWithTag(i + 10000) as? UIImageView else { return }
                    subview.image = UIImage(named: "login_privacy_agree")
                } else {
                    let view = mainItemView.viewWithTag(i + 20000)
                    view?.layer.borderWidth = 0
                    view?.backgroundColor = UIColor.contentBkgColor
                    guard let subview = mainItemView.viewWithTag(i + 10000) as? UIImageView else { return }
                    subview.image = UIImage(named: "login_privacy_disagree_glay")
                }
            }
            var tempModel = YHWorkExperienceCompanyModel()
            tempModel = model
            tempModel.company_location = dataSource[sender.tag - 20000]
            if let block = selectBlock {
                block(tempModel)
            }
        }
    }
    
    @objc func leftClick(sender: UIButton) {
        let number = sender.tag - 4000
        var tempModel = YHWorkExperienceCompanyModel()
        if number == 0 {
            tempModel.is_ipo_company = 1
        } else if number == 1 && model.is_ipo_company == 1 {
            tempModel.has_ipo_company_equity = 1
            tempModel.is_ipo_company = 1
        } else if number == 2 && model.is_ipo_company == 2 {
            tempModel.has_company_equity = 1
            tempModel.is_ipo_company = 2
        } else if number == 3 && (model.is_ipo_company == 1 && model.has_ipo_company_equity == 1) {
            tempModel.has_ipo_sales_reached = 1
            tempModel.is_ipo_company = 1
            tempModel.has_ipo_company_equity = 1
        } else if number == 3 && (model.is_ipo_company == 2 && model.has_company_equity == 1) {
            tempModel.has_sales_reached = 1
            tempModel.is_ipo_company = 2
            tempModel.has_company_equity = 1
        } else {
            return
        }
        tempModel.company_location = ""
        tempModel.has_provide_certificate = 0
        selectItem.removeAll()
        if let block = selectBlock {
            block(tempModel)
        }
    }
    
    @objc func rightClick(sender: UIButton) {
        let number = sender.tag - 3000
        var tempModel = YHWorkExperienceCompanyModel()
        if number == 0 {
            tempModel.is_ipo_company = 2
        } else if number == 1 && model.is_ipo_company == 1 {
            tempModel.has_ipo_company_equity = 2
            tempModel.is_ipo_company = 1
        } else if number == 2 && model.is_ipo_company == 2 {
            tempModel.has_company_equity = 2
            tempModel.is_ipo_company = 2
        } else if number == 3 && (model.is_ipo_company == 1 && model.has_ipo_company_equity == 1) {
            tempModel.has_ipo_sales_reached = 2
            tempModel.is_ipo_company = 1
            tempModel.has_ipo_company_equity = 1
        } else if number == 3 && (model.is_ipo_company == 2 && model.has_company_equity == 1) {
            tempModel.has_sales_reached = 2
            tempModel.is_ipo_company = 2
            tempModel.has_company_equity = 1
        } else {
            return
        }
        tempModel.company_location = ""
        tempModel.has_provide_certificate = 0
        selectItem.removeAll()
        if let block = selectBlock {
            block(tempModel)
        }
    }
}

class YHCompanyReasonFileCell: UITableViewCell {
    
    typealias SelectBlock = (_ model: YHWorkExperienceCompanyModel) -> Void
    var selectBlock: SelectBlock?
    var selectItem: [Int] = []
    var centerView: UIView!
    var titleLabel: UILabel!
    var subTitleLabel: UILabel!
    var mainItemView: UIView!
    var alertLabel: UILabel!
    var dataSource: [String] = ["验资报告", "审计报告", "绝对实益拥有人声明书", "企业所得税月(季)度预缴纳税申报表(A类)（前4个季度/前12个月）", "企业所得税完税证明(表格式)", "企业所得税年度纳税申报表(A类) (近一年度)", "工作证明"]
    var model: YHWorkExperienceCompanyModel? {
        didSet {
            if model?.company_location == "内地" {
                dataSource = ["验资报告", "审计报告", "绝对实益拥有人声明书", "企业所得税月(季)度预缴纳税申报表(A类)（前4个季度/前12个月）", "企业所得税完税证明(表格式)", "企业所得税年度纳税申报表(A类) (近一年度)", "工作证明"]
            } else if model?.company_location == "香港" {
                dataSource = ["周年申报表", "审计报告", "利得税申请表", "利得税缴纳通知书", "缴税凭证", "绝对实益拥有人声明书", "工作签证", "工作证明"]
            } else if model?.company_location == "澳门" {
                dataSource = ["商业登记证明", "审计报告", "所得补充税B组──收益申报书（M1）", "所得补充税—收益评定通知书（M5）", "缴税凭证", "绝对实益拥有人声明书", "工作签证", "工作证明"]
            } else if model?.company_location == "境外" {
                dataSource = ["财务报表", "合法纳税及完税证明", "公司所有权官方证明文件", "工作签证", "工作证明"]
            } else {
                dataSource = ["年报（近一年）", "上市证明（证券交易所/百度股市通截图等）", "持股证明文件（周年申报表/工商备案的公司章程/国家企业信用信息公示报告/上市公司定期公告等）"]
            }
            updateAllViews()
        }
    }
    var messageDataSource: [String] = ["您是否可以提供以下所有证明文件"]

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        backgroundColor = .clear
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius6
            return view
        }()
        contentView.addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.bottom.equalToSuperview()
        }
        
        titleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.text = "证件提供确认"
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(16)
            make.height.equalTo(20)
            make.right.equalTo(-18)
        }
        
        mainItemView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        centerView.addSubview(mainItemView)
        mainItemView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-16)
            make.top.equalTo(52)
        }
        
        alertLabel = {
            let label = UILabel()
            label.numberOfLines = 0
            let b: ASAttributedString = .init("若不能提供以上证明材料，将导致您的该收入", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor(hex: 0x8993a2)))
            let c: ASAttributedString = .init("不被认可不予加分", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.failColor))
            let d: ASAttributedString = .init("，请尽可能准备以上材料并修改此选项)", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor(hex: 0x8993a2)))
            label.attributed.text = b + c + d
            return label
        }()
        centerView.addSubview(alertLabel)
        alertLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.bottom.equalTo(-16)
        }
    }
    
    func updateAllViews() {
        mainItemView.removeSubviews()
        for j in 0..<messageDataSource.count {
            let lineView = {
                let label = UIView()
                label.backgroundColor = UIColor.separatorColor
                return label
            }()
            centerView.addSubview(lineView)
            lineView.snp.makeConstraints { make in
                make.height.equalTo(1)
                make.left.right.equalToSuperview()
                if j == 0 {
                    make.top.equalTo(52)
                } else {
                    let view = mainItemView.viewWithTag(2000 + j - 1)
                    make.top.equalTo(view?.snp.bottom ?? mainItemView.snp.bottom).offset(15)
                }
            }
            
            let titleLabel = {
                let label = UILabel()
//                label.attributed.text = dataSource?[i]
                label.numberOfLines = 0
                let str = "*" + messageDataSource[j]
                let attributes: [NSAttributedString.Key: Any] = [
                    .font: UIFont.PFSC_R(ofSize: 14),
                    .foregroundColor: UIColor.mainTextColor
                ]
                let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                let starRange = NSRange(location: 0, length: 1)
                questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                label.attributedText = questionAttrStr
                label.tag = 2000 + j
                return label
            }()
            mainItemView.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { make in
                make.top.equalTo(lineView.snp.bottom).offset(15)
                make.left.equalTo(18)
                make.width.equalTo(106)
            }
            
            let rightButton = {
                let button = UIButton(type: .custom)
                button.setBackgroundColor(color: UIColor.brandMainColor.withAlphaComponent(0.08), forState: .selected)
                button.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                button.layer.borderColor = UIColor.brandMainColor.cgColor
                button.setTitleColor(UIColor.mainTextColor, for: .normal)
                button.setTitleColor(UIColor.brandMainColor, for: .selected)
                button.setTitle("否", for: .normal)
                button.layer.cornerRadius = 16
                button.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
                button.addTarget(self, action: #selector(rightClick(sender:)), for: .touchUpInside)
                button.tag = 3000 + j
                return button
            }()
            mainItemView.addSubview(rightButton)
            rightButton.snp.makeConstraints { make in
                make.right.equalTo(-18)
                make.centerY.equalTo(titleLabel.snp.centerY)
                make.height.equalTo(32)
                make.width.equalTo(74)
            }
            
            let leftButton = {
                let button = UIButton(type: .custom)
                button.setBackgroundColor(color: UIColor.brandMainColor.withAlphaComponent(0.08), forState: .selected)
                button.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
                button.layer.borderColor = UIColor.brandMainColor.cgColor
                button.setTitleColor(UIColor.brandMainColor, for: .selected)
                button.setTitleColor(UIColor.mainTextColor, for: .normal)
                button.layer.cornerRadius = 16
                button.setTitle("是", for: .normal)
                button.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
                button.addTarget(self, action: #selector(leftClick(sender:)), for: .touchUpInside)
                button.tag = 4000 + j
                return button
            }()
            mainItemView.addSubview(leftButton)
            leftButton.snp.makeConstraints { make in
                make.right.equalTo(rightButton.snp.left).offset(-12)
                make.centerY.equalTo(titleLabel.snp.centerY)
                make.height.equalTo(32)
                make.width.equalTo(74)
            }
            let bgviewButton = {
                let view = UIButton()
                view.backgroundColor = UIColor.contentBkgColor
                view.layer.cornerRadius = 3
                view.layer.borderColor = UIColor.brandMainColor.cgColor
                return view
            }()
            mainItemView.addSubview(bgviewButton)
            if model?.has_provide_certificate == 0 {
                leftButton.isSelected = false
                rightButton.isSelected = false
                leftButton.layer.borderWidth = 0
                rightButton.layer.borderWidth = 0
                alertLabel.isHidden = true
            }
            if model?.has_provide_certificate == 1 {
                leftButton.isSelected = true
                rightButton.isSelected = false
                leftButton.layer.borderWidth = 1
                rightButton.layer.borderWidth = 0
                alertLabel.isHidden = true
            }
            if model?.has_provide_certificate == 2 {
                rightButton.isSelected = true
                leftButton.isSelected = false
                leftButton.layer.borderWidth = 0
                rightButton.layer.borderWidth = 1
                alertLabel.isHidden = false
            }
            for i in 0..<dataSource.count {
                let agreeButton = {
                    let button = UIView()
                    button.tag = 10000 + i
                    button.backgroundColor = UIColor(hex: 0xb3c8e9)
                    return button
                }()
                mainItemView.addSubview(agreeButton)
                agreeButton.snp.makeConstraints { make in
                    if i == 0 {
                        make.top.equalTo(titleLabel.snp.bottom).offset(32)
                    } else {
                        let view = mainItemView.viewWithTag(1000 + i - 1)
                        make.top.equalTo(view?.snp.bottom ?? mainItemView.snp.bottom).offset(18)
                    }
                    make.left.equalTo(34)
                    make.height.equalTo(5)
                    make.width.equalTo(5)
                }
                
                let subTitleLabel = {
                    let label = UILabel()
                    label.text = dataSource[i]
                    label.numberOfLines = 0
                    label.tag = 1000 + i
                    label.textColor = UIColor.mainTextColor
                    label.font = UIFont.PFSC_R(ofSize: 14)
                    label.isUserInteractionEnabled = false
                    return label
                }()
                mainItemView.addSubview(subTitleLabel)
                subTitleLabel.snp.makeConstraints { make in
                    make.top.equalTo(agreeButton.snp.top).offset(-10)
                    make.left.equalTo(56)
                    make.right.equalTo(-35)
                    if i == (dataSource.count) - 1 {
                        make.bottom.equalToSuperview().offset(-16)
                    }
                }
                if i == dataSource.count - 1 {
                    bgviewButton.snp.makeConstraints { make in
                        make.top.equalTo(titleLabel.snp.bottom).offset(16)
                        make.bottom.equalTo(subTitleLabel.snp.bottom).offset(16)
                        make.left.equalTo(18)
                        make.right.equalTo(-18)
                    }
                }
            }
        }
    }
    
    @objc func leftClick(sender: UIButton) {
        model?.has_provide_certificate = 1
        if let block = selectBlock {
            block(model ?? YHWorkExperienceCompanyModel())
        }
        mainItemView.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-16)
            make.top.equalTo(52)
        }
        alertLabel.isHidden = true

    }
    
    @objc func rightClick(sender: UIButton) {
        model?.has_provide_certificate = 2
        if let block = selectBlock {
            block(model ?? YHWorkExperienceCompanyModel())
        }
        mainItemView.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-72)
            make.top.equalTo(52)
        }
        alertLabel.isHidden = false
    }
    
}
