//
//  QSLAddController.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/11/27.
//

import UIKit
import Contacts
import ContactsUI

enum QSLAddJumpType: Int {
    
    case homesmall
    case homebig
    case friend
}

class QSLAddController: QSLBaseController {
    
    var type: QSLAddJumpType?
    
    lazy var bgImageView: UIImageView = {
      
        let imageView = UIImageView()
        imageView.image = UIImage(named: "add_bg")
        return imageView
    }()
    
    lazy var backButton: UIButton = {
       
        let button = UIButton()
        button.image(UIImage(named: "public_back_btn"))
        button.title("添加好友")
        button.mediumFont(17)
        button.textColor(QSLColor.Color_202020)
        button.setImageTitleLayout(.imgLeft, spacing: 4.rpx)
        button.addTarget(self, action: #selector(addBackBtnAction), for: .touchUpInside)
        return button
    }()
    
    lazy var addView: UIView = {
       
        let view = UIView()
        view.addRadius(radius: 8.rpx)
        view.backgroundColor = .white
        return view
    }()
    
    lazy var addTitleIcon: UIImageView = {
       
        let imageView = UIImageView()
        imageView.image = UIImage(named: "add_title_icon")
        return imageView
    }()
    
    lazy var addInputView: UIView = {
      
        let view = UIView()
        view.backgroundColor = QSLColor.backGroundColor
        view.addRadius(radius: 12.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(addressBookAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var addBtn: UIButton = {
       
        let btn = UIButton()
        btn.addRadius(radius: 22.rpx)
        btn.gradientBackgroundColor(color1: .hexStringColor(hexString: "#15CBA1"), color2: .hexStringColor(hexString: "#1FE0BA"), width: QSLConst.qsl_kScreenW - 32.rpx, height: 44.rpx, direction: .horizontal)
        btn.title("添加")
        btn.mediumFont(16)
        btn.textColor(.white)
        btn.setImageTitleLayout(.imgLeft, spacing: 0)
        btn.addTarget(self, action: #selector(addBtnAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var infoLabel: UILabel = {
      
        let label = UILabel()
        label.text("定位功能需要双方同意方可使用")
        label.textColor = .hexStringColor(hexString: "#A7A7A7")
        label.font(13)
        return label
    }()    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        initializeView()
        
        if let type = self.type {
            switch type {
            case .homesmall:
                gravityInstance?.track(QSLGravityConst.add_show, properties: ["id": 1001])
            case .homebig:
                gravityInstance?.track(QSLGravityConst.add_show, properties: ["id": 1002])
            case .friend:
                gravityInstance?.track(QSLGravityConst.add_show, properties: ["id": 1003])
            }
        }
    }
    
    // 点击添加按钮
    @objc func addBtnAction() {
        
        self.view.keyboardEndEditing()
        
        gravityInstance?.track(QSLGravityConst.add_click)
        
        if !QSLBaseManager.shared.isLogin() {
            
            QSLAlertView.alert(view: self.view, title: "温馨提示", content: "登录之后才可以发送好友申请", oneBtnClosure:  {
                
                QSLJumpManager.shared.pushToLogin(type: .add)
            })
            
            return
        }
        
        if !QSLBaseManager.shared.isVip() {
            
            QSLJumpManager.shared.pushToVip(type: .add)
            return
        }
        
        if self.phoneTextField.text?.count == 0 {
            gravityInstance?.track(QSLGravityConst.add_result, properties: ["id": 1001])
        }
        
        guard let phone = self.phoneTextField.text, phone.count == 11 else {
            self.view.toast(text: "请输入正确的电话号码")
            gravityInstance?.track(QSLGravityConst.add_result, properties: ["id": 1002])
            return
        }
        
        QSLAlertView.alert(view: self.view, title: "温馨提示", content: "1.在对方同意添加您为好友之后，才能查看对方的位置。\n\n2.如果您的好友还没有下载该应用，建议您邀请他们下载安装。\n\n3.通过同意添加该用户为您的好友，即表示您同意本软件合法地收集、存储和使用您的信息，并将位置等信息与该好友分享。", isOneBtn: true, contentTextAlignment: .left, oneBtnText: "我知道了", oneBtnClosure:  { [weak self] in
            
            self?.requestAddFri()
        })
    }
    
    @objc func addressBookAction() {
        
        gravityInstance?.track(QSLGravityConst.add_addressBook)
        
        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 vc = CNContactPickerViewController()
                        vc.delegate = self
                        self.present(vc, animated: true, completion: nil)
                    }
                } else {
                    
                    DispatchQueue.main.async {
                        self.view.toast(text: "请先开启通讯录权限")
                    }
                }
            }
        } else {
            
            let vc = CNContactPickerViewController()
            vc.delegate = self
            self.present(vc, animated: true, completion: nil)
        }
    }
    
