package com.miya.fastcashier.ui

import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.EncodeUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.fastcashier.lib_common.BuildConfig
import com.fastcashier.lib_common.base.BaseActivity
import com.fastcashier.lib_common.function.account.AccountService.getAccountInfo
import com.fastcashier.lib_common.function.account.AccountService.getUserName
import com.fastcashier.lib_common.function.account.SelfCashierTerminalConfig
import com.fastcashier.lib_common.net.CommonCallback
import com.fastcashier.lib_common.util.LogFileUtils.isProhibitWrite
import com.miya.fastcashier.R
import com.miya.fastcashier.bean.LFileParamBean
import com.miya.fastcashier.net.MiyaApi.Companion.UPLOAD_LOG_FILE
import com.miya.fastcashier.net.MiyaApiRequest.Companion.getDataSourceIp
import com.miya.fastcashier.net.MiyaApiRequest.Companion.uploadFile
import com.miya.fastcashier.ui.adapter.PathAdapter
import com.miya.fastcashier.ui.dialog.CustomImageCenterDialog
import com.miya.fastcashier.util.FileUtils
import com.miya.fastcashier.util.manage.log.LFileFilter
import com.miya.fastcashier.widget.EmptyRecyclerView
import es.dmoral.toasty.Toasty
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.util.*

