//
//  QSLContactAddAlertView.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/12/12.
//

import UIKit
import Contacts
import ContactsUI

class QSLContactAddAlertView: UIView {
    
    var vc: UIViewController?
    
    lazy var contentView: UIView = {
        
        let contentView = UIView(frame: CGRect(x: 0, y: 0, width: QSLConst.qsl_kScreenW - 60.rpx, height: 152.0.rpx))
        contentView.backgroundColor = .white
        contentView.addRadius(radius: 8.rpx)
        return contentView
    }()
    
    lazy var titleLabel: UILabel = {
      
        let label = UILabel()
        label.text("添加紧急联系人")
        label.mediumFont(17)
        label.textColor = QSLColor.Color_202020
        return label
    }()
    
    lazy var addInputView: UIView = {
      
        let view = UIView()
        view.backgroundColor = QSLColor.backGroundColor
        view.addRadius(radius: 4.rpx)
        view.addBorder(borderWidth: 1.rpx, borderColor: .hexStringColor(hexString: "#F2F2F2"))
        return view
    }()
    
    lazy var phoneTextField: UITextField = {
       
        let textField = UITextField()
        textField.maxTextNumber = 11
        textField.keyboardType = .numberPad
        textField.textColor = QSLColor.Color_202020
        textField.font = UIFont.textF(16)
        textField.placeholder = "请输入手机号"
        textField.setPlaceholderAttribute(font: UIFont.textF(16), color: UIColor.hexStringColor(hexString: "#A7A7A7"))
        return textField
    }()
    
    lazy var lineView: UIView = {
       
        let view = UIView()
        view.backgroundColor = .hexStringColor(hexString: "#F2F2F2")
        return view
    }()
    
    lazy var addressBookBtn: UIButton = {
       
        let btn = UIButton()
        btn.image(UIImage(named: "add_address_btn"))
        btn.title("通讯录导入")
        btn.textColor(.hexStringColor(hexString: "#11B58F"))
        btn.font(13)
        btn.addTarget(self, action: #selector(addressBtnAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var firstButton: UIButton = {
        
        let btn = UIButton()
        btn.backgroundColor = .hexStringColor(hexString: "#F8F8F8")
        btn.addRadius(radius: 20.rpx)
        btn.title("取消")
        btn.textColor(.hexStringColor(hexString: "#A7A7A7"))
        btn.mediumFont(16)
        btn.addTarget(self, action: #selector(removeView), for: .touchUpInside)
        return btn
    }()
    
    lazy var secondButton: UIButton = {
        
        let btn = UIButton()
        btn.addRadius(radius: 20.rpx)
        btn.title("添加")
        btn.textColor(.white)
        btn.mediumFont(16)
        btn.gradientBackgroundColor(color1: .hexStringColor(hexString: "#15CBA1"), color2: .hexStringColor(hexString: "#1FE0BA"), width: 118.rpx, height: 40.rpx, direction: .horizontal)
        btn.addTarget(self, action: #selector(addBtnAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var closeButton: UIButton = {
       
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "public_btn_close_AAA"), for: .normal)
        btn.addTarget(self, action: #selector(removeView), for: .touchUpInside)
        return btn
    }()
    
    var secondBtnClosure: ((String) -> ())?
    
    var addressBtnClosure: (() -> ())?
    
    class func alert(vc: UIViewController,
                     secondBtnClosure: @escaping (String) -> ()) {
        
        let window = QSLContactAddAlertView(frame: CGRect(x: 0, y: 0, width: QSLConst.qsl_kScreenW, height: QSLConst.qsl_kScreenH))
        window.vc = vc
        window.secondBtnClosure = secondBtnClosure
        vc.view.addSubview(window)
        
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.95, initialSpringVelocity: 0.05) {
            window.backgroundColor = .hexStringColor(hexString: "#000000", alpha: 0.7)
            window.contentView.isHidden = false
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func addBtnAction() {
        
        gravityInstance?.track(QSLGravityConst.contact_add)
        
        guard let text = self.phoneTextField.text, text.count == 11 else {
            self.vc?.view.toast(text: "请输入正确的电话号码")
            return
        }
        
        if let secondBtnClosure = self.secondBtnClosure {
            secondBtnClosure(text)
        }
        
        self.keyboardEndEditing()
        self.removeView()
    }
    
    @objc func addressBtnAction() {
        
        gravityInstance?.track(QSLGravityConst.contact_addressbook)
        
        self.removeView()
            
        let status = CNContactStore.authorizationStatus(for: .contacts)
        if status != .authorized {
            
            let store = CNContactStore()
            store.requestAccess(for: .contacts) { granted, error in
                if granted {
                    DispatchQueue.main.async {
                        
                        let picker = CNContactPickerViewController()
                        picker.delegate = self
                        self.vc?.present(picker, animated: true, completion: nil)
                    }
                } else {
                    
                    DispatchQueue.main.async {
                        self.vc?.view.toast(text: "请先开启通讯录权限")
                    }
                }
            }
        } else {
            
            let picker = CNContactPickerViewController()
            picker.delegate = self
            self.vc?.present(picker, animated: true, completion: nil)
        }
    }
    
    // 移除
    @objc func removeView() {
        
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.95, initialSpringVelocity: 0.05) { [weak self] in
            self?.backgroundColor = UIColor.init(white: 0, alpha: 0)
            self?.contentView.isHidden = true
        } completion: { [weak self] finished in
            self?.removeFromSuperview()
        }
    }
}

extension QSLContactAddAlertView: CNContactPickerDelegate {
    
    // 通讯录选择电话
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        
        let phoneArray = contact.phoneNumbers

        if let firstPhone = phoneArray.first {
            
            let phoneNum = firstPhone.value
            
            let code = phoneNum.stringValue
            
            let phone = code.replacingOccurrences(of: " ", with: "")
            
            self.phoneTextField.text = phone
            
            print("Phone number is --- \(code)")
        }

        let name = CNContactFormatter.string(from: contact, style: .fullName) ?? "Unknown"
        print("Full name is --- \(name)")
    }
}

extension QSLContactAddAlertView {
    
