//
//  AdditionalPhotoController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/14.
//

import Foundation
import DDControlsKit_Private
import DDAutoUIKit_Private
import RxSwift
import ZLPhotoBrowser
import RxCocoa
import RxRelay
import SnapKit
import DDUtilsSwiftKit_Private

extension AdditionalPhotoController{
    func addActions() {
        refreshRelay
            .flatMapLatest {[weak self] _ in
                return RQ.orderPhotoList(prameters: OrderPhotoListParameters(userOrderId: (self?.userOrderId)!, orderCode: (self?.orderCode)!, taskOrderId: (self?.taskOrderId)!))
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] response in
                if response?.success == true {
                    if let data = response?.data {
                        self?.resultArr.removeAll()
                        self?.resultArr.append(contentsOf: data)
                        for section in 0..<(self?.resultArr.count ?? 0) {
                            let sectionModel = self?.resultArr[section]
                            for item in 0..<(sectionModel?.photoList.count ?? 0) {
                                let itemModel = sectionModel?.photoList[item]
                                itemModel?.taskStatus = sectionModel?.taskStatus
                            }
                        }
                        self?.additionalPhotoView.collectionView.reloadData()
                    }
                }else{
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
        
        refreshRelay.accept(nil)
        
        uploadImageRelay
            .flatMapLatest {[weak self] itemModel in
                return RQ.supplementOrderPhoto(prameters: SupplementOrderPhotoParameters(userOrderId: (self?.userOrderId)!, orderCode: (self?.orderCode)!, taskOrderId: (self?.taskOrderId)!, taskStatus: (itemModel.taskStatus)!, tag: itemModel.tag, file: (itemModel.uploadImage)!)) { multipartFormData in
                    
                    multipartFormData.append((itemModel.uploadImage)!, withName: "file",fileName: "\(String(Date.init().timeIntervalSince1970*1000)).jpg",mimeType: "image/jpeg")
                    if let data = itemModel.tag.data(using: .utf8) {
                        multipartFormData.append(data, withName: "tag")
                    }
                    
                    if let data = String((itemModel.taskStatus)!).data(using: .utf8) {
                        multipartFormData.append(data, withName: "taskStatus")
                    }
                    
                    if let data = String((self?.taskOrderId)!).data(using: .utf8) {
                        multipartFormData.append(data, withName: "taskOrderId")
                    }
                    
                    if let data = String((self?.orderCode)!).data(using: .utf8) {
                        multipartFormData.append(data, withName: "orderCode")
                    }
                    
                    if let data = String((self?.userOrderId)!).data(using: .utf8) {
                        multipartFormData.append(data, withName: "userOrderId")
                    }
                } uploadProgress: { progress in
                    
                }
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] response in
                if response?.success == true {
                    self?.refreshRelay.accept(nil)
                }else{
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
        
        // 保存至相册（带 HUD，批量保存，统一结果反馈）
        additionalPhotoView.actionView.save.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { [weak self] in
                guard let self = self else { return }
                let images = self.collectSelectedImages()
                guard !images.isEmpty else { self.view.dd_makeToast("请先选择照片"); return }

                // 显示 HUD
                let hud = ZLProgressHUD.show()

                let group = DispatchGroup()
                var successCount = 0

                images.forEach { img in
                    group.enter()
                    ZLPhotoManager.saveImageToAlbum(image: img) { isSuccess, _ in
                        if isSuccess { successCount += 1 }
                        group.leave()
                    }
                }

                group.notify(queue: .main) {
                    hud.hide()
                    if successCount == images.count {
                        self.view.dd_makeToast("已保存到相册")
                    } else if successCount == 0 {
                        // 全部失败：统一弹窗（沿用库内风格的 alert 方法）
                        self.presentSaveErrorAlert()
                    } else {
                        self.view.dd_makeToast("已保存 \(successCount)/\(images.count) 张")
                    }
                }
            })
            .disposed(by: disposeBag)

        // 分享
        additionalPhotoView.actionView.share.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { [weak self] in
                guard let self = self else { return }
                let images = self.collectSelectedImages()
                guard !images.isEmpty else { self.view.dd_makeToast("请先选择照片"); return }
                let activity = UIActivityViewController(activityItems: images, applicationActivities: nil)
                activity.modalPresentationStyle = .formSheet
                self.present(activity, animated: true)
            })
            .disposed(by: disposeBag)
    }
}