    @objc func addBackBtnAction() {
        
        gravityInstance?.track(QSLGravityConst.add_back)
        
        self.backBtnAction()
    }
}

extension QSLAddController {
    
    func requestAddFri() {
        
        guard let phone = self.phoneTextField.text else {
            return
        }
        
        QSLNetwork().request(.requestSend(dict: ["phone": phone])) { response in
            
            self.view.toast(text: "已发送好友请求")
            if QSLBaseManager.shared.isVip() {
                ///输入手机号添加成功
                gravityInstance?.track(QSLGravityConst.vip_friend_add_success_phone, properties: ["id": 04003])
            }

        } fail: { code, error in
            self.view.toast(text: error)
            if QSLBaseManager.shared.isVip() {
                ///输入手机号添加失败
                gravityInstance?.track(QSLGravityConst.vip_friend_add_fail_phone, properties: ["id": 04004])
            }
            switch code {
            case 1102:
                // 该好友已在好友列表
                gravityInstance?.track(QSLGravityConst.add_result, properties: ["id": 1003])
                break
            case 1103:
                // 不能添加自己
                gravityInstance?.track(QSLGravityConst.add_result, properties: ["id": 1005])
                break
            case 1100:
                // 好友未注册
                gravityInstance?.track(QSLGravityConst.add_result, properties: ["id": 1005])
                break
            default:
                gravityInstance?.track(QSLGravityConst.add_result, properties: ["id": 1006])
                break
            }
        }
    }
}

extension QSLAddController: 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 QSLAddController {
    
    func initializeView() {
        
        self.view.backgroundColor = .hexStringColor(hexString: "#FAFAFA")
        
        self.view.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.height.equalTo(195.rpx)
        }
        
        self.view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.width.equalTo(100.rpx)
            make.height.equalTo(25.rpx)
            make.left.equalTo(12.rpx)
            make.top.equalTo(QSLConst.qsl_kStatusBarFrameH)
        }
        
        self.view.addSubview(addView)
        addView.snp.makeConstraints { make in
            make.top.equalTo(bgImageView.snp.bottom)
            make.left.equalTo(12.rpx)
            make.right.equalTo(-12.rpx)
            make.height.equalTo(236.rpx)
        }
        
        addView.addSubview(addTitleIcon)
        addTitleIcon.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 157.rpx, height: 26.rpx))
            make.left.top.equalTo(24.rpx)
        }
        
        addView.addSubview(addInputView)
        addInputView.snp.makeConstraints { make in
            make.left.equalTo(16.rpx)
            make.right.equalTo(-16.rpx)
            make.height.equalTo(52.rpx)
            make.top.equalTo(74.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)
        }
        
        addView.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.left.equalTo(28.rpx)
            make.right.equalTo(-28.rpx)
            make.height.equalTo(44.rpx)
            make.bottom.equalTo(-30.rpx)
        }
        
        self.view.addSubview(infoLabel)
        infoLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-QSLConst.qsl_kTabbarBottom - 26.rpx)
        }
    }
}
