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

import UIKit
import AttributedString

class YHResignUploadTravelPassportViewController: YHBaseViewController {
    
    lazy var viewModel: YHResignUploadTravelCardDetailViewModel = {
        let vm = YHResignUploadTravelCardDetailViewModel()
        return vm
    }()
    
    var fatherData: YHResignUploadTravelCardListDetailModel = YHResignUploadTravelCardListDetailModel()
    // 上个界面传递过来的数据对象
    var dataModel: YHResignUploadTravelCardDetailModel = YHResignUploadTravelCardDetailModel()
    var orderId: Int = 0
    var batchId: Int = 0
    var tipsArr: [ASAttributedString] = []
    var urls: [String] = [""]
    var data: [YHItemModel] = []
    var isShowPrompt = false
    var failString: String = ""
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.estimatedSectionFooterHeight = 16.0
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hex: 0xF8F9FB)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHTravelCertificateTipsCell.self, forCellReuseIdentifier: YHTravelCertificateTipsCell.cellReuseIdentifier)
        tableView.register(YHResignUploadTravelPassportTableViewCell.self, forCellReuseIdentifier: YHResignUploadTravelPassportTableViewCell.cellReuseIdentifier)
        return tableView
    }()
    
    let bottomViewHeight = 98.0
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        return view
    }()
    
    lazy var bottomBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("确认，保存", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.addTarget(self, action: #selector(didSaveBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "上传旅行证件"
        self.view.backgroundColor = .white
        self.view.addSubview(self.tableView)
        self.view.addSubview(bottomView)

        self.tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(98)
        }
        self.bottomView.addSubview(bottomBtn)
        self.bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        loadDetailInfo()
    }
    
    func getTextWithType(type: Int, date: String) -> ASAttributedString {
        
        if type ==  0 {
           return .init("上传《护照》(需有效期≥\(date))", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.5)))
        }
        
        return .init("", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.5)))
    }
    
    func getTipsWithType(date: String) -> [ASAttributedString] {
        return [self.getTextWithType(type: 0, date: date)]
    }
    
    func updateData() {
        
        // travel_cert_type 证件类型 0-未知 1-护照 3-港澳通行证
        // nationality : Int = -1  国籍 1-中国 2-国外
        let params: [String: Any] = [
            "order_id": orderId,
            "renewal_id": batchId,
            "user_id": fatherData.id,
            "user_type": fatherData.type
        ]
        viewModel.getResignCertificateDetail(params) {[weak self] _, _ in
            guard let self = self else { return }
            dataModel = self.viewModel.dataModel
            if dataModel.img_front.count != 0 {
                urls[0] = dataModel.img_front
            }
            self.data = viewModel.getPassPortDataSource(isShowPrompt)
            // 头部提示
            tipsArr = getTipsWithType(date: self.dataModel.latest_validaty_date)
            tableView.reloadData()
        }
        
    }
    
    func updateAllViews() {
        if dataModel.img_front.count != 0 {
            urls[0] = dataModel.img_front
        }
        self.data = viewModel.getPassPortDataSource(isShowPrompt)
        // 头部提示
        tipsArr = getTipsWithType(date: self.dataModel.latest_validaty_date)
        tableView.reloadData()
    }
    
    @objc func didSaveBtnClicked() {
        if !checkInfo() {
            isShowPrompt = true
            updateAllViews()
            return
        }
        
        saveAllTravelCertificate()
    }
    
    func checkInfo() -> Bool {
        if urls.first?.count == 0 {
            failString = "请上传护照"
            return false
        }
        
        if self.viewModel.dataModel.issue_start.count == 0 {
            return false
        }
        if self.viewModel.dataModel.issue_end.count == 0 {
            return false
        }
        return true
    }
}

private extension YHResignUploadTravelPassportViewController {
    // 1、获取详情信息
    func loadDetailInfo() {
        self.updateData()
    }
    
    // 2、保存旅行证件
    func saveAllTravelCertificate() {
        let params: [String: Any] = [
            "order_id": orderId,
            "renewal_id": batchId,
            "user_id": fatherData.id,
            "user_type": fatherData.type,
            "type": self.viewModel.dataModel.type,
            "img_front": urls[0],
            "issue_start": self.viewModel.dataModel.issue_start,
            "issue_end": self.viewModel.dataModel.issue_end
        ]
        viewModel.submitResignCertificateUpdate(params) { success, error in
            if success {
                YHHUD.flash(message: "保存成功")
                self.navigationController?.popViewController()
            } else {
                let msg = error?.errorMsg ?? "保存失败,请重试"
                YHHUD.flash(message: msg)
            }
        }
    }
}

extension YHResignUploadTravelPassportViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.section == 0 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHTravelCertificateTipsCell.cellReuseIdentifier, for: indexPath) as? YHTravelCertificateTipsCell else {
                return UITableViewCell()
            }
            cell.userName = self.dataModel.name
            cell.tipsArr = tipsArr
            return cell
        }
    
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHResignUploadTravelPassportTableViewCell.cellReuseIdentifier, for: indexPath) as? YHResignUploadTravelPassportTableViewCell else {
            return UITableViewCell()
        }
        cell.firstImageName = "service_adopter_card_china_travel_front"
        cell.firstLabelName = "护照资料页"
        cell.dataModel = dataModel
        cell.failString = failString
        cell.urls = urls
        cell.data = data
        cell.urlBlock = { [weak self] url, index in
            guard let self = self else { return }
            self.urls[index] = url
            self.viewModel.getPublicImageUrl(url) {[weak self] success, _ in
                guard let self = self else { return }
                guard let url = success else { return }
                self.data = viewModel.getPassPortDataSource(isShowPrompt)
                self.tableView.reloadData()
            }
        }
        cell.deleteBlock = { [weak self] url, index in
            guard let self = self else { return }
            self.urls[index] = url
            if index == 0 {
                self.dataModel.img_front = ""
            }
            self.updateAllViews()
        }
        cell.block = {[weak self] model in
            guard let self = self else { return }
            self.viewModel.updateModel(model)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section != 0 {
            if urls[0].count == 0 {
                return 231
            } else {
                var tatol = 0
                for item in data {
                    let isShow = item.isShowPrompts ?? false
                    let message = item.message ?? ""
                    let isNeed = item.isNeed ?? false
                    if isShow && message.count == 0 && isNeed {
                        tatol += 20
                    }
                }
                return CGFloat(333 + tatol)
            }
        }
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
            
        return 16.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        if section == 0 {
            view.backgroundColor = .white
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
}