// MARK: UICollectionViewDelegate, UICollectionViewDataSource
extension AdditionalPhotoController : UICollectionViewDelegate, UICollectionViewDataSource {
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return resultArr.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let model = resultArr[section]
        return model.photoList.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? AdditionalPhotoCell
        let sectionModel = resultArr[indexPath.section]
        let itemModel = sectionModel.photoList[indexPath.item]
        cell?.titleLabel.text = itemModel.imageTitle
        cell?.backgroundImageView.sd_setImage(with: URL(string: ""))
        if let photoUrl = itemModel.photoUrl {
            cell?.uploadImageView.isHidden = false
            cell?.uploadImageView.sd_setImage(with: URL(string: photoUrl))
        }else{
            cell?.uploadImageView.isHidden = true
            cell?.uploadImageView.sd_setImage(with: nil)
        }
        cell?.takePhotoButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                ZLPhotoConfiguration.default().allowSelectVideo = false
                ZLPhotoConfiguration.default().maxSelectCount = 1
                ZLPhotoConfiguration.default().allowTakePhotoInLibrary = true
                ZLPhotoConfiguration.default().allowEditImage = false
                
                let photoPreviewSheet = ZLPhotoPreviewSheet.init()
                photoPreviewSheet.selectImageBlock = { [weak self] results, isOriginal in
                    let image = results.map { $0.image }.first
//                    let imageCreateDate = results.map { $0.asset.creationDate }.first ?? Date()
                    itemModel.uploadImage = image?.dd_compressedToData(withQulitySize: 300 * 1024)
                    self?.uploadImageRelay.accept(itemModel)
                }
                if let self {
                    photoPreviewSheet.showPhotoLibrary(sender: self)
                }
            })
            .disposed(by: cell!.disposeBag)
        cell?.takePhotoButton.isHidden = !canModify
        
        // 选择模式 UI（无图片时不显示选择按钮）
        let hasImage = (itemModel.photoUrl != nil) || ((cell?.uploadImageView.image) != nil)
        cell?.selectButton.isHidden = !isSelecting || !hasImage
        let isChecked = selectedIndexPaths.contains(indexPath)
        cell?.selectButton.isSelected = isChecked
        cell?.selectButton.setTitleColor(isChecked ? .white : UIColor.hex("#206FFF"), for: .normal)

        cell?.selectButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { [weak self] in
                guard let self = self else { return }
                // 若当前无图片，忽略点击
                guard let c = collectionView.cellForItem(at: indexPath) as? AdditionalPhotoCell, c.uploadImageView.isHidden == false else { return }
                if self.selectedIndexPaths.contains(indexPath) {
                    self.selectedIndexPaths.remove(indexPath)
                } else {
                    self.selectedIndexPaths.insert(indexPath)
                }
                if let c = collectionView.cellForItem(at: indexPath) as? AdditionalPhotoCell {
                    let checked = self.selectedIndexPaths.contains(indexPath)
                    c.selectButton.isSelected = checked
                    c.selectButton.setTitleColor(checked ? .white : UIColor.hex("#206FFF"), for: .normal)
                }
                self.updateActionViewVisibility(animated: true)
            })
            .disposed(by: cell!.disposeBag)
        return cell!
    }
    
    public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "AdditionalPhotoHeaderView", for: indexPath) as? AdditionalPhotoHeaderView
        let sectionModel = resultArr[indexPath.section]
        headerView?.titleLabel.text = String(indexPath.section + 1)+"、"+sectionModel.taskStatusString
        return headerView!
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if isSelecting {
            // 无图片的条目不允许选中
            if let c = collectionView.cellForItem(at: indexPath) as? AdditionalPhotoCell, c.uploadImageView.isHidden {
                return
            }
            if selectedIndexPaths.contains(indexPath) {
                selectedIndexPaths.remove(indexPath)
            } else {
                selectedIndexPaths.insert(indexPath)
            }
            if let c = collectionView.cellForItem(at: indexPath) as? AdditionalPhotoCell {
                let checked = selectedIndexPaths.contains(indexPath)
                c.selectButton.isSelected = checked
                c.selectButton.setTitleColor(checked ? .white : UIColor.hex("#206FFF"), for: .normal)
            }
            updateActionViewVisibility(animated: true)
            return
        }

        // 非选择模式：沿用原预览逻辑
        if let cell = collectionView.cellForItem(at: indexPath) as? AdditionalPhotoCell,
           let image = cell.uploadImageView.image {
            let vc = ZLImagePreviewController.init(datas: [image as Any],showSelectBtn: false,showBottomView: false)
            vc.modalPresentationStyle = .fullScreen
            navigationController?.present(vc, animated: true)
        }
    }
}


