//
//  PhotoDetailViewController.swift
//  MCPlus
//
//  Created by seo ha on 07/02/2019.
//  Copyright © 2019 KangSH. All rights reserved.
//

import UIKit

class PhotoDetailViewController: UIViewController {
    
    @IBOutlet weak var closeButton: UIImageView!{
        didSet{
            closeButton.addTapGestureRecognizer(action: self.closeAction)
        }
    }
    
    @IBOutlet weak var scrollView: UIScrollView!{
        didSet{
            scrollView.delegate = self
        }
    }
    
    @IBOutlet weak var imageView: UIImageView!
    
    @IBOutlet weak var patientIdLabel :UILabel!{
        didSet{
            patientIdLabel.text = self.photo?.user?.patientId
        }
    }
    
    @IBOutlet weak var patientNmLabel :UILabel!{
        didSet{
            patientNmLabel.text = self.photo?.user?.patientNm
        }
    }
    
    @IBOutlet weak var ageGenderLabel :UILabel!{
        didSet{
            ageGenderLabel.text = "\(self.photo?.user?.age ?? "") / \(self.photo?.user?.gender ?? "")"
        }
    }
    
    @IBOutlet weak var titleLabel: UILabel!{
        didSet{
            titleLabel.text = self.photo?.key
        }
    }
    
    @IBOutlet weak var exitButton: UIButton!{
        didSet{
            exitButton.addTapGestureRecognizer(action: self.closeAction)
        }
    }
    
    @IBOutlet weak var uploadButton: UIButton!{
        didSet{
            if self.photo?.isSended == true{
                uploadButton.isHidden = true
            }
            uploadButton.addTapGestureRecognizer(action: self.uploadAction)
        }
    }
    
    @IBOutlet weak var deptNmLabel: UILabel!{
        didSet{
            PictureViewController.deptNm.signal.observe { [weak deptNmLabel](item) in
                guard let value = item.value as? String else{ return }
                let attr = deptNmLabel?.attributedText?.attributes(at: 0, effectiveRange: nil)
                let attrString = NSMutableAttributedString(string: value, attributes: attr)
                deptNmLabel?.attributedText = attrString
            }
        }
    }
    
    @IBOutlet weak var treatClsKrLabel: UILabel!{
        didSet{
            PictureViewController.treatClsKr.signal.observe { [weak treatClsKrLabel](item) in
                guard let value = item.value as? String else{ return }
                let attr = treatClsKrLabel?.attributedText?.attributes(at: 0, effectiveRange: nil)
                let attrString = NSMutableAttributedString(string: value, attributes: attr)
                treatClsKrLabel?.attributedText = attrString
            }
        }
    }
    
    @IBOutlet weak var doctorNmLabel: UILabel!{
        didSet{
            PictureViewController.doctorNm.signal.observe { [weak doctorNmLabel](item) in
                guard let value = item.value as? String else{ return }
                let attr = doctorNmLabel?.attributedText?.attributes(at: 0, effectiveRange: nil)
                let attrString = NSMutableAttributedString(string: value, attributes: attr)
                doctorNmLabel?.attributedText = attrString
            }
        }
    }
    
    
    var image:UIImage?
    var photo:Photo?
    var callBack:(()->Void)?
}

extension PhotoDetailViewController:UIScrollViewDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.isNavigationBarHidden = true
        if let img = self.image{
            self.imageView.image = img
        }
    }
    
    func closeAction(){
        self.navigationController?.popViewController(animated: true)
        self.callBack?()
    }
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return scrollView.subviews.first
    }
    
    func uploadAction(){
        guard let photo = self.photo else {
            return
        }
        self.uploadItem(photo)
    }
    
    func uploadItem(_ photo:Photo){
        var param = [String:Any]()
        param["hospitalCd"] = photo.user?.hospitalCD ?? ""
        param["userId"] = photo.user?.userId ?? ""
        param["patientId"] = photo.user?.patientId ?? ""
        param["deptCd"] = photo.user?.deptCd ?? ""
        param["doctorId"] = photo.user?.doctorId ?? ""
        param["searchCls"] = photo.user?.treatCls ?? ""
        param["thumbnail"] = ""
        param["excutionDtTm"] = Date().fromString(format: "yyyy-MM-dd hh:mm:ss")
        param["visitDt"] = photo.user?.visitDt ?? ""
        
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            //원본 이미지 찾기
            let origin = dir.appendingPathComponent("kunkuk/\(photo.file ?? "")")
            if let data = try? Data(contentsOf: origin){
                
                param["image"] = String(data: data, encoding: .utf8)
            }
        }
        
        
        let url = "\(MCarePlusConstants.DOMAIN_NAME)/\(photo.user?.serviceUrl ?? "")"
        APIClient(url)
            .param(reqParam: param)
            .enType(.json)
            .connect { [weak self](result:[String:Any]) in
                
                guard let `result` = result["result"] as? [[String:Any]] else{ return }
                let returnCd = result.first?["returnCd"] as? String
                //성공일시
                if returnCd == "0000"{
                    photo.isSended = true
                    photo.update()
                    self?.showAlert("서버에 업로드 되었습니다.", "", "확인", nil, { action in
                        self?.closeAction()
                    })
                }else{
                    self?.showAlert("서버업로드에 실패하였습니다. 관리자에게 문의하여 주세요.", "", "확인", nil, { action in
                        self?.closeAction()
                    })
                }
        }
        
        
        
        
    }
}
