package com.lukouguoji.gjc.fragment

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.activity.GjcYiKuListActivity
import com.lukouguoji.gjc.adapt.GjcYiKuListAdapter
import com.lukouguoji.gjc.model.GjcYiKuListModel
import com.lukouguoji.gjc.viewModel.GjcYiKuListViewModel
import com.lukouguoji.module_base.ActivityCollector
import com.lukouguoji.module_base.MyApplication
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.util.Common
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.bean.ZxingConfig
import java.util.*
import kotlin.collections.ArrayList


class GjcYiKuFragment : Fragment(), View.OnClickListener {
    private lateinit var viewModel: GjcYiKuListViewModel
    private lateinit var yiKuActivity: GjcYiKuListActivity

    private lateinit var adapter: GjcYiKuListAdapter
    private val collectList = ArrayList<GjcYiKuListModel>()
    private var collectListFromNet = ArrayList<GjcYiKuListModel>()
    private lateinit var refreshLayout: RefreshLayout
    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0
    private var totalCount = 0  //总条数

    //搜索
    private lateinit var wbNo: EditText
    private lateinit var wbNoScanIcon: ImageView
    private lateinit var carrier: EditText
    private lateinit var dest: EditText

    private lateinit var searchLayout: LinearLayout
    private lateinit var checkIcon: ImageView
    private lateinit var quickSearch: EditText
    private var isAllCheck = false

    //列表
    private lateinit var listLayout: LinearLayout
    private lateinit var totalLayout: LinearLayout

    //底部
    private lateinit var totalPc: TextView
    private lateinit var selPc: TextView
    private lateinit var send: TextView