open class AdditionalPhotoController : ZDViewController {
    private let additionalPhotoView = AdditionalPhotoView()
    private let disposeBag = DisposeBag()
    private let refreshRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    private let uploadImageRelay = ReplayRelay<OrderPhotoListDataModel.PhotoList>.create(bufferSize: 1)
    private let userOrderId : Int
    private let orderCode : String
    private let taskOrderId : Int
    private let canModify : Bool
    private var resultArr : [OrderPhotoListDataModel] = []
    private var isSelecting = false
    private var selectedIndexPaths = Set<IndexPath>()
    private var selectButton: UIButton?
    public init(userOrderId: Int, orderCode: String, taskOrderId: Int, canModify:Bool){
        self.userOrderId = userOrderId
        self.orderCode = orderCode
        self.taskOrderId = taskOrderId
        self.canModify = canModify
        super.init(nibName: nil, bundle: nil)
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationItemTitle = "工单照片"
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        dd_navigationBarBarButtonItemAttributes = [.foregroundColor : UIColor.white]

        addSubviews()
        addActions()
        let selectButton = UIButton(type: .system)
        selectButton.setTitle("选择", for: .normal)
        selectButton.setTitleColor(.white.alpha(0.7), for: .normal)
        selectButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        selectButton.addTarget(self, action: #selector(toggleSelectMode), for: .touchUpInside)
        let barButton = UIBarButtonItem(customView: selectButton)
        navigationItem.rightBarButtonItem = barButton
        self.selectButton = selectButton
    }
    
    func addSubviews() {
        view.backgroundColor = .white
        view.addSubview(additionalPhotoView)
        additionalPhotoView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(-view.safeAreaInsets.bottom - auto(10))
        }
        
        additionalPhotoView.collectionView.register(AdditionalPhotoCell.self, forCellWithReuseIdentifier: "cell")
        additionalPhotoView.collectionView.register(AdditionalPhotoHeaderView.self, forSupplementaryViewOfKind: DDCollectionView.elementKindSectionHeader, withReuseIdentifier: "AdditionalPhotoHeaderView")
        additionalPhotoView.collectionView.delegate = self
        additionalPhotoView.collectionView.dataSource = self
    }
    
