package com.cr.pages

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import cn.carbs.android.segmentcontrolview.library.SegmentControlView
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.contrarywind.listener.OnItemSelectedListener
import com.cr.common.CrUnitManager
import com.cr.common.DataManager
import com.cr.cruav.CrApplication
import com.cr.cruav.R
import com.cr.data.CrConfig
import com.cr.data.CrUtil
import com.cr.dialog.DialogLoadingUtil
import com.cr.map.CaseModel
import com.cr.map.EventMap
import com.cr.map.MapAction
import com.cr.models.SelModel
import com.cr.models.SubmitCaseModel
import com.cr.network.NetManager
import com.cr.network.TCPDataTask
import com.cr.view.CrViewWheel
import com.cr.widget.CrImageBrowserWidget
import dji.v5.utils.common.ContextUtil
import org.json.JSONArray

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/8/18 10:26
 * 描述：案件上传页面
 */
class FragmentUploadAction : CrNavigationFragment(), View.OnClickListener {
    // todo: 2023/8/18 控件定义
    private var btnAsyncCaseType: Button? = null // define: 2023/8/18 同步案件类型按钮
    private var btnAsyncCaseDesc: Button? = null // define: 2023/8/18 同步案件描述信息按钮
    private var wheelCaseType: CrViewWheel? = null // define: 2023/8/18 案件类型选择器
    private var wheelCaseDesc: CrViewWheel? = null // define: 2023/8/18 案件描述选择器
    private var lblMessage: TextView? = null  // define: 2023/8/23 信息显示
    private var lblLongitude: TextView? = null // define: 2023/8/25 经度
    private var lblLatitude: TextView? = null // define: 2023/8/25 纬度
    private var lblAngle: TextView? = null // define: 2023/8/25 角度
    private var lblAltitude: TextView? = null // define: 2023/8/25 高度
    private var imageBrowser: CrImageBrowserWidget? = null // define: 2023/8/26 图片浏览器
    private var btnSubmit: LinearLayout? = null // define: 2023/8/26 上传按钮
    private var progressBar: ProgressBar? = null // define: 2023/8/28 进度条
    private var lblProgress: TextView? = null // define: 2023/8/28 进度条文字提示
    private var segmentSubmitType: SegmentControlView? = null // define: 2023/9/1 上传方式
    private var segmentConstructProgress:SegmentControlView?=null // define: 2023/9/1 建设程度

    // todo: 2023/8/23 变量定义
    private var caseSubmitDescriptionList: List<SelModel>? = null // define: 2023/8/23 案件上传描述信息列表
    private var caseTypeList: List<SelModel>? = null // define: 2023/8/24 案件类型列表
    private var adapterCaseType: ArrayWheelAdapter<String>? = null // define: 2023/8/24 案件类型适配器
    private var adapterCaseDesc: ArrayWheelAdapter<String>? = null // define: 2023/8/24 案件描述适配器
    private var itemsCaseType: MutableList<String>? = null // define: 2023/8/24 案件类型数据集
    private var itemsCaseDesc: MutableList<String>? = null // define: 2023/8/24 案件描述信息数据集
    private var joinCase: CaseModel? = null // define: 2023/8/25 关联的案件
    private var caseType: String? = null // define: 2023/9/1 案件类型
    private var caseDesc: String? = null // define: 2023/9/1 案件描述
    private var strSubmitType:String = "ADD"  // define: 2023/9/1 上传案件方式
    private var strConstructProgress:String = "在建"  // define: 2023/9/1 建设程度