    private fun initView() {
        yiKuActivity = activity!! as GjcYiKuListActivity

        viewModel = ViewModelProvider(this).get(GjcYiKuListViewModel::class.java)
        val layoutManager = LinearLayoutManager(activity)
        adapter = GjcYiKuListAdapter(yiKuActivity, viewModel, collectList)
        var recyclerView: RecyclerView = yiKuActivity.findViewById(R.id.collectList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter
        refreshLayout = yiKuActivity.findViewById(R.id.refreshLayout)

        wbNo = yiKuActivity.findViewById(R.id.wbNo)
        wbNoScanIcon = yiKuActivity.findViewById(R.id.wbNoScanIcon)
        carrier = yiKuActivity.findViewById(R.id.carrier)
        dest = yiKuActivity.findViewById(R.id.dest)

        searchLayout = yiKuActivity.findViewById(R.id.searchLayout)
        checkIcon = yiKuActivity.findViewById(R.id.checkIcon)
        quickSearch = yiKuActivity.findViewById(R.id.quickSearch)
        //列表
        listLayout = yiKuActivity.findViewById(R.id.listLayout)
        totalLayout = yiKuActivity.findViewById(R.id.totalLayout)
        //底部
        totalPc = yiKuActivity.findViewById(R.id.totalPc)
        selPc = yiKuActivity.findViewById(R.id.selPc)
        send = yiKuActivity.findViewById(R.id.send)

        searchLayout.setOnClickListener(this)
        wbNoScanIcon.setOnClickListener(this)
        checkIcon.setOnClickListener(this)
        send.setOnClickListener(this)

        quickSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null && s.toString() != "") {
                    val filterCollectionList = collectList.filter { c -> c.wbNo.contains(s.toString()) }
                    collectList.clear()
                    collectList.addAll(filterCollectionList)
                    recyclerView.adapter = GjcYiKuListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        collectList
                    )
                } else {
                    collectList.clear()
                    collectList.addAll(collectListFromNet)
                    recyclerView.adapter = GjcYiKuListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        collectList
                    )
                }
                val checkList = collectList.filter { c -> c.isCheck }
                viewModel.setCheckCount(checkList.size)
                adapter.notifyDataSetChanged()
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        wbNo.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null && s.toString().length > 11) {
                    Common.alertDialog(ActivityCollector.getLastActivity()!!, "运单号不能超过11位！") { dialog ->
                        wbNo.setText(s.toString().substring(0, 11))
                        dialog.dismiss()
                    }
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        carrier.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(editable: Editable?) {
                val originText = editable.toString()
                if (originText != null && originText != "") {
                    val regularExpression = "(^([A-Z]+)$)"
                    val matches = originText.matches(regularExpression.toRegex())
                    if(!matches){
                        val regularExpression2 = "([^A-Za-z]+)"
                        val replaceStr = originText.replace(regularExpression2.toRegex(),"")
                        val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                        carrier.setText(replaceStrToUpper)
                        carrier.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })

        dest.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(editable: Editable?) {
                val originText = editable.toString()
                if (originText != null && originText != "") {
                    val regularExpression = "(^([A-Z]+)$)"
                    val matches = originText.matches(regularExpression.toRegex())
                    if(!matches){
                        val regularExpression2 = "([^A-Za-z]+)"
                        val replaceStr = originText.replace(regularExpression2.toRegex(),"")
                        val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                        dest.setText(replaceStrToUpper)
                        dest.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_gjc_yi_ku, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()
        yiKuActivity.setBackArrow("国际出港移库")

        //查询返回结果
        viewModel.searchParamLive.observe(yiKuActivity) {
            yiKuActivity.loadingCancel()
            //1.获取数据
            var listArr: JSONArray = it["list"] as JSONArray
            totalCount = it.getIntValue("total")
            totalPage = it["pages"] as Int
//            var listArr :JSONArray =it["list"] as JSONArray
            if (listArr.size > 0) {
                collectList.clear()
                listLayout.visibility = View.VISIBLE
                totalLayout.visibility = View.VISIBLE
                //2.循环遍历塞入collectList
                listArr.forEach {
                    val itemObj = it as JSONObject

                    val id = itemObj.getIntValue("maWbId")
                    val pkId = itemObj.getString("pkId") ?: ""
                    val no = itemObj.getString("wbNo") ?: ""
                    val fno = itemObj.getString("fno") ?: ""
                    val pc = itemObj.getIntValue("pc")
                    val weight = itemObj.getDoubleValue("weight")//实到重量

                    val goods = itemObj.getString("goods") ?: ""
                    val agentCode = itemObj.getString("agentCode") ?: ""
                    val spCode = itemObj.getString("spCode") ?: ""
                    val pickDate = itemObj.getString("chargeTime") ?: ""

                    val origin = itemObj.getString("origin") ?: ""
                    val dest = itemObj.getString("dest") ?: ""
                    val by1 = itemObj.getString("by1") ?: ""
                    val awbType = itemObj.getString("awbType") ?: ""

                    //列表赋值
                    collectList.add(
                        GjcYiKuListModel(
                            id,
                            no,
                            pkId,
                            fno,
                            pc,
                            weight,
                            goods,
                            agentCode,
                            spCode,
                            pickDate, origin, dest, by1, awbType, false
                        )
                    )
                }
                collectListFromNet.clear()
                collectListFromNet = collectList.clone() as ArrayList<GjcYiKuListModel>

                //3.调adpter展示
                if (currentPage == 1) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }

            totalPc.text = totalCount.toString()
            resetSelCount(false, totalCount)
        }

        //确认移库 返回结果
        viewModel.moveGnjYiKuObserver.observe(yiKuActivity) {
            yiKuActivity.loadingCancel()
            val status = it.getString("status")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status) {
                var dataStatus = it.getString("data")
                if (Constant.Result.succ == dataStatus) {
                    if (msg != null && msg != "") {
                        Common.showToast(yiKuActivity, msg)
                    } else {
                        Common.showToast(yiKuActivity, "移库成功！")
                    }
                    //重新搜索
                    resetSearch()
                } else {
                    if (msg != null && msg != "") {
                        Common.showToast(yiKuActivity, msg)
                    } else {
                        Common.showToast(yiKuActivity, "移库失败！")
                    }
                }
            } else {
                if (msg != null && msg != "") {
                    Common.showToast(yiKuActivity, msg)
                } else {
                    Common.showToast(yiKuActivity, "移库失败！")
                }
            }
        }

        //监听 复选框选中
        viewModel.checkCount.observe(yiKuActivity) {
            selPc.text = it.toString()
        }

        //搜索
        resetSearch()

        ///////////////////////////////   加载刷新的布局
        refreshLayout.setRefreshHeader(ClassicsHeader(yiKuActivity))
        refreshLayout.setRefreshFooter(ClassicsFooter(yiKuActivity))
        /////////////////////////////// 下拉刷新
        refreshLayout.setOnRefreshListener {
            resetSearch()
        }
        /////////////////////////////// 上拉加载
        refreshLayout.setOnLoadMoreListener {
            if (currentPage < totalPage) {
                currentPage++
                //初始化查询
                searchFun()
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData()
            }
        }

    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.searchLayout -> {
//                    viewModel.queryPickByIdGnjChuKu("M000995643")
                    resetSearch()
                }
                R.id.wbNoScanIcon -> {
                    scanCode(Constant.RequestCode.gjc_yiku_wb_no_scan)
                }
                R.id.checkIcon -> {
                    isAllCheck = !isAllCheck
                    resetSelCount(isAllCheck, totalCount)
                    checkIcon.setImageResource(if (isAllCheck) R.drawable.img_check_all_checked else R.drawable.img_check_all_unchecked)
                }
                R.id.send -> {
                    val ids = collectList.filter { c -> c.isCheck }.map { c -> c.id }
                    viewModel.moveGnjYiKu(ids)
                }
                else -> {
                    Toast.makeText(yiKuActivity, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 扫码返回的结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 扫描二维码/条码回传
        if (requestCode == Constant.RequestCode.gjc_yiku_wb_no_scan) {
            if (data != null) {
                val content = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
                wbNo.setText("$content")

                resetSearch()
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchFun() {
        yiKuActivity.loading()
        listLayout.visibility = View.GONE
        totalLayout.visibility = View.GONE
        viewModel.search(
            pageSize,
            currentPage,
            wbNo.text.toString(),
            dest.text.toString(),
            carrier.text.toString()
        )
    }

    /**
     * 重置数据，搜索
     */
    private fun resetSearch() {
        //recyclerView 清除所有数据数据
        viewModel.setCheckCount(0)
        refreshLayout.setNoMoreData(false)
        adapter.notifyItemRangeRemoved(0, collectList.size)
        collectList.clear()
        currentPage = 1
        searchFun()
    }

    /**
     * 重新计算选中数量
     * isAllCheckParam  true：全选  false:全部全效选择
     */
    private fun resetSelCount(isAllCheckParam: Boolean, totalCount: Int) {
        collectList.forEach { c ->
            c.isCheck = isAllCheckParam
        }
        if (isAllCheckParam) {
            viewModel.setCheckCount(totalCount)
        } else {
            viewModel.setCheckCount(0)
        }
        adapter.notifyDataSetChanged()
    }

    /**
     * 扫码功能
     */
    fun scanCode(requestCode: Int) {
        AndPermission.with(this)
            .runtime()
            .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
            .onGranted { data: List<String?>? ->
                val intent = Intent(yiKuActivity, CaptureActivity::class.java)
                val config = ZxingConfig()
                config.isFullScreenScan = false //是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                intent.putExtra(com.yzq.zxinglibrary.common.Constant.INTENT_ZXING_CONFIG, config)
                startActivityForResult(intent, requestCode)
            }
            .onDenied { data: List<String?>? ->
                val packageURI = Uri.parse("package:${yiKuActivity.packageName}")
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
                Toast.makeText(yiKuActivity, "没有权限无法扫描呦", Toast.LENGTH_LONG).show()
            }
            .start()
    }
}