package com.sybotan.android.demo.activities

import android.Manifest
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import com.framework.mvvm.model.vo.AdmRequest
import com.framework.mvvm.model.vo.Building
import com.framework.mvvm.mv.AdmViewModel
import com.google.gson.Gson
import com.sybotan.android.demo.R
import com.sybotan.android.demo.activities.poc.SceneActivity
import com.sybotan.android.demo.activities.poc.SpaceActivity
import com.sybotan.android.demo.bean.AutoUpDateBean
import com.sybotan.android.demo.tools.CommonUtils
import com.sybotan.android.demo.tools.DownLoadApk
import com.sybotan.android.demo.tools.LocalDataOperation
import com.sybotan.android.demo.viewmodel.GraphyVM
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jetbrains.anko.startActivity
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import org.kodein.di.android.x.viewmodel.viewModel
import org.kodein.di.instance
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat

class PocActivity : BaseActivity(), DIAware {

    override val di: DI by closestDI()

    private val mVm: AdmViewModel by viewModel()
    private val sp: SharedPreferences by instance()
    private var autoUpDateBean: AutoUpDateBean.Content? = null

    private val REQUEST_EXTERNAL_STORAGE = 1 // 不可改

    private lateinit var downloadBtn: Button

    private lateinit var uploadBtn: Button

    private lateinit var dictBtn: Button

    private lateinit var configBtn: Button

    private lateinit var frameBtn: Button

    private lateinit var space3DBtn: Button

    private lateinit var scene3DBtn: Button

    private lateinit var version: TextView

    private lateinit var unUploadTv: TextView
    private lateinit var unUploadLabelTv: TextView

    // 测试用，后期动态设置
    /* private val request =
         AdmRequest(userId = "admjd", projectId = "Pj9909990002", groupCode = "JD")
 */
    @RequiresApi(Build.VERSION_CODES.R)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_poc)
        checkStoragePermission()
        val bundle = intent.getBundleExtra("project")!!
        val userId = bundle.getString("userId")!!
        val projectId = bundle.getString("projectId")!!
        val groupCode = bundle.getString("groupCode")!!
        val request = AdmRequest(userId = userId, projectId = projectId, groupCode = groupCode)

        downloadBtn = findViewById(R.id.downloadBtn)
        uploadBtn = findViewById(R.id.uploadBtn)
        dictBtn = findViewById(R.id.dictBtn)
        configBtn = findViewById(R.id.configBtn)
        frameBtn = findViewById(R.id.frameBtn)
        space3DBtn = findViewById(R.id.space3DBtn)
        scene3DBtn = findViewById(R.id.scene3DBtn)

        version = findViewById(R.id.version)
        unUploadTv = findViewById(R.id.unUploadTv)
        unUploadLabelTv = findViewById(R.id.unUploadLabelTv)

        space3DBtn.setOnClickListener {
            val intent = Intent(this, SpaceActivity::class.java)
            intent.putExtra("is3D", true)
            startActivity(intent)
        }
        scene3DBtn.setOnClickListener {
            val intent = Intent(this, SceneActivity::class.java)
            intent.putExtra("is3D", true)
            startActivity(intent)
        }

        lifecycleScope.launchWhenStarted {
            val unUploadNum = mVm.getNoDoneTaskByProjectId(projectId)
            unUploadTv.text = "$unUploadNum"
            if (unUploadNum > 0) {
                unUploadLabelTv.setTextColor(Color.RED)
                unUploadTv.setTextColor(Color.RED)
            } else {
                unUploadLabelTv.setTextColor(resources.getColor(R.color.black_1F2429))
                unUploadTv.setTextColor(resources.getColor(R.color.black_1F2429))
            }

        }

        downloadBtn.setOnClickListener {
            mVm.downloadBuilding(request, sp) {
                // ToastUtils.showMyToast("下载完成")
                val builder = AlertDialog.Builder(this)
                val dialog = builder.setMessage("建筑数据下载成功")
                    .setPositiveButton("确定") { dialog, id ->
                        dialog.dismiss()
                    }.create()
                dialog.show()
            }
            // 单独下载一边关系数据
            mVm.downloadBuilding(request, sp, true)
        }

        uploadBtn.setOnClickListener {
            lifecycleScope.launch(Dispatchers.IO) {
                LocalDataOperation.getInstance().offlineSendRequest.uploadImageNew(this@PocActivity)
            }
            mVm.uploadBuilding(
                request, block = {
                    // ToastUtils.showMyToast("建筑数据上传成功")
                    val builder = AlertDialog.Builder(this)
                    val dialog = builder.setMessage("建筑数据上传成功")
                        .setPositiveButton("确定") { dialog, id ->
                            dialog.dismiss()
                        }.create()
                    dialog.show()

                    lifecycleScope.launch {
                        val unUploadNum = mVm.getNoDoneTaskByProjectId(projectId)
                        unUploadTv.text = "$unUploadNum"
                        if (unUploadNum > 0) {
                            unUploadLabelTv.setTextColor(Color.RED)
                            unUploadTv.setTextColor(Color.RED)
                        } else {
                            unUploadLabelTv.setTextColor(resources.getColor(R.color.black_1F2429))
                            unUploadTv.setTextColor(resources.getColor(R.color.black_1F2429))
                        }
                    }

                },
                log = { msg: String, building: Building? ->
                    val dir = getExternalFilesDir("log")
                    if (dir == null || !dir.exists()) {
                        dir?.mkdir()
                    }

                    val writer = FileWriter(
                        File(
                            dir,
                            "${
                                SimpleDateFormat("YYYY年MM月dd日 HH:mm:ss").format(
                                    System.currentTimeMillis()
                                )
                            }-${request.projectId}.${building?.buildingId ?: ""}.log"
                        )
                    )
                    writer.use {
                        it.append(msg)
                        it.append("\n")
                        val json = Gson().toJson(building)
                        it.append(json)
                    }
                }
            )
        }

        dictBtn.setOnClickListener {
            mVm.requestDict(
                request
            ) {
                val builder = AlertDialog.Builder(this)
                val dialog = builder.setMessage("数据字典下载成功")
                    .setPositiveButton("确定") { dialog, id ->
                        dialog.dismiss()
                    }.create()
                dialog.show()
            }
        }

        configBtn.setOnClickListener {
            mVm.requestConfig(
                request
            ) {
                val builder = AlertDialog.Builder(this)
                val dialog = builder.setMessage("配置信息下载成功")
                    .setPositiveButton("确定") { dialog, id ->
                        dialog.dismiss()
                    }.create()
                dialog.show()
            }
        }

        frameBtn.setOnClickListener {
            mVm.requestFrame(
                request
            ) {
                val builder = AlertDialog.Builder(this)
                val dialog = builder.setMessage("框架数据下载成功")
                    .setPositiveButton("确定") { dialog, id ->
                        dialog.dismiss()
                    }.create()
                dialog.show()
            }
        }


        val spaceCL = findViewById<ConstraintLayout>(R.id.spaceCL)
        spaceCL.setOnClickListener {
            startActivity<SpaceActivity>()
        }

        val sceneCL = findViewById<ConstraintLayout>(R.id.sceneCL)
        sceneCL.setOnClickListener {
            startActivity<SceneActivity>()
        }

        version.setText("版本号：${CommonUtils.getVersionName(this)}")