    /**
     * 初始化
     * @param inflater LayoutInflater
     * @param container ViewGroup?
     * @param savedInstanceState Bundle?
     * @return View?
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        self = this
        mainView = inflater.inflate(R.layout.frag_case_upload_upload, null)
        // todo: 2023/8/18 挂载控件
        joinControls()
        // todo: 2023/8/24 初始化页面
        initPage()
        return mainView
    }

    /**
     * 挂载控件 覆写
     */
    override fun joinControls() {
        super.joinControls()
        mainView?.let {
            btnAsyncCaseType = it.findViewById(R.id.btn_async_case_type)
            btnAsyncCaseDesc = it.findViewById(R.id.btn_async_desc)
            btnAsyncCaseType?.setOnClickListener(this)
            btnAsyncCaseDesc?.setOnClickListener(this)
            wheelCaseType = it.findViewById(R.id.wheel_case_type)
            wheelCaseDesc = it.findViewById(R.id.wheel_case_desc)
            setWheel(wheelCaseType!!, listenerWheelCaseType)
            setWheel(wheelCaseDesc!!, listenerWheelCaseDesc)
            lblMessage = it.findViewById(R.id.lbl_message)
            lblLongitude = it.findViewById(R.id.lbl_longitude)
            lblLatitude = it.findViewById(R.id.lbl_latitude)
            lblAngle = it.findViewById(R.id.lbl_angle)
            lblAltitude = it.findViewById(R.id.lbl_altitude)
            // todo: 2023/8/26 挂接图片浏览器
            imageBrowser = it.findViewById(R.id.image_browser)
            // todo: 2023/8/26 挂载上传按钮
            btnSubmit = it.findViewById(R.id.btn_submit)
            btnSubmit?.setOnClickListener(this)
            // todo: 2023/8/28 挂载进度条
            progressBar = it.findViewById(R.id.progress_bar)
            lblProgress = it.findViewById(R.id.lbl_progress)
            // todo: 2023/9/1 挂载上传方式及建设程度控件
            segmentSubmitType = it.findViewById(R.id.segment_submit_type)
            segmentConstructProgress = it.findViewById(R.id.segment_construct_progress)
            segmentSubmitType?.setOnSegmentChangedListener(segmentSubmitTypeListener)
            segmentConstructProgress?.setOnSegmentChangedListener(segmentConstructProgressListener)
        }
    }

    /**
     * 页面初始化
     */
    override fun initPage() {
        super.initPage()
        // todo: 2023/8/24 初始化选择器
        itemsCaseDesc = mutableListOf()
        adapterCaseDesc = ArrayWheelAdapter(itemsCaseDesc)
        wheelCaseDesc?.adapter = adapterCaseDesc
        // todo: 2023/8/25 同步本地案件描述
        syncLocalCaseDescription()

        itemsCaseType = mutableListOf()
        adapterCaseType = ArrayWheelAdapter(itemsCaseType)
        wheelCaseType?.adapter = adapterCaseType
        // todo: 2023/8/25 同步显示本地案件类型
        syncLocalCaseType()

        // todo: 2023/8/25 同步关联案件显示
        updateCaseView()
    }

    /**
     * 设置选择器
     * @param wheel CrViewWheel 选择器
     * @param listener OnItemSelectedListener 监听
     */
    private fun setWheel(wheel: CrViewWheel, listener: OnItemSelectedListener) {
        wheel.setTextColorCenter(Color.YELLOW) // TODO: 4/17/21 设置选中项颜色
        wheel.setItemsVisibleCount(5)
        wheel.setTextSize(CrUtil.getDimens(R.dimen.sp_6))
        wheel.setTypeface(CrUtil.getFont(ContextUtil.getContext()))
        wheel.setCyclic(false) // TODO: 6/9/21 禁止循环
        wheel.setOnItemSelectedListener(listener)
    }

    /**
     * 案件类型选择器监听
     */
    private val listenerWheelCaseType = OnItemSelectedListener { index ->
        caseType = caseTypeList!![index].name
    }

    /**
     * 案件描述选择器监听
     */
    private val listenerWheelCaseDesc = OnItemSelectedListener { index ->
        caseDesc = caseSubmitDescriptionList!![index].name
    }

