package com.lukouguoji.gnj.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.gnj.R
import com.lukouguoji.gnj.activity.GnjYiKuListActivity
import com.lukouguoji.gnj.adapt.GnjYiKu2ListAdapter
import com.lukouguoji.gnj.model.GnjYiKu2ListModel
import com.lukouguoji.gnj.viewModel.GnjYiKu2ListViewModel
import com.lukouguoji.module_base.ActivityCollector
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.text.SimpleDateFormat
import java.util.*

class GnjYiKu2Fragment : Fragment(), View.OnClickListener {
    private lateinit var yiKuActivity: GnjYiKuListActivity
    private val currentTitleName = "国际出港查询完成移库"
    private lateinit var viewModel: GnjYiKu2ListViewModel

    private lateinit var adapter: GnjYiKu2ListAdapter
    private val collectList = ArrayList<GnjYiKu2ListModel>()

    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0
    private lateinit var refreshLayout: RefreshLayout

    //标题
    private lateinit var toolBack: LinearLayout
    private lateinit var titleName: TextView

    //搜索条件
    private lateinit var searchListFragment: LinearLayout
    private lateinit var filtrateLayout: LinearLayout
    private lateinit var startDate: TextView
    private lateinit var endDate: TextView
    private lateinit var awbType: TextView
    private var awbTypeValue = ""
    private lateinit var id: EditText
    private lateinit var idScanIcon: ImageView
    private lateinit var searchLayout: LinearLayout

    //筛选页
    private lateinit var filtrateFragment: LinearLayout
    private lateinit var wbNo: EditText
    private lateinit var wbNoScanIcon: ImageView


    private lateinit var submit: TextView
    private lateinit var reset: TextView

//    、、特码、代理人、品名、运单类型、业务类型查询


    private val ymdSdf = SimpleDateFormat("yyyy-MM-dd")//年月日
    private val ymdHmsSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//年月日 时分秒
    private val calendar = Calendar.getInstance()

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

