CNLiveMineInputViewController.swift 9.46 KB
//
//  CNLiveMineInputViewController.swift
//  metaCode
//
//  Created by open on 2023/9/11.
//

import Foundation
import EmptyDataSet_Swift
import HXPHPicker

typealias resultUploadImageBlock = (_ url: String) -> Void
class CNLiveMineInputViewController : CNLiveBaseViewController, UITableViewDelegate, UITableViewDataSource, EmptyDataSetSource, EmptyDataSetDelegate, PhotoPickerControllerDelegate{
    
    let kMineBodyInputAuthCellIdentifier = "kMineBodyInputAuthCellIdentifier"
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        tableView.backgroundColor = HexColor("#F7F8FA")
        tableView.tableFooterView = UIView.init()
        tableView.contentInsetAdjustmentBehavior = .scrollableAxes
        tableView.separatorStyle = .none
        tableView.register(MineBodyInputAuthCell.self, forCellReuseIdentifier: kMineBodyInputAuthCellIdentifier)
        return tableView
    }()
    
    lazy var sendButton: UIButton = {
        let sendButton = UIButton(type: .custom)
        sendButton.setTitle("添加身份", for: .normal)
        sendButton.setTitleColor(.white, for: .normal)
        sendButton.titleLabel?.font = BoldFont_16_Fit
        sendButton.layer.cornerRadius = 20
        sendButton.layer.masksToBounds = true
        sendButton.isHidden = true
        sendButton.addTarget(self, action: #selector(sendInfoActionMothod), for: .touchUpInside)
        return sendButton
    }()
    
    lazy var dataArray: NSMutableArray = {
        return NSMutableArray.init()
    }()

    var select_image: UIImage!
    var _listModel:StandListModel!
    var tempCell:MineBodyInputAuthCell!
    init(listModel:StandListModel) {
       super.init(nibName:nil, bundle:nil)
        _listModel = listModel
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationBarHidden = false
        titleName = _listModel.name ?? ""
        view.backgroundColor = HexColor("#F7F8FA")
        
        loadStandInfoData()
        
        view.addSubview(sendButton)
        sendButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-get_system_tabbar_ui_offsetHeight() - 20)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(40)
        }
        setupWithSendBtnStatue(statue: false)
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(get_system_nav_height())
            make.left.right.equalToSuperview()
            make.bottom.equalTo(sendButton.snp.top).offset(-10)
        }
    }
    
    private func loadStandInfoData() {
        showLoading(message: "")
        CNLiveMineViewModel.requestsStandInfo(identityId: "\(_listModel.id)", type: .nodate) {[weak self] result, respStatue in
            if respStatue == .success {
                self?.dataArray.addObjects(from: result as! [Any])
                self?.tableView.reloadData()
                if (self?.dataArray.count)! > 0 {
                    self?.sendButton.isHidden = false
                    self?.tableView.tableHeaderView = self?.setupHeaderAndFooter(is_last: false)
                    self?.tableView.tableFooterView = self?.setupHeaderAndFooter(is_last: true)
                }
            }
        }
    }
    
    private func setupWithSendBtnStatue(statue: Bool) {
        var alpha = 0.3
        if statue {
            alpha = 1
        }
        sendButton.setGradient(colors: [UIColor(red: 103/255.0, green: 197/255.0, blue: 255/255.0, alpha: alpha),UIColor(red: 96/255.0, green: 154/255.0, blue: 255/255.0, alpha: alpha)], startPoint: CGPoint(x: 0, y: 0.5), endPoint: CGPoint(x: 1, y: 0.5))
        sendButton.isUserInteractionEnabled = statue
    }
    
    @objc func sendInfoActionMothod() {
        setupWithContentUploadImage { [self] url in
            self.tempCell._infoModel?.value = url
            CNLiveMineViewModel.requestsPOSTAuthInfo(identityId: "\(_listModel.id)", infos: self.dataArray) { [self] result, respStatue in
                if respStatue == .success {
                    showMessage(message: "上传成功")
                    DispatchQueue.main.asyncAfter(deadline: .now()+1) { [self] in
                        self.navigationController?.pushViewController(CNLiveMineAuthResultViewController.init(listModel: _listModel,show_type: .result_success), animated: true)
                    }
                }
            }
        }
    }
    
    private func setupWithContentUploadImage(resultUploadImageBlock: @escaping resultUploadImageBlock) {
        if select_image != nil {
            UploadManager.uploadImage(imageData: select_image.jpegData(compressionQuality: 1.0)! as NSData, progressBlock: {key, progress in
                print("获取进度==>\(progress)")
            }, successBlock: { key,url in
                resultUploadImageBlock(url)
            })
        } else {
            resultUploadImageBlock("")
        }
    }
    
    
    func setupHeaderAndFooter(is_last: Bool) -> UIView {
        let mainView = UIView.init(frame: CGRect(x: 0, y: 0, width: Int(KSreenWidth), height: 10));
        mainView.backgroundColor = .clear
        let v = UIView.init(frame: CGRect(x: 10, y: 0, width: Int(KSreenWidth) - 20, height: 10))
        v.backgroundColor = .white
        if !is_last {
            v.addCorner(conrners: [.topLeft, .topRight], radius: 10)
        } else {
            v.addCorner(conrners: [.bottomLeft, .bottomRight], radius: 10)
        }
        mainView.addSubview(v)
        return mainView
    }
    
}