    /**
     * 显示消息
     * @param message String 消息内容
     */
    private fun setMessage(message: String) {
        mainHandler.post {
            lblMessage?.text = "${CrUnitManager.toSystemYMDHMSDate()} $message"
        }
    }

    /**
     * 同步本地案件描述信息
     */
    private fun syncLocalCaseDescription() {
        caseSubmitDescriptionList = DataManager.getCaseSubmitDescription()
        itemsCaseDesc!!.clear()
        for (model in caseSubmitDescriptionList!!) {
            itemsCaseDesc?.add(model.name!!)
        }
        wheelCaseDesc?.setSelectItem(itemsCaseDesc!![0])
        wheelCaseDesc?.onItemSelected()
    }

    /**
     * 同步本地案件类型
     */
    private fun syncLocalCaseType() {
        caseTypeList = DataManager.getCaseType()
        itemsCaseType!!.clear()
        for (model in caseTypeList!!) {
            itemsCaseType?.add(model.name!!)
        }
        wheelCaseType?.setSelectItem("违章建筑")
        // todo: 2023/9/1 赋值
        wheelCaseType?.onItemSelected()
    }

    /**
     * 同步案件描述信息
     */
    private fun asyncCaseDescription() {
        TCPDataTask.getInstance().sendJSON(
            NetManager.getServerUrl("appQueryCaseDescription"),
            CrConfig.user!!,
            object : TCPDataTask.IChangeCallback {
                // todo: 2023/8/23 成功
                override fun onSuccess(jsonArray: JSONArray) {
                    var list = SelModel.fromJSONArray(jsonArray)
                    if (DataManager.saveCaseSubmitDescription(list!!)) {
                        setMessage("案件描述信息同步成功！")
                        syncLocalCaseDescription()
                    } else {
                        setMessage("案件描述信息同步成功，本地化存储失败！")
                    }
                }

                // todo: 2023/8/23 失败
                override fun onFailed(message: String) {
                    showError(message)
                }

            },
            "获取中..."
        )
    }

    /**
     * 同步案件类型信息
     */
    private fun asyncCaseType() {
        TCPDataTask.getInstance().sendJSON(
            NetManager.getServerUrl("appQueryCaseSource"),
            CrConfig.user!!,
            object : TCPDataTask.IChangeCallback {
                // todo: 2023/8/23 成功
                override fun onSuccess(jsonArray: JSONArray) {
                    var list = SelModel.fromJSONArray(jsonArray)
                    if (DataManager.saveCaseType(list!!)) {
                        setMessage("案件类型同步成功！")
                        syncLocalCaseType()
                    } else {
                        setMessage("案件类型同步成功，本地化存储失败！")
                    }
                }

                // todo: 2023/8/23 失败
                override fun onFailed(message: String) {
                    showError(message)
                }

            },
            "获取中..."
        )
    }