        viewModel = ViewModelProvider(this).get(GnjYiKu2ListViewModel::class.java)
        val layoutManager = LinearLayoutManager(yiKuActivity)
        adapter = GnjYiKu2ListAdapter(yiKuActivity, collectList)
        var recyclerView: RecyclerView = yiKuActivity.findViewById(R.id.recyclerList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        //标题
        toolBack = yiKuActivity.findViewById(R.id.tool_back)
        titleName = yiKuActivity.findViewById(R.id.title_name)
        //搜索列表页
        searchListFragment = yiKuActivity.findViewById(R.id.searchListFragment)
        startDate = yiKuActivity.findViewById(R.id.startDate)
        endDate = yiKuActivity.findViewById(R.id.endDate)
        awbType = yiKuActivity.findViewById(R.id.awbType)
        id = yiKuActivity.findViewById(R.id.id)
        idScanIcon = yiKuActivity.findViewById(R.id.idScanIcon)
        searchLayout = yiKuActivity.findViewById(R.id.searchLayout)
        filtrateLayout = yiKuActivity.findViewById(R.id.filtrateLayout)
        //筛选页
        filtrateFragment = yiKuActivity.findViewById(R.id.filtrateFragment)

        wbNo = yiKuActivity.findViewById(R.id.wbNo)
        wbNoScanIcon = yiKuActivity.findViewById(R.id.wbNoScanIcon)
        submit = yiKuActivity.findViewById(R.id.submit)
        reset = yiKuActivity.findViewById(R.id.reset)

        toolBack.setOnClickListener(this)
        searchLayout.setOnClickListener(this)
        startDate.setOnClickListener(this)
        endDate.setOnClickListener(this)
        awbType.setOnClickListener(this)
        idScanIcon.setOnClickListener(this)
        wbNoScanIcon.setOnClickListener(this)
        filtrateLayout.setOnClickListener(this)
        submit.setOnClickListener(this)
        reset.setOnClickListener(this)

        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?) {

            }
        })

        val format = ymdSdf.format(Date())
        startDate.text = "$format 00:00:00"
        endDate.text = "$format 23:59:59"
    }

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

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        initView()

        //初始化查询
        searchFun()
        yiKuActivity.loading()
        //查询返回结果
        viewModel.searchParamLive.observe(yiKuActivity) {
            yiKuActivity.loadingCancel()
            //1.获取数据
            var listArr: JSONArray = it["list"] as JSONArray
            totalPage = it["pages"] as Int
//            var listArr :JSONArray =it["list"] as JSONArray
            if (listArr.size > 0) {
                collectList.clear()

                //2.循环遍历塞入collectList
                listArr.forEach {
                    val itemObj = it as JSONObject

                    val id = itemObj.getString("moveId")
                    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 flight = itemObj.getString("flight") ?: ""
                    val awbType = itemObj.getString("awbType") ?: ""

                    //列表赋值
                    collectList.add(
                        GnjYiKu2ListModel(
                            id,
                            no,
                            fno,
                            pc,
                            weight,
                            goods,
                            agentCode,
                            spCode,
                            pickDate, origin, dest, flight, awbType, false
                        )
                    )
                }

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

            }

        }

        ///////////////    下拉框   start
        viewModel.awb(Constant.businessType.CI)
        viewModel.awbObserver.observe(yiKuActivity) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择运单类型"
            noneObj["code"] = ""
            viewModel.awbList.add(noneObj)
            viewModel.awbList.addAll(vd.getJSONArray("data"))
        }
        ///////////////    下拉框   end

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

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null) {
            val content = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
            // 扫描二维码/条码回传
            when (requestCode) {
                Constant.RequestCode.gnj_yiku2_id_scan -> {
                    id.setText(content)
                    resetSearch()
                }
                Constant.RequestCode.gnj_yiku2_wb_no_scan -> {
                    wbNo.setText(content)
                    resetSearch()
                }
            }

        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.tool_back -> {
                    if (searchListFragment.visibility == View.GONE && filtrateFragment.visibility == View.VISIBLE) {
                        searchListFragment.visibility = View.VISIBLE
                        filtrateFragment.visibility = View.GONE
                        titleName.text = currentTitleName
                    } else {
                        yiKuActivity.finish()
                    }
                }
                R.id.searchLayout -> {
                    resetSearch()
                }
                R.id.filtrateLayout -> {
                    if (searchListFragment.visibility == View.VISIBLE && filtrateFragment.visibility == View.GONE) {
                        searchListFragment.visibility = View.GONE
                        filtrateFragment.visibility = View.VISIBLE
                        titleName.text = "搜索"
                    } else {
                        searchListFragment.visibility = View.VISIBLE
                        filtrateFragment.visibility = View.GONE
                        titleName.text = currentTitleName
                    }
//                    Common.showToast(this,"筛选")
                }
                R.id.startDate -> {
                    Common.onYearMonthDayTime(yiKuActivity, startDate.text.toString()) { year, month, day, hour, min, second ->
                        calendar.set(year, month - 1, day, hour, min, second)
                        startDate.text = ymdHmsSdf.format(calendar.time)
                    }
                }
                R.id.endDate -> {
                    Common.onYearMonthDayTime(yiKuActivity, endDate.text.toString()) { year, month, day, hour, min, second ->
                        calendar.set(year, month - 1, day, hour, min, second)
                        endDate.text = ymdHmsSdf.format(calendar.time)
                    }
                }
                R.id.awbType -> {
                    Common.singleSelect(yiKuActivity, "运单类型", viewModel.awbList, awbTypeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        awbType.text = name
                        awbTypeValue = code
                    }
                }
                R.id.idScanIcon -> {
                    scanCode(Constant.RequestCode.gnj_yiku2_id_scan)
                }
                R.id.wbNoScanIcon -> {
                    scanCode(Constant.RequestCode.gnj_yiku2_wb_no_scan)
                }
                R.id.submit -> {
                    titleName.text = currentTitleName
                    //搜索
                    resetSearch()
                }
                R.id.reset -> {
                    resetFun()
                }
                else -> {
                    Toast.makeText(yiKuActivity, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchFun() {
        //筛选页隐藏
        searchListFragment.visibility = View.VISIBLE
        filtrateFragment.visibility = View.GONE
        yiKuActivity.loading()
        viewModel.search(
            pageSize,
            currentPage,
            startDate.text.toString(),
            endDate.text.toString(),
            awbTypeValue,
            id.text.toString(),
            wbNo.text.toString()
        )
    }

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

    /**
     * 重置筛选条件
     */
    private fun resetFun() {
        currentPage = 1
        val format = ymdSdf.format(Date())
        startDate.text = "$format 00:00:00"
        endDate.text = "$format 23:59:59"
        wbNo.setText("")
        id.setText("")
        awbType.text = ""
        awbTypeValue = ""

    }

    /**
     * 扫码功能
     */
    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()
    }
}