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

import UIKit

class YHAdopterTravelViewController: YHBaseViewController {

    var tableView: UITableView!
    var nextButton: UIButton!
    var clickIndex = -1
    var data: [YHItemModel] = []
    var viewModel = YHYHAdopterTravelViewModel()
    var model: YHAdopterDependentDataDocModel = YHAdopterDependentDataDocModel()
    var isShowPrompt = false
    var urls: [String] = ["", ""]
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "上传旅行证件"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1
        urls = model.url
        if urls.count == 0 {
            urls = ["", ""]
        }
        setView()
        getData()
    }
    
    func getData() {
        viewModel.mainModel = model
        data = viewModel.getBaseDataSource(isShowPrompt)
        tableView.reloadData()
    }
    
    func setView() {
        view.backgroundColor = .white
        tableView = {
            let tableView = UITableView(frame: .zero, style: .plain)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .white
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHAdopterIncomeTitleTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterTravelCardTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterTravelItemTableViewCell.self)
//            tableView.register(cellWithClass: YHAdopterIncomeFileCountTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 8)
            make.bottom.left.right.equalTo(view)
        }
    
        nextButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor.brandMainColor
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("确认上传", for: .normal)
            button.setTitleColor( UIColor(hex: 0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(nextStep), for: .touchUpInside)
            return button
        }()
        view.addSubview(nextButton)
        nextButton.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-8 - k_Height_safeAreaInsetsBottom())
            make.height.equalTo(48)
        }
        if model.status == 1 || model.status == 3 {
            nextButton.isHidden = true
        } else {
            tableView.snp.remakeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 8)
                make.left.right.equalTo(view)
                make.bottom.equalTo(-56 - k_Height_safeAreaInsetsBottom())
            }
        }
    }
    
    @objc func nextStep() {
        for item in urls {
            if item.count == 0 {
                YHHUD.flash(message: "请上传文件")
                return
            }
        }
        if self.viewModel.isCanNext(1) {
            viewModel.postdependentsUpload(urls: urls) {[weak self] _, _ in
                guard let self = self else { return }
                self.navigationController?.popViewController(animated: true)
            }
        } else {
            self.isShowPrompt = true
            self.getData()
            YHHUD.flash(message: "您还有信息未填写")
        }
    }
    
    func isOneYearAfter(_ dateString: String) -> Bool {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        guard let inputDate = dateFormatter.date(from: dateString) else {
            return false // 输入格式不正确
        }
        
        let currentDate = Date()
        let oneYearFromNow = Calendar.current.date(byAdding: .year, value: 1, to: currentDate)!
        
        return inputDate < oneYearFromNow
    }
}

extension YHAdopterTravelViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 2
        }
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withClass: YHAdopterIncomeTitleTableViewCell.self)
                cell.docDataSource = model
                return cell
            }
            if indexPath.row == 1 {
                let cell = tableView.dequeueReusableCell(withClass: YHAdopterTravelCardTableViewCell.self)
                cell.firstImageName = "service_adopter_card_travel_front"
                cell.lastImageName = "service_adopter_card_travel_back"
                cell.firstLabelName = "证件页1"
                cell.lastLabelName = "证件页2"
                cell.urls = urls
                cell.state = model.status
                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.viewModel.requestHkIDCardMessage(url, isBack: 0) {[weak self] _, _ in
                            guard let self = self else { return }
                            self.data = viewModel.getBaseDataSource(isShowPrompt)
                            self.tableView.reloadData()
                        }
                    }
                }
                cell.deleteBlock = { [weak self] url, index in
                    guard let self = self else { return }
                    self.urls[index] = url
                }
                return cell
            }
        }
        let cell = tableView.dequeueReusableCell(withClass: YHAdopterTravelItemTableViewCell.self)
        cell.dataSource = data[indexPath.row]
        cell.state = model.status
        cell.informationBlock = {[weak self] model in
            guard let self = self else { return }
            self.viewModel.updateModel(model)
            let id = model.id
            if id != .id2 && id != .id3 && id != .id4 {
                self.data = viewModel.getBaseDataSource(isShowPrompt)
                self.tableView.reloadData()
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                
                if model.reject_reason.count != 0 && model.status == 2 {
                    return 119
                } else {
                    if isOneYearAfter(model.certificates_info.sign_expire_date) && model.certificates_info.sign_expire_date.count != 0 {
                        return 119
                    }
                    return 86
                }
            }
            if indexPath.row == 1 {
                return 173
            }
        }
        
        let model = data[indexPath.row]
        let isShow = model.isShowPrompts ?? false
        let message = model.message ?? ""
        let isNeed = model.isNeed ?? false
        if isShow && message.count == 0 && isNeed {
            return 52 + 20
        } else {
            return 52
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
    
}