class LFilePickerActivity : BaseActivity() {
    private val TAG = "FilePickerLeon"
    private var mCustomImageCenterDialog: CustomImageCenterDialog? = null
    private var mRecylerView: EmptyRecyclerView? = null
    private var mEmptyView: View? = null
    private var mTvPath: TextView? = null
    private var mTvBack: TextView? = null
    private var mBtnAddBook: Button? = null
    private var mPath: String? = null
    private var mPathAdapter: PathAdapter? = null
    private var mToolbar: Toolbar? = null
    private var mParamEntity: LFileParamBean? = null
    private var mIsAllSelected = false
    private var mMenu: Menu? = null
    private var successToast: Toast? = null
    protected var selfCashierTerminalConfig: SelfCashierTerminalConfig? = null
    private var mFilter: LFileFilter? = null
    private var mListFiles: List<File>? = null
    private val mListNumbers = ArrayList<String>() //存放选中条目的数据地址
    private var mQrCodeEncodeMsg: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        mParamEntity = intent.extras!!.getSerializable("param") as LFileParamBean?
        setTheme(mParamEntity!!.theme)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lfile_picker)
        selfCashierTerminalConfig = getAccountInfo()!!.transformToSelfCashierTermianlConfig()
        initView()
        setSupportActionBar(mToolbar)
        supportActionBar!!.setHomeButtonEnabled(true)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        initToolbar()
        updateAddButton()
        if (!checkSDState()) {
            Toast.makeText(this, R.string.lfile_NotFoundPath, Toast.LENGTH_SHORT).show()
            return
        }
        mPath = mParamEntity!!.path
        if (StringUtils.isEmpty(mPath)) {
            //如果没有指定路径，则使用默认路径
            mPath = Environment.getExternalStorageDirectory().absolutePath
        }
        mTvPath!!.text = mPath
        mFilter = LFileFilter(mParamEntity!!.fileTypes)
        mListFiles =
            FileUtils.getFileList(mPath, mFilter, mParamEntity!!.isGreater, mParamEntity!!.fileSize)
        mPathAdapter = PathAdapter(
            mListFiles as MutableList<File>,
            this,
            mFilter!!,
            mParamEntity!!.isMutilyMode,
            mParamEntity!!.isGreater,
            mParamEntity!!.fileSize
        )
        mRecylerView!!.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mPathAdapter!!.setmIconStyle(mParamEntity!!.iconStyle)
        mRecylerView!!.setAdapter(mPathAdapter)
        mRecylerView!!.setmEmptyView(mEmptyView)
        mCustomImageCenterDialog = CustomImageCenterDialog(this)
        initListener()
    }

    /**
     * 更新Toolbar展示
     */
    private fun initToolbar() {
        if (mParamEntity!!.title != null) {
            mToolbar!!.title = mParamEntity!!.title
        }
        if (mParamEntity!!.titleStyle != 0) {
            mToolbar!!.setTitleTextAppearance(this, mParamEntity!!.titleStyle)
        }
        if (mParamEntity!!.titleColor != null) {
            mToolbar!!.setTitleTextColor(Color.parseColor(mParamEntity!!.titleColor)) //设置标题颜色
        }
        if (mParamEntity!!.backgroundColor != null) {
            mToolbar!!.setBackgroundColor(Color.parseColor(mParamEntity!!.backgroundColor))
        }
        mToolbar!!.setNavigationOnClickListener { finish() }
    }

    private fun updateAddButton() {
        if (!mParamEntity!!.isMutilyMode) {
            mBtnAddBook!!.visibility = View.GONE
        }
        if (!mParamEntity!!.isChooseMode) {
            mBtnAddBook!!.visibility = View.VISIBLE
            mBtnAddBook!!.text = getString(R.string.lfile_OK)
            //文件夹模式默认为单选模式
            mParamEntity!!.isMutilyMode = false
        }
    }

    /**
     * 添加点击事件处理
     */
    private fun initListener() {
        // 返回目录上一级
        mTvBack!!.setOnClickListener(View.OnClickListener {
            val tempPath = File(mPath).parent ?: return@OnClickListener
            mPath = tempPath
            mListFiles = FileUtils.getFileList(
                mPath,
                mFilter,
                mParamEntity!!.isGreater,
                mParamEntity!!.fileSize
            )
            mPathAdapter!!.setmListData(mListFiles as MutableList<File>)
            mPathAdapter!!.updateAllSelelcted(false)
            mIsAllSelected = false
            updateMenuTitle()
            mBtnAddBook!!.text = getString(R.string.lfile_Selected)
            mRecylerView!!.scrollToPosition(0)
            setShowPath(mPath)
            //清除添加集合中数据
            mListNumbers.clear()
            if (mParamEntity!!.addText != null) {
                mBtnAddBook!!.text = mParamEntity!!.addText
            } else {
                mBtnAddBook!!.setText(R.string.lfile_Selected)
            }
        })
        mPathAdapter!!.onItemClickListener = object : PathAdapter.OnItemClickListener {
            override fun click(position: Int) {
                if (mParamEntity!!.isMutilyMode) {
                    if (mListFiles!![position].isDirectory) {
                        //如果当前是目录，则进入继续查看目录
                        chekInDirectory(position)
                        mPathAdapter!!.updateAllSelelcted(false)
                        mIsAllSelected = false
                        updateMenuTitle()
                        mBtnAddBook!!.text = getString(R.string.lfile_Selected)
                    } else {
                        //如果已经选择则取消，否则添加进来
                        if (mListNumbers.contains(mListFiles!![position].absolutePath)) {
                            mListNumbers.remove(mListFiles!![position].absolutePath)
                        } else {
                            mListNumbers.add(mListFiles!![position].absolutePath)
                        }
                        if (mParamEntity!!.addText != null) {
                            mBtnAddBook!!.text =
                                mParamEntity!!.addText + "( " + mListNumbers.size + " )"
                        } else {
                            mBtnAddBook!!.text =
                                getString(R.string.lfile_Selected) + "( " + mListNumbers.size + " )"
                        }
                        //先判断是否达到最大数量，如果数量达到上限提示，否则继续添加
                        if (mParamEntity!!.maxNum > 0 && mListNumbers.size > mParamEntity!!.maxNum) {
                            Toast.makeText(
                                this@LFilePickerActivity,
                                R.string.lfile_OutSize,
                                Toast.LENGTH_SHORT
                            ).show()
                            return
                        }
                    }
                } else {
                    //单选模式直接返回
                    if (mListFiles!![position].isDirectory) {
                        chekInDirectory(position)
                        return
                    }
                    if (mParamEntity!!.isChooseMode) {
                        //选择文件模式,需要添加文件路径，否则为文件夹模式，直接返回当前路径
                        mListNumbers.add(mListFiles!![position].absolutePath)
                        chooseDone()
                    } else {
                        Toast.makeText(
                            this@LFilePickerActivity,
                            R.string.lfile_ChooseTip,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
        }
        mBtnAddBook!!.setOnClickListener {
            if (mParamEntity!!.isChooseMode && mListNumbers.size < 1) {
                val info = mParamEntity!!.notFoundFiles
                if (TextUtils.isEmpty(info)) {
                    Toast.makeText(
                        this@LFilePickerActivity,
                        R.string.lfile_NotFoundBooks,
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    Toast.makeText(this@LFilePickerActivity, info, Toast.LENGTH_SHORT).show()
                }
            } else {
                //返回
                chooseDone()
            }
        }
    }

    /**
     * 点击进入目录
     *
     * @param position
     */
    private fun chekInDirectory(position: Int) {
        mPath = mListFiles!![position].absolutePath
        setShowPath(mPath)
        //更新数据源
        mListFiles =
            FileUtils.getFileList(mPath, mFilter, mParamEntity!!.isGreater, mParamEntity!!.fileSize)
        mPathAdapter!!.setmListData(mListFiles as MutableList<File>)
        mPathAdapter!!.notifyDataSetChanged()
        mRecylerView!!.scrollToPosition(0)
    }

    /**
     * 完成提交
     */
    private fun chooseDone() {
        //判断是否数量符合要求
        if (mParamEntity!!.isChooseMode) {
            if (mParamEntity!!.maxNum > 0 && mListNumbers.size > mParamEntity!!.maxNum) {
                Toast.makeText(this@LFilePickerActivity, R.string.lfile_OutSize, Toast.LENGTH_SHORT)
                    .show()
                return
            }
        }
        val path = mTvPath!!.text.toString().trim { it <= ' ' }
        val intent = Intent()
        intent.putStringArrayListExtra("paths", mListNumbers)
        intent.putExtra("path", path)
        setResult(RESULT_OK, intent)
        showProgressDialog()
        uploadFile(mListNumbers[0])
    }

    fun uploadFile(path: String?) {
        isProhibitWrite = true
        val equType = equType
        val file = File(path)
        val requestBody = RequestBody.create("".toMediaTypeOrNull(), file)
        val part: MultipartBody.Part = MultipartBody.Part.createFormData("logFile", file.name, requestBody)
        var ip = getDataSourceIp(selfCashierTerminalConfig!!, equType)
        if (!TextUtils.isEmpty(selfCashierTerminalConfig!!.scoRuntimeConfig.platformUrl)) {
            ip = (selfCashierTerminalConfig!!.scoRuntimeConfig.platformUrl
                    + UPLOAD_LOG_FILE)
        }
        LogUtils.e("ip = $ip")

        tryGenQrCodeMsg(file.name)
        uploadFile(
            ip!!, part,
            object : CommonCallback<String>() {
                override fun onSuccess(data: String) {
                    hidProgressDialog()
                    isProhibitWrite = false
                    successToast = Toasty.success(this@LFilePickerActivity, "文件上传成功！")
                    with(successToast) { this?.show() }
                    showQrImageIfNeeded()
                }

                override fun onFailure(errorType: Int, errorCode: String?, errorMessage: String?) {
                    hidProgressDialog()
                    isProhibitWrite = false
                    Toasty.error(this@LFilePickerActivity, "文件上传失败！").show()
                }
            })
    }//强制进入米雅页面//mpos//支付宝

    //微信
    private val equType: String
        private get() {
            var equType = ""
            if (BuildConfig.appType == "weixin") {
                //微信
                equType = "WECHAT_EQU"
            } else if (BuildConfig.appType == "standard") {
                //支付宝
                equType = "ALIPAY_EQU"
            } else if (BuildConfig.appType == "mpos") {
                //mpos
                equType = "MPOS_EQU"
            } else if (BuildConfig.appType == "miya") {
                //强制进入米雅页面
                equType = ""
            }
            return equType
        }

    private fun tryGenQrCodeMsg(fileName: String) {
        val huihuaConfig = selfCashierTerminalConfig!!.huihuaConfig
        if (huihuaConfig != null) {
            val hhMerchant = huihuaConfig.hhMerchant
            val storeId = huihuaConfig.storeId
            val username = getUserName()
            val qrMsg =
                String.format("%s/%s/%s/%s/%s", hhMerchant, storeId, username, uploadEq, fileName)
            mQrCodeEncodeMsg = EncodeUtils.base64Encode2String(qrMsg.toByteArray())
        }
    }

    private fun showQrImageIfNeeded() {
        if (TextUtils.isEmpty(mQrCodeEncodeMsg)) {
            return
        }
        if (mCustomImageCenterDialog == null) {
            mCustomImageCenterDialog = CustomImageCenterDialog(this)
        }
        mCustomImageCenterDialog!!.setOnDismissListener { dialog: DialogInterface? -> finish() }
        mCustomImageCenterDialog!!.setFullScreenStatus(true)
            .setHintContent("请将日志二维码拍照保存")
            .setQrContent(mQrCodeEncodeMsg)
            .build().show()
    }

    private val uploadEq: String
        private get() {
            var eq = ""
            val equType = equType
            when (equType) {
                "WECHAT_EQU" -> eq = "w_eq"
                "MPOS_EQU" -> eq = "m_eq"
                else -> {
                }
            }
            return eq
        }

    /**
     * 初始化控件
     */
    private fun initView() {
        mRecylerView = findViewById<View>(R.id.recylerview) as EmptyRecyclerView
        mTvPath = findViewById<View>(R.id.tv_path) as TextView
        mTvBack = findViewById<View>(R.id.tv_back) as TextView
        mBtnAddBook = findViewById<View>(R.id.btn_addbook) as Button
        mEmptyView = findViewById(R.id.empty_view)
        mToolbar = findViewById<View>(R.id.toolbar) as Toolbar
        if (mParamEntity!!.addText != null) {
            mBtnAddBook!!.text = mParamEntity!!.addText
        }
    }

    /**
     * 检测SD卡是否可用
     */
    private fun checkSDState(): Boolean {
        return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
    }

    /**
     * 显示顶部地址
     *
     * @param path
     */
    private fun setShowPath(path: String?) {
        mTvPath!!.text = path
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main_toolbar, menu)
        mMenu = menu
        updateOptionsMenu(menu)
        return true
    }

    /**
     * 更新选项菜单展示，如果是单选模式，不显示全选操作
     *
     * @param menu
     */
    private fun updateOptionsMenu(menu: Menu) {
        mMenu!!.findItem(R.id.action_selecteall_cancel).isVisible = mParamEntity!!.isMutilyMode
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_selecteall_cancel) {
            //将当前目录下所有文件选中或者取消
            mPathAdapter!!.updateAllSelelcted(!mIsAllSelected)
            mIsAllSelected = !mIsAllSelected
            if (mIsAllSelected) {
                for (mListFile in mListFiles!!) {
                    //不包含再添加，避免重复添加
                    if (!mListFile.isDirectory && !mListNumbers.contains(mListFile.absolutePath)) {
                        mListNumbers.add(mListFile.absolutePath)
                    }
                    if (mParamEntity!!.addText != null) {
                        mBtnAddBook!!.text =
                            mParamEntity!!.addText + "( " + mListNumbers.size + " )"
                    } else {
                        mBtnAddBook!!.text =
                            getString(R.string.lfile_Selected) + "( " + mListNumbers.size + " )"
                    }
                }
            } else {
                mListNumbers.clear()
                mBtnAddBook!!.text = getString(R.string.lfile_Selected)
            }
            updateMenuTitle()
        }
        return true
    }

    /**
     * 更新选项菜单文字
     */
    fun updateMenuTitle() {
        if (mIsAllSelected) {
            mMenu!!.getItem(0).title = getString(R.string.lfile_Cancel)
        } else {
            mMenu!!.getItem(0).title = getString(R.string.lfile_SelectAll)
        }
    }

    fun showProgressDialog() {
        showProgressDialog(getString(R.string.please_wait))
    }

    fun hidProgressDialog() {
        dismissProgressDialog()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (successToast != null) successToast!!.cancel()
    }
}