package com.quansu.heifengwuliu.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.quansu.heifengwuliu.R
import com.quansu.heifengwuliu.activity.AddressActivity
import com.quansu.heifengwuliu.activity.AreaSelectActivity
import com.quansu.heifengwuliu.activity.CollectionActivity
import com.quansu.heifengwuliu.adapter.CarEnterAdapter
import com.quansu.heifengwuliu.base.MBFragment
import com.quansu.heifengwuliu.config.ConfigRx
import com.quansu.heifengwuliu.config.MIntentAction
import com.quansu.heifengwuliu.databinding.FragmentOwnermoreBinding
import com.quansu.heifengwuliu.inte.ChoiceData
import com.quansu.heifengwuliu.model.AddressBean
import com.quansu.heifengwuliu.model.DataInfoBean
import com.quansu.heifengwuliu.model.SelectData
import com.quansu.heifengwuliu.model.bean.ReceiveBean
import com.quansu.heifengwuliu.model.bean.SendBean
import com.quansu.heifengwuliu.utils.PopuListUtils
import com.quansu.heifengwuliu.utils.PopupUtils
import com.quansu.heifengwuliu.vmodel.OwnerMoreVModel
import com.ysnows.base.model.PositionBean
import com.ysnows.base.utils.B
import com.ysnows.base.utils.UiSwitch
import java.text.DecimalFormat

/**
 * 一装多卸
 *Created by shihuiyun
 *on 2020/9/11
 */
class OwnerMoreFragment : MBFragment<OwnerMoreVModel, FragmentOwnermoreBinding>(){
    //新的
    var adapter: CarEnterAdapter? =null
    var  receiveList = ArrayList<ReceiveBean>()

    var info_id:String="0"
    //货物类型
    var goodsTypeList = ArrayList<SelectData>()

    //货物单位
    var numsTypeList = ArrayList<String>()
    //是否购买保险
    var insurance = ArrayList<String>()

    //协议相关
    var is_agree = 1//默认 已阅读运输协议
    var is_public = 1//默认 发布到货源大厅
    var is_insurance = 0//默认  不够买保险

    //出
    var lat_out: String = ""
    var lng_out: String = ""
    var province_out: String = ""
    var city_out: String = ""
    var area_out: String = ""
    var time_out: String = ""

    //常用司机
    var driverList=ArrayList<String>()




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