    @objc private func toggleSelectMode() {
        if isSelecting { cancelSelectMode() } else { enterSelectMode() }
    }
    private func enterSelectMode() {
        isSelecting = true
        selectedIndexPaths.removeAll()
        selectButton?.setTitle("取消", for: .normal)
        updateActionViewVisibility(animated: true)
        additionalPhotoView.collectionView.reloadData()
    }
    private func cancelSelectMode() {
        isSelecting = false
        selectedIndexPaths.removeAll()
        selectButton?.setTitle("选择", for: .normal)
        updateActionViewVisibility(animated: true)
        additionalPhotoView.collectionView.reloadData()
    }
    private func updateActionViewVisibility(animated: Bool) {
        let shouldShow = isSelecting && !selectedIndexPaths.isEmpty
        let targetHeight: CGFloat = shouldShow ? 50 : 0
        additionalPhotoView.actionView.isHidden = (targetHeight == 0)
        additionalPhotoView.actionHeightConstraint?.update(offset: targetHeight)
        if isSelecting {
            if !selectedIndexPaths.isEmpty {
                selectButton?.setTitle("取消", for: .normal)
            } else {
                selectButton?.setTitle("取消", for: .normal)
            }
        } else {
            selectButton?.setTitle("选择", for: .normal)
        }
        if animated {
            UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() }
        } else {
            self.view.layoutIfNeeded()
        }
    }
    private func collectSelectedImages() -> [UIImage] {
        var images: [UIImage] = []
        for indexPath in selectedIndexPaths {
            let sectionModel = resultArr[indexPath.section]
            let itemModel = sectionModel.photoList[indexPath.item]
            if let cell = additionalPhotoView.collectionView.cellForItem(at: indexPath) as? AdditionalPhotoCell,
               let img = cell.uploadImageView.image {
                images.append(img)
            } else if let urlString = itemModel.photoUrl,
                      let url = URL(string: urlString),
                      let data = try? Data(contentsOf: url),
                      let img = UIImage(data: data) {
                images.append(img)
            }
        }
        return images
    }

    private func presentSaveErrorAlert() {
        let alert = UIAlertController(title: nil, message: "图片保存失败，请检查相册权限", preferredStyle: .alert)
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let confirm = UIAlertAction(title: "确定", style: .default, handler: { _ in
            UrlLinks.default.openSetting()
        })
        alert.addAction(cancel)
        alert.addAction(confirm)
        self.present(alert, animated: true)
    }
}


open class AdditionalPhotoView : DDView {
    public var collectionView : DDCollectionView
    public var actionView : AdditionalPhotoActionView
    public var actionHeightConstraint : Constraint?

    public override init(frame: CGRect) {
        let flowLayout = UICollectionViewFlowLayout.init()
        flowLayout.itemSize = CGSize(width: auto(165), height: auto(100))
        flowLayout.headerReferenceSize = CGSizeMake(0, auto(30))
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumLineSpacing = auto(10)
        flowLayout.sectionInset = UIEdgeInsets(top: auto(10), left: auto(15), bottom: auto(10), right: auto(15))
        collectionView = DDCollectionView(frame: .zero, collectionViewLayout: flowLayout)
        actionView = AdditionalPhotoActionView()
        super.init(frame: frame)
        
        collectionView.backgroundColor = .white
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        actionView.isHidden = true
        addSubview(actionView)
        actionView.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
            self.actionHeightConstraint = make.height.equalTo(0).constraint
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class AdditionalPhotoCell : DDCollectionViewCell {
    public let titleLabel : DDLabel
    public let backgroundImageView : DDImageView
    public let backgroundCoverView : DDView
    public let stateView : DDView
    public let stateLabel : DDLabel
    public let takePhotoButton : DDButton
    public let uploadImageView : DDImageView
    public let selectButton : DDButton
    public var disposeBag = DisposeBag()
    
    public override init(frame: CGRect) {
        titleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("8B8A8B"))
        backgroundImageView = DDImageView.init()
        backgroundCoverView = DDView.init()
        stateView = DDView.init()
        stateLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(12)), textColor: .white)
        takePhotoButton = DDButton.dd_initCustom()
        uploadImageView = DDImageView.init()
        selectButton = DDButton.dd_initCustom()
        super.init(frame: .zero)
        