//        mVm.requestBuilding(
//            AdmRequest(
//                userId = "bdtp",
//                projectId = "Pj0002220011",
//                groupCode = "BR",
//                buildingId = "Bd0002220002bcaa181bd406439c9ecaddac13b0d543"
//            )
//        )
        val viewModel = GraphyVM(this.application, { name, params ->
            when (name) {
                GraphyVM.UPDATE_APP -> {
                    autoUpDateBean = params as AutoUpDateBean.Content
                    if (!CommonUtils.IsNull(autoUpDateBean)
                        && Integer.valueOf(autoUpDateBean!!.getBuild()) > Integer.valueOf(
                            CommonUtils.getVersionMsg(this).get(0)
                        )
                    ) { //需要更新
                        downUrl(
                            "https://edition.persagy.com/api/download/getByParams/app/saas-version-app/Spring/MVC/entrance/unifier/download?resource="
                                    + autoUpDateBean!!.getDownloadUrl(),
                            autoUpDateBean!!.getBuild()
                        )
                    }
                }
            }
        }, this@PocActivity, "", "", "")
        viewModel.queryAutoUpdate();
    }

    fun downUrl(url: String?, build: String?) {
        val dialog = ProgressDialog(this@PocActivity)
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
        dialog.setCancelable(false)
        dialog.show()
        Thread(DownLoadApk(dialog, url, this@PocActivity, build)).start()
    }

    @RequiresApi(Build.VERSION_CODES.R)
    private fun checkStoragePermission() {
//        ActivityCompat.requestPermissions(
//            this, arrayOf(
//                Manifest.permission.READ_EXTERNAL_STORAGE,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE
//            ),
//            REQUEST_EXTERNAL_STORAGE
//        )
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.MANAGE_EXTERNAL_STORAGE
                ),
                1
            )
        }
    }
}