        vm.initData(this)
        getData()
        vm.info.observe(this, Observer {
            //观察
            goodsTypeList.addAll(it.goods_type)

            numsTypeList.addAll(it.nums_type)

            initTab(it)
            initAdapter()

        })
        initData()
    }


    override fun listeners() {
        super.listeners()
        binding.llOperation.setOnClickListener {
            //添加

            addList()
        }

        binding.llIsInsurance.setOnClickListener {

            PopuListUtils.showQMUIPopup(context(), binding.tvIsInsurance, insurance, object : ChoiceData {
                override fun onRestuse(name: String?) {
                    vm.insurance.value = name
                    is_insurance = if (name.equals("是")) 1 else 0

                }
            })
        }

        binding.llAgree.setOnClickListener {

            is_agree = if (is_agree == 1) 0 else 1
            vm.isAgree.value = is_agree
        }
        binding.llPublic.setOnClickListener {

            is_public = if (is_public == 1) 0 else 1
            vm.isPush.value = is_public

        }

        binding.tvPublish.setOnClickListener{
            //提交
            judgeValue()
        }

        binding.llDriver.setOnClickListener {
            //指定常用司机
            UiSwitch.singleRes(this, CollectionActivity::class.java, MIntentAction.REQUEST_CODE_THREE)

        }

    }

    private fun judgeValue() {

        var type_id=binding.viewHead.type_id
        if(TextUtils.isEmpty(type_id)){
            toast("请选择车型！")
            return
        }
        if (TextUtils.isEmpty(province_out)) {
            toast("请选择装货地址！")
            return

        }
        var name_out = binding.viewHead.getEtName()!!.text.toString().trim()
        if (TextUtils.isEmpty(name_out)) {
            toast("请输入发货人!")
            return
        }
        var mobile_out = binding.viewHead.getEtPhone()!!.text.toString().trim()
        if (TextUtils.isEmpty(mobile_out)) {
            toast("请输入发货人电话!")
            return
        }
        if (TextUtils.isEmpty(time_out)) {
            toast("请输入装货时间")
            return
        }
        var address_out = binding.viewHead.getEtDetailedAddress()!!.text.toString().trim()
        var sendBean = SendBean(lat_out, lng_out, province_out, city_out, area_out, address_out, name_out, mobile_out, time_out, "0")

        var list=adapter!!.data as ArrayList<ReceiveBean>

        var total:Double=0.00
        for(item in list){
            if (TextUtils.isEmpty(item.province)) {
                toast("请选择卸货地址！")
                return
            }
            if (TextUtils.isEmpty(item.name)) {
                toast("请输入卸货人!")
                return
            }
            if (TextUtils.isEmpty(item.mobile)) {
                toast("请输入卸货人电话!")
                return
            }
            if (TextUtils.isEmpty(item.time)) {
                toast("请输入卸货时间")
                return
            }
            if (TextUtils.isEmpty(item.goods)) {
                toast("请输入货物名称")
                return
            }
            if (TextUtils.isEmpty(item.goods_type)) {
                toast("请选择货物类型")
                return
            }
            if (TextUtils.isEmpty(item.nums)) {
                toast("请输入单车运量数量")
                return
            }
            if (TextUtils.isEmpty(item.nums_type)) {
                toast("请选择单车运量单位")
                return
            }

            total += item.total.toDouble()

        }

        if (is_agree==0) {
            toast("请阅读并同意《平台运输协议》")
            return
        }
        var carnums=binding.etCarNums.text.toString()
        if(TextUtils.isEmpty(carnums)){
            toast("请输入所需车辆数量")
            return
        }
        var data=binding.etData.text.toString()

        var sendList=ArrayList<SendBean>()
        sendList.add(sendBean)
        var send= Gson().toJson(sendList)

        var receive= Gson().toJson(list)

       // var total = binding.etSingCarTotal.text.toString().trim()

        var df = DecimalFormat("0.00")
        var driver=Gson().toJson(driverList)


        vm.setReleaseSource(info_id,type_id,df.format(total),driver,carnums,is_public.toString(),is_insurance.toString(),"2",
                data,send,receive)



    }

    private fun addList(){

        var bean=ReceiveBean("","","","","","","","","",
                "1","","","","","","","","")
        receiveList.add(bean)
        adapter!!.addData(bean)
        toast("添加一条")

    }

    private fun initTab(info: DataInfoBean) {
        binding.viewHead.setHeadData(info,childFragmentManager)

        //设置默认装货地址-卸货地址
        if(null!=info.default_send){
            binding.viewHead.getTvCity()!!.text = info.default_send.province.name + info.default_send.city.name + info.default_send.area.name
            binding.viewHead.getEtDetailedAddress()!!.setText(info.default_send.address)
            binding.viewHead.getTvChoseTime()!!.text = info.default_send.create_time
            binding.viewHead.getEtName()!!.setText(info.default_send.name)
            binding.viewHead.getEtPhone()!!.setText(info.default_send.mobile)
            lat_out = info.default_send.lat.toString()
            lng_out = info.default_send.lng.toString()
            area_out = info.default_send.area!!.code.toString()
            province_out = info.default_send.province!!.code.toString()
            city_out = info.default_send.city!!.code.toString()
            time_out = info.default_send.create_time.toString()
        }

        binding.viewHead.getImgNext()!!.setOnClickListener {


            var selectViewpage = binding.viewHead.getQmViewPager()!!.currentItem

            if (selectViewpage < binding.viewHead.getCats().size - 1) {
                binding.viewHead.getQmViewPager()!!.currentItem = selectViewpage + 1
            }

        }
        //向右
        binding.viewHead.getImgDown()!!.setOnClickListener {
            toast("222")
            var selectViewpage =binding.viewHead.getQmViewPager()!!.currentItem
            if (selectViewpage < binding.viewHead.getCats().size - 1) {
                binding.viewHead.getQmViewPager()!!.currentItem = selectViewpage + 1
            }


        }

        //向左
        binding.viewHead.getImgUp()!!.setOnClickListener {
            var selectViewpage = binding.viewHead.getQmViewPager()!!.currentItem

            if (selectViewpage < binding.viewHead.getCats().size - 1 && selectViewpage > 0) {
                binding.viewHead.getQmViewPager()!!.currentItem = selectViewpage - 1
            }
        }

    }

    private fun getData() {
        //获取信息
        vm.getDataInfo(info_id);

    }
    private fun initAdapter(){
        //默认一个出
        adapter= CarEnterAdapter(vm)
        adapter!!.setData(goodsTypeList,numsTypeList)
        binding.recyclerView.adapter=adapter
        var bean=ReceiveBean("","","","","","","","","",
                "1","","","","","","","","")
        receiveList.add(bean)
        adapter!!.addData(bean)

    }
    private fun initData() {

        insurance.add("是")
        insurance.add("否")

        binding.viewHead.getLlChoseMap()!!.setOnClickListener {
            //地图选点
            vm.type = 1
            vm.goChoseMap()
        }

        binding.viewHead.getLlChoseAddress()!!.setOnClickListener {
            //地址薄 1
            vm.type = 1
            UiSwitch.bundleRes(this, AddressActivity::class.java,
                    B.with().putString("type", "1").ok(), MIntentAction.REQUEST_CODE_ONE)
        }

        binding.viewHead.getTvCity()!!.setOnClickListener {
            vm.type = 1
            UiSwitch.singleRes(this, AreaSelectActivity::class.java,
                    MIntentAction.REQUEST_CODE_TWO)
        }
        //装货时间
        binding.viewHead.getTvChoseTime()!!.setOnClickListener {
            PopupUtils.setChoseTime(context, binding.viewHead.getTvChoseTime(), object : ChoiceData {
                override fun onRestuse(time: String?) {
                    if (time != null) {
                        time_out = time
                    }
                }
            })
        }

    }



    override fun binding(inflater: LayoutInflater, container: ViewGroup?): FragmentOwnermoreBinding {
       return  FragmentOwnermoreBinding.inflate(layoutInflater)
    }

    override fun vmClass(): Class<OwnerMoreVModel> {
        return OwnerMoreVModel::class.java
    }


    override fun title(): String? {
        return null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (MIntentAction.REQUEST_CODE_TWO === requestCode && resultCode == Activity.RESULT_OK) {
            val bundle = data!!.extras
            if (null != bundle) {
                var name = bundle.getString("name")
                if (vm.type == 1) {

                    area_out = bundle.getString("area_code")
                    province_out = bundle.getString("province_code")
                    city_out = bundle.getString("city_code")

                    binding.viewHead.getTvCity()!!.text = name
                } else {
                var list=adapter!!.data as ArrayList<ReceiveBean>
                    list[vm.position].area=bundle.getString("area_code")
                    list[vm.position].province=bundle.getString("province_code")
                    list[vm.position].city=bundle.getString("city_code")
                    list[vm.position].pca=name
                    adapter!!.notifyItemChanged(vm.position)

                }

            }
            return

        }

        if (MIntentAction.REQUEST_CODE_ONE == requestCode && resultCode == Activity.RESULT_OK) {
            val bundle = data!!.extras
            if (null != bundle) {
                var item = bundle.getSerializable("item") as AddressBean
                //todo
                if (vm.type == 1) {
                    binding.viewHead.getTvCity()!!.text = item.province?.name + item.city?.name + item.area?.name
                    binding.viewHead.getEtDetailedAddress()!!.setText(item.address)
                    binding.viewHead.getTvChoseTime()!!.text = item.create_time
                    binding.viewHead.getEtName()!!.setText(item.name)
                    binding.viewHead.getEtPhone()!!.setText(item.mobile)
                    lat_out = item.lat.toString()
                    lng_out = item.lng.toString()
                    area_out = item.area!!.code.toString()
                    province_out = item.province!!.code.toString()
                    city_out = item.city!!.code.toString()

                } else {
                    var list=adapter!!.data as ArrayList<ReceiveBean>
                    list[vm.position].area=item.area!!.code.toString()
                    list[vm.position].province=item.province!!.code.toString()
                    list[vm.position].city=item.city!!.code.toString()
                    list[vm.position].lat=item.lat.toString()
                    list[vm.position].lng=item.lng.toString()

                    list[vm.position].address=item.address.toString()
                    list[vm.position].address=item.address.toString()
                    list[vm.position].address=item.address.toString()
                    list[vm.position].address=item.address.toString()

                    list[vm.position].pca=item.province!!.name.toString()+item.city!!.name.toString()+item.area!!.name.toString()

                    list[vm.position].name=item.name.toString()
                    list[vm.position].mobile=item.mobile.toString()

                    adapter!!.notifyItemChanged(vm.position)


//
//
                }

            }

            return

        }

        if (MIntentAction.REQUEST_CODE_THREE == requestCode && resultCode == Activity.RESULT_OK){
            //常用司机
            val bundle = data!!.extras
            if (null != bundle) {
                driverList.clear()

                var  arr=bundle.getSerializable("driver") as ArrayList<String>
                driverList.addAll(arr)
                binding.tvDriver.text="已指定"+driverList.size+"人"

            }

            return
        }


    }

    override val isRxbus: Boolean
        get() =true


    @Subscribe(tags = [Tag(ConfigRx.ADD_POSITION)])
    fun getPosition(bean: PositionBean) {

        if (vm.type == 2) {

            var list=adapter!!.data as ArrayList<ReceiveBean>

            Log.e("-shy-", "position= "+vm.position )

            list[vm.position].area= bean.areacode
            list[vm.position].province=bean.areacode.substring(0, 2) + "0000"
            list[vm.position].city=bean.areacode.substring(0, 4) + "00"
            list[vm.position].lat=bean.latitude
            list[vm.position].lng=bean.longitude
            list[vm.position].address=bean.position
            list[vm.position].pca=bean.provincename + bean.cityname + bean.areaname
            adapter!!.notifyItemChanged(vm.position)



        } else {

            lat_out = bean.latitude
            lng_out = bean.longitude
            area_out = bean.areacode
            province_out = bean.areacode.substring(0, 2) + "0000"
            city_out = bean.areacode.substring(0, 4) + "00"
            binding.viewHead.getEtDetailedAddress()!!.setText(bean.position)
            binding.viewHead.getTvCity()!!.text = bean.provincename + bean.cityname + bean.areaname
        }
    }


    @Subscribe(tags = [Tag(ConfigRx.SUM_AGAIN)])
    fun setSumAgain(type:String) {
        //重新计算总和

        //重新计算总和
        var list=adapter!!.data as ArrayList<ReceiveBean>
        var df = DecimalFormat("0.00");
        var total:Double = 0.00
        for(item in list){
            if(TextUtils.isEmpty(item.total)){
                item.total="0"
            }
            Log.e("-shy-", "item.total=: "+item.total )
            total += item.total.toDouble()

        }
        binding.tvTotalMoney.text = df.format(total)


        Log.e("-shy-", "list="+Gson().toJson(list))


    }


}