    /**
     * 重写点击事件
     * @param view View 视图
     */
    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.btn_async_desc -> {
                // todo: 2023/8/23 同步描述信息
                asyncCaseDescription()
            }
            R.id.btn_async_case_type -> {
                // todo: 2023/8/24 同步案件类型
                asyncCaseType()
            }
            R.id.btn_submit -> {
                // todo: 2023/8/26 提报
                submit()
            }
        }
    }

    /**
     * 检查上传信息
     * @return SubmitCaseModel?
     */
    private fun checkSubmitInfo(): SubmitCaseModel? {
        if (caseDesc == null) {
            showError("请选择案件描述信息！")
            return null
        }
        if (caseType == null) {
            showError("请选择案件类型信息！")
            return null
        }
        var resModel = SubmitCaseModel(CrConfig.user!!.userId!!)
        resModel.name = joinCase!!.name!!
        resModel.longitude = joinCase!!.longitude!!
        resModel.latitude = joinCase!!.latitude!!
        resModel.altitude = joinCase!!.altitude!!
        resModel.angle = joinCase!!.angle!!
        resModel.joinCaseId = joinCase!!.joinNetCaseAJHArray!!.joinToString(",")
        resModel.joinPolygon = joinCase!!.joinPolygon!!.coords!!
        resModel.caseArea = joinCase!!.joinPolygon!!.area!!
        resModel.submitType = strSubmitType
        resModel.constructProgress = strConstructProgress
        return resModel
    }

    /**
     * 案件上传方式选择监听
     */
    private val segmentSubmitTypeListener =
        SegmentControlView.OnSegmentChangedListener { newSelectedIndex ->
            when(newSelectedIndex){
                0->{
                    strSubmitType = "ADD"
                }
                1->{
                    strSubmitType = "UPP"
                }
            }
        }

    /**
     * 案件建设程度选择监听
     */
    private val segmentConstructProgressListener =
        SegmentControlView.OnSegmentChangedListener { newSelectedIndex ->
            when(newSelectedIndex){
                0->{
                    strSubmitType = "在建"
                }
                1->{
                    strSubmitType = "完工"
                }
            }
        }

    /**
     * 提报
     */
    private fun submit() {
        // todo: 2023/9/1 检查上传信息
        var submitCaseModel: SubmitCaseModel? = checkSubmitInfo() ?: return
        var filePathList = mutableListOf<String>()
        // todo: 2023/8/28 加入文件
        for (name in joinCase?.imgArray!!) {
            filePathList.add("${CrUtil.IMAGE_PATH}${name}")
            // todo: 2023/9/1 挂载上报照片名称
            submitCaseModel?.submitImages += "${name};"
        }
        TCPDataTask.getInstance().sendUploadFiles(
            NetManager.getServerUrl("appUploadCase"),
            filePathList,
            submitCaseModel!!,
            object : TCPDataTask.IProgressCallback {
                // todo: 2023/8/28 开始
                override fun onStart() {
                    DialogLoadingUtil.show(CrApplication.getContext(),"案件上传中...")
                }

                // todo: 2023/8/28 上传失败
                override fun onFailed(message: String) {
                    DialogLoadingUtil.dismiss()
                    showError(message)
                }

                // todo: 2023/8/28 上传进度
                override fun onProgress(progress: Long, total: Long) {
                    progressBar?.max = total.toInt()
                    progressBar?.progress = progress.toInt()
                    // todo: 2023/8/31 显示上传进度
                    var jd = (progress * 1f / total * 1f) * 100;
                    lblProgress?.text = String.format("%.2f", jd) + "%";
                }

                // todo: 2023/8/28 上传完成
                override fun onSuccess(message: String) {
                    DialogLoadingUtil.dismiss()
                    // todo: 2023/9/27 通知地图更新
                    CrApplication.getEventBus().post(EventMap(MapAction.EventCaseUploadSuccess,joinCase))
                    // todo: 2023/9/27 底部信息
                    setMessage(message)
                }
            })
    }

    /**
     * 更新关联案件信息展示
     */
    private fun updateCaseView() {
        this.joinCase?.let {
            // todo: 2023/8/25 设置显示
            lblLongitude?.text = String.format("%.6f", it.longitude)
            lblLatitude?.text = String.format("%.6f", it.latitude)
            lblAngle?.text = String.format("%.3f", it.angle)
            lblAltitude?.text = String.format("%.3f", it.altitude)
            // todo: 2023/8/26 挂接关联照片
            for (fileName in it.imgArray!!) {
                val filePath = "${CrUtil.IMAGE_PATH}${fileName}"
                imageBrowser?.crAppendImage(filePath)
            }
        }
    }

    /**
     * 设置关联的案件
     * @param joinCase CaseModel 案件
     */
    fun crSetJoinCase(joinCase: CaseModel) {
        this.joinCase = joinCase;
        // todo: 2023/9/1 打印
        this.joinCase?.joinPolygon?.toString()?.let { CrUtil.print(it) }
        updateCaseView()
    }
}