//
//  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

extension AdditionalPhotoController{
    func addActions() {
        refreshRelay
            .flatMapLatest {[weak self] _ in
                return RQ.orderPhotoList(prameters: OrderPhotoList(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: SupplementOrderPhoto(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))",mimeType: "text/plain")
                    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)
    }
}

// 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: 1048576)
                    self?.uploadImageRelay.accept(itemModel)
                }
                if let self {
                    photoPreviewSheet.showPhotoLibrary(sender: self)
                }
            })
            .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!
    }
}


open class AdditionalPhotoController : DDViewController {
    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 var resultArr : [OrderPhotoListDataModel] = []
    public init(userOrderId: Int, orderCode: String, taskOrderId: Int){
        self.userOrderId = userOrderId
        self.orderCode = orderCode
        self.taskOrderId = taskOrderId
        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)]
        
        addSubviews()
        addActions()
    }
    
    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
    }
}


open class AdditionalPhotoView : DDView {
    public var collectionView : DDCollectionView
    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)
        super.init(frame: frame)
        
        collectionView.backgroundColor = .white
        addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
    }
    
    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 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()
        super.init(frame: .zero)
        
        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)
        
        titleLabel.snp.makeConstraints { make in
            make.left.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()
        }
        
        uploadImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        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")
    }
}
