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

import UIKit
import AttributedString

class YHResignUploadTravelHKViewController: 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(YHResignUploadTravelHKTableViewCell.self, forCellReuseIdentifier: YHResignUploadTravelHKTableViewCell.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("上传《港澳通行证》(背面逗留D签注有效期≥\(date))", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.5)))
        }
        
        if type == 1 {
            let a = ASAttributedString.init("点击查看办理逗留D签注延期", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor50))
            let b = ASAttributedString.init("《", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.brandMainColor))
            let c = ASAttributedString.init("港澳通行证逗留（D）签注延期-办理指引", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.brandMainColor), .underline(.single), .action {
                // 跳转提示
                let view = YHResignUploadTravelGuideView.sheetView()
                view.show()
            })
            let d = ASAttributedString.init("》", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.brandMainColor))
            return a+b+c+d
        }
        
        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),
                self.getTextWithType(type: 1, date: date)]
    }
    
    func updateData() {
        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
            }
            if dataModel.img_back.count != 0 {
                urls[1] = dataModel.img_back
            }
            self.data = viewModel.getBaseDataSource(isShowPrompt)
            // 头部提示
            tipsArr = getTipsWithType(date: self.dataModel.latest_validaty_date)
            tableView.reloadData()
        }
    }
    
    func updateAllViews() {
        if dataModel.img_front.count != 0 {
            urls[0] = dataModel.img_front
        }
        if dataModel.img_back.count != 0 {
            urls[1] = dataModel.img_back
        }
        self.data = viewModel.getBaseDataSource(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 urls.last?.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
        }
        if self.viewModel.dataModel.visa_start.count == 0 {
            return false
        }
        if self.viewModel.dataModel.visa_end.count == 0 {
            return false
        }
        return true
    }
}

private extension YHResignUploadTravelHKViewController {
    // 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_back": urls[1],
            "img_front": urls[0],
            "issue_start": self.viewModel.dataModel.issue_start,
            "issue_end": self.viewModel.dataModel.issue_end,
            "visa_start": self.viewModel.dataModel.visa_start,
            "visa_end": self.viewModel.dataModel.visa_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 YHResignUploadTravelHKViewController: 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: YHResignUploadTravelHKTableViewCell.cellReuseIdentifier, for: indexPath) as? YHResignUploadTravelHKTableViewCell else { return UITableViewCell() }
        cell.firstImageName = "service_adopter_card_travel_front"
        cell.lastImageName = "service_adopter_card_travel_back"
        cell.firstLabelName = "港澳通行证正面"
        cell.lastLabelName = "港澳通行证背面"
        cell.dataModel = dataModel
        cell.failString = failString
        cell.data = data
        cell.urls = urls
        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 }
                if index == 0 {
                    self.viewModel.getHKCardInfoByOcr(url, isBack: 0) { success, result in
                        YHHUD.hide()
                        if success, let result = result {
                            if !result.term_begins.isEmpty {
                                self.dataModel.issue_start = result.term_begins
                            }
                            if !result.end_of_term.isEmpty {
                                self.dataModel.issue_end = result.end_of_term
                            }
                            self.failString = ""
                        } else {
                            // OCR 无法识别
                            self.failString = "非逗留（D）签证，请核查文件"
                        }
                        self.updateAllViews()
                    }
                } else {
                    self.viewModel.getHKCardBackInfoByOcr(url, isBack: 1) { success, result in
                        YHHUD.hide()
                        if success, let result = result {
                            if !result.back_term_begins.isEmpty {
                                self.dataModel.visa_start = result.back_term_begins
                            }
                            if !result.back_end_of_term.isEmpty {
                                self.dataModel.visa_end = result.back_end_of_term
                            }
                            self.failString = ""
                        } else {
                            // OCR 无法识别
                            self.failString = "非逗留（D）签证，请核查文件"
                        }
                        self.updateAllViews()
                    }
                }
            }
        }
        cell.deleteBlock = { [weak self] url, index in
            guard let self = self else { return }
            self.urls[index] = url
            if index == 0 {
                self.dataModel.img_front = ""
            } else {
                self.dataModel.img_back = ""
            }
            self.updateAllViews()
        }
        cell.block = {[weak self] model in
            guard let self = self else { return }
            self.viewModel.updateModel(model)
            self.dataModel = self.viewModel.dataModel
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section != 0 {
            if urls[0].count == 0 && urls[1].count == 0 {
                return 223
            } 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(501 + 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
    }
}