        titleLabel.numberOfLines = 2
        addSubview(titleLabel)
        backgroundImageView.layer.borderColor = UIColor.hex("000000").alpha(0.1).cgColor
        backgroundImageView.layer.borderWidth = 0.5
        backgroundImageView.layer.cornerRadius = auto(4)
        backgroundImageView.layer.masksToBounds = true
        backgroundImageView.isUserInteractionEnabled = true
        addSubview(backgroundImageView)
        
        backgroundCoverView.backgroundColor = .white.alpha(0.3)
        backgroundImageView.addSubview(backgroundCoverView)
        stateView.backgroundColor = .hex("000000").alpha(0.5)
        backgroundImageView.addSubview(stateView)
        stateLabel.text = "补充"
        backgroundImageView.addSubview(stateLabel)
        uploadImageView.isHidden = true
        uploadImageView.isUserInteractionEnabled = true
        backgroundImageView.addSubview(uploadImageView)
        
        takePhotoButton.setImage(UIImage(named: "additionalPhotot_takePhoto"), for: .normal)
        backgroundImageView.addSubview(takePhotoButton)
        
        backgroundImageView.addSubview(selectButton)
        selectButton.setImage(UIImage(named: "refuseOrder_reason_unselected"), for: .normal)
        selectButton.setImage(UIImage(named: "refuseOrder_reason_selected"), for: .selected)
        selectButton.isHidden = true
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(auto(5))
            make.right.equalTo(-auto(5))
            make.top.equalTo(0)
        }
        
        backgroundImageView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(auto(5))
            make.left.equalToSuperview().offset(auto(5))
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        backgroundCoverView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        stateView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(auto(25))
        }
        
        stateLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(stateView)
        }
        
        takePhotoButton.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.height.width.equalTo(auto(40))
        }
        
        uploadImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        selectButton.snp.makeConstraints { make in
            make.top.right.equalToSuperview().inset(0)
            make.width.height.equalTo(auto(30))
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        selectButton.isSelected = false
        selectButton.isHidden = true
        disposeBag = DisposeBag()
    }
}

open class AdditionalPhotoHeaderView : DDCollectionViewCell {
    public let titleLabel : DDLabel
    
    public override init(frame: CGRect) {
        titleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(14)), textColor: .hex("000000").alpha(0.85))
        super.init(frame: .zero)
        
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(auto(20))
            make.centerY.equalToSuperview()
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class AdditionalPhotoActionView : UIView {
    public let save : UIButton = UIButton(type: .custom)
    public let share : UIButton = UIButton(type: .custom)
    private let topSeparator = UIView()
    private let middleSeparator = UIView()
    override init(frame: CGRect) {
        super.init(frame: frame)
        buildUI()
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        buildUI()
    }
    
    func buildUI() {
        // Top horizontal separator
        topSeparator.backgroundColor = UIColor.hex("E5E6EB")
        addSubview(topSeparator)
        topSeparator.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(1.0 / UIScreen.main.scale)
        }

        save.setTitle("保存至相册", for: .normal)
        save.setTitleColor(.black, for: .normal)
        save.titleLabel?.font = .dd_systemFont(ofSize: 16, weight: .medium)
        addSubview(save)
        share.setTitle("分享", for: .normal)
        share.setTitleColor(.black, for: .normal)
        share.titleLabel?.font = .dd_systemFont(ofSize: 16, weight: .medium)
        addSubview(share)
        save.snp.makeConstraints { make in
            make.centerX.equalToSuperview().multipliedBy(0.5)
            make.centerY.equalToSuperview()
        }
        share.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview().multipliedBy(1.5)
        }

        // Middle vertical separator
        middleSeparator.backgroundColor = UIColor.hex("E5E6EB")
        addSubview(middleSeparator)
        middleSeparator.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(1.0 / UIScreen.main.scale)
            make.height.equalTo(24)
        }
    }
}