    func initView() {
        
        addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: QSLConst.qsl_kScreenW - 60.rpx, height: 203.0.rpx))
            make.center.equalToSuperview()
        }
        
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(24.rpx)
        }

        contentView.addSubview(addInputView)
        addInputView.snp.makeConstraints { make in
            make.left.equalTo(29.rpx)
            make.right.equalTo(-19.rpx)
            make.top.equalTo(titleLabel.snp.bottom).offset(16.rpx)
            make.height.equalTo(44.rpx)
        }
        
        addInputView.addSubview(addressBookBtn)
        addressBookBtn.snp.makeConstraints { make in
            make.width.equalTo(104.rpx)
            make.top.bottom.right.equalTo(0)
        }
        
        addInputView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.top.equalTo(16.rpx)
            make.bottom.equalTo(-16.rpx)
            make.right.equalTo(addressBookBtn.snp.left)
            make.width.equalTo(1.rpx)
        }
        
        addInputView.addSubview(phoneTextField)
        phoneTextField.snp.makeConstraints { make in
            make.left.equalTo(12.rpx)
            make.top.bottom.equalTo(0)
            make.right.equalTo(lineView.snp.left).offset(-12.rpx)
        }
        
        contentView.addSubview(firstButton)
        firstButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 118.rpx, height: 40.rpx))
            make.left.equalTo(24.rpx)
            make.bottom.equalTo(-24.rpx)
        }
        
        contentView.addSubview(secondButton)
        secondButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 118.rpx, height: 40.rpx))
            make.right.equalTo(-24.rpx)
            make.bottom.equalTo(-24.rpx)
        }
        
        contentView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 24.rpx, height: 24.rpx))
            make.top.equalTo(12.rpx)
            make.right.equalTo(-12.rpx)
        }
    }
}