extension CNLiveMineInputViewController {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: kMineBodyInputAuthCellIdentifier) as! MineBodyInputAuthCell
        cell.setListModel(infoModel: self.dataArray[indexPath.row] as! MineStandInfoModel, is_last: indexPath.row == self.dataArray.count - 1) {[weak self] type in
            if type == .end {
                let is_result = self?.inspectResult()
                self?.setupWithSendBtnStatue(statue: is_result ?? true)
            }
            if type == .select {
                var crop = PhotoCroppingConfiguration.init()
                crop.isRoundCrop = true
                let configuration = PhotoEditorConfiguration()
                configuration.state = .cropping
                configuration.cropping = crop
                configuration.fixedCropState = true
                let config = PhotoTools.getWXPickerConfig()
                config.selectMode = .single
                config.selectOptions = .photo
                config.photoEditor = configuration
                config.maximumSelectedPhotoCount = 1
                let pickerController = PhotoPickerController(picker: config)
                pickerController.pickerDelegate = self
                pickerController.isOriginal = false
                self?.navigationController?.present(pickerController, animated: true, completion: nil)
                self?.tempCell = cell
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let infoModel = self.dataArray[indexPath.row] as! MineStandInfoModel
        return infoModel.inputType == 6 ? 70 : 50
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let infoModel = self.dataArray[indexPath.row] as! MineStandInfoModel
        if infoModel.inputType == 3 || infoModel.inputType == 4 {
            let show_type: CNLiveStandListAlertShowType  = infoModel.children.count > 0 ? .custom : .date
            self.view.endEditing(true)
            DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
                MineStandListAlertView.showStandListView(infos: infoModel.children as NSArray,name: "选择\(infoModel.name ?? "")", show_type: show_type) {[weak self] text in
                    infoModel.value = text
                    self?.tableView.reloadData()
                    let is_result = self?.inspectResult()
                    self?.setupWithSendBtnStatue(statue: is_result ?? true)
                }
            }
        }
    }
    
    func pickerController(_ pickerController: PhotoPickerController,
                            didFinishSelection result: PickerResult) {
        result.getImage { [weak self] (image, photoAsset, index) in
            if let image = image {
                self?.select_image = image
            }else {
                print("failed")
            }
        } completionHandler: { [weak self] (images) in
            self?.tempCell.iconView.image = images.first
        }
    }
    
    private func inspectResult() -> Bool {
        var is_result: Bool = true
        for item in self.dataArray {
            let listModel = item as! MineStandInfoModel
            if (listModel.nonEmpty && listModel.value?.count == 0) {
                is_result = false
            }
        }
        return is_result
    }
}