package com.quansu.heifengwuliu.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.quansu.heifengwuliu.activity.AddressActivity
import com.quansu.heifengwuliu.activity.AreaSelectActivity
import com.quansu.heifengwuliu.activity.CollectionActivity
import com.quansu.heifengwuliu.base.MBFragment
import com.quansu.heifengwuliu.config.ConfigRx
import com.quansu.heifengwuliu.config.MIntentAction
import com.quansu.heifengwuliu.databinding.FragmentOwnersingleBinding
import com.quansu.heifengwuliu.inte.ChoiceData
import com.quansu.heifengwuliu.inte.ChoiceListData
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.OwnerSingleVModel
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import com.ysnows.base.ccretrofit.CCRetrofit
import com.ysnows.base.model.PositionBean
import com.ysnows.base.route.IGaode
import com.ysnows.base.utils.B
import com.ysnows.base.utils.UiSwitch
import java.text.DecimalFormat

/**
 * 一装一卸
 *Created by shihuiyun
 *on 2020/9/11
 */
class OwnerSingleFragment : MBFragment<OwnerSingleVModel, FragmentOwnersingleBinding>() {
    private var type = 1// 1:/装货 2卸货

    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 lat_in: String = ""
    var lng_in: String = ""
    var province_in: String = ""
    var city_in: String = ""
    var area_in: String = ""
    var time_in: String = ""

    var info_id:String="0"
    var goods_type_code="0"
    //常用司机
    var driverList=ArrayList<String>()



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

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

            numsTypeList.addAll(it.nums_type)
            initTab(it)

        })

        initData()

    }


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

    override fun listeners() {
        super.listeners()
        binding.tvPublish.setOnClickListener {
            //发布
            judgeValue()

        }

        binding.llChoseUnits.setOnClickListener {

            PopuListUtils.showQMUIPopup(context(), binding.llChoseUnits, numsTypeList, object : ChoiceData {
                override fun onRestuse(name: String?) {
                    vm.unit.value = name
                }
            })
        }


        binding.llGoodsType.setOnClickListener {

            PopuListUtils.showQMUIPopup(context(), binding.llGoodsType, goodsTypeList, object : ChoiceListData {
            override fun onRestuse(code: String?,name: String?) {
                goods_type_code=code!!
                vm.goodstype.value = name

            }
        })
        }

        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.etSingCarNums.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun afterTextChanged(editable: Editable) {
                var nums = editable.toString().trim()
                if (TextUtils.isEmpty(nums)) {
                    nums = "0"
                }
                sumTotal(1, nums)

            }
        })

        binding.etSingCarPrice.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun afterTextChanged(editable: Editable) {
                var price = editable.toString().trim()
                if (TextUtils.isEmpty(price)) {
                    price = "0"
                }
                sumTotal(2, price)

            }
        })

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

        }



    }


    private fun judgeValue() {

//        UiSwitch.bundle(context, SourceDetailsActivity::class.java, Bundle().apply {
//            putString("info_id", "55")
//            putString("type","1")
//        })
//
//        return

        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")


        if (TextUtils.isEmpty(province_in)) {
            toast("请选择卸货地址！")
            return

        }
        var name_in = binding.viewEnter.getEtName()!!.text.toString().trim()
        if (TextUtils.isEmpty(name_in)) {
            toast("请输入卸货人!")
            return
        }
        var mobile_in = binding.viewEnter.getEtPhone()!!.text.toString().trim()
        if (TextUtils.isEmpty(mobile_in)) {
            toast("请输入卸货人电话!")
            return
        }
        if (TextUtils.isEmpty(time_in)) {
            toast("请输入卸货时间")
            return
        }

        var goods_name=binding.etGoodsName.text.toString().trim()

        if (TextUtils.isEmpty(goods_name)) {
            toast("请输入货物名称")
            return
        }

        if (TextUtils.isEmpty(vm.goodstype.value.toString())) {
            toast("请选择货物类型")
            return
        }
        if (TextUtils.isEmpty(vm.unit.value.toString())) {
            toast("请选择单车运量单位")
            return
        }

        var nums = binding.etSingCarNums.text.toString().trim()

        if (TextUtils.isEmpty(vm.unit.value.toString())) {
            toast("请输入单车运量数量")
            return
        }
        var price = binding.etSingCarPrice.text.toString().trim()
        var total = binding.etSingCarTotal.text.toString().trim()
        if (TextUtils.isEmpty(vm.unit.value.toString())) {
            toast("请输入总金额")
            return
        }

        var address_in = binding.viewEnter.getEtDetailedAddress()!!.text.toString().trim()

        var receiveBean = ReceiveBean(lat_in, lng_in, province_in, city_in, area_in, address_in, name_in, mobile_in, time_in, "1",
                goods_name, goods_type_code, nums, vm.unit.value.toString(), price, total,"",""
        )

        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 receiveList=ArrayList<ReceiveBean>()
        receiveList.add(receiveBean)

        var receive= Gson().toJson(receiveList)

        var driver=Gson().toJson(driverList)

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

    }


    /**
     * type:1单车运量 2单价
     * value:输入的值
     * @return
     */
    private fun sumTotal(type: Int, value: String) {
        var df = DecimalFormat("0.00")
        var total = "0"
        if (type == 1) {//数量
            var price = binding.etSingCarPrice.text.toString().trim()
            if (TextUtils.isEmpty(price)) {
                price = "0"
            }
            total = df.format(value.toDouble() * price.toDouble())
        } else {//价格
            var nums = binding.etSingCarNums.text.toString().trim()
            if (TextUtils.isEmpty(nums)) {
                nums = "0"
            }
            var df = DecimalFormat("0.00");
            total = df.format(nums.toDouble() * value.toDouble())

        }
        binding.etSingCarTotal.setText(total)

    }


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

    }


    private fun initTab(info: DataInfoBean) {


        binding.viewHead.setHeadData(info,childFragmentManager)
        if(null!=info.car_type&& info.car_type.isNotEmpty()) {
            binding.etSingCarNums.setText(info.car_type[0].weight)
        }
        //设置默认装货地址-卸货地址
        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()
        }
        if(null!=info.default_receive){

            binding.viewEnter.getTvCity()!!.text = info.default_receive.province?.name + info.default_receive.city?.name + info.default_receive.area?.name
            binding.viewEnter.getEtDetailedAddress()!!.setText(info.default_receive.address)
            binding.viewEnter.getTvChoseTime()!!.text = info.default_receive.create_time
            binding.viewEnter.getEtName()!!.setText(info.default_receive.name)
            binding.viewEnter.getEtPhone()!!.setText(info.default_receive.mobile)
            lat_in = info.default_receive.lat.toString()
            lng_in = info.default_receive.lng.toString()
            area_in = info.default_receive.area!!.code.toString()
            province_in = info.default_receive.province!!.code.toString()
            city_in = info.default_receive.city!!.code.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 initData() {


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

        //卸货信息
        binding.viewEnter.getTvCity()!!.hint = "请选择卸货地址"
        binding.viewEnter.getTvChoseTime()!!.hint = "请选择卸货时间"

        binding.viewEnter.getLlChoseMap()!!.setOnClickListener {
            //地图选点
            type = 2
            choseMap()
        }

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

        binding.viewEnter.getTvCity()!!.setOnClickListener {

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

        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 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 (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 {
                    area_in = bundle.getString("area_code")
                    province_in = bundle.getString("province_code")
                    city_in = bundle.getString("city_code")
                    binding.viewEnter.getTvCity()!!.text = name
                }

            }
            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 (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()
                    time_out = item.create_time.toString()

                } else {

                    binding.viewEnter.getTvCity()!!.text = item.province?.name + item.city?.name + item.area?.name
                    binding.viewEnter.getEtDetailedAddress()!!.setText(item.address)
                    binding.viewEnter.getTvChoseTime()!!.text = item.create_time
                    binding.viewEnter.getEtName()!!.setText(item.name)
                    binding.viewEnter.getEtPhone()!!.setText(item.mobile)
                    lat_in = item.lat.toString()
                    lng_in = item.lng.toString()
                    area_in = item.area!!.code.toString()
                    province_in = item.province!!.code.toString()
                    city_in = item.city!!.code.toString()
                    time_in = item.create_time.toString()
                }

            }

            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
        }




    }


    private fun choseMap() {

        AndPermission.with(repository().context)
                .runtime()
                .permission(Permission.ACCESS_COARSE_LOCATION,
                        Permission.ACCESS_FINE_LOCATION,
                        Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.READ_PHONE_STATE
                )
                .onGranted { data ->
                    CCRetrofit.instance()
                            .with(context)
                            .create(IGaode::class.java)
                            .selectLocation()
                            .subscribe()

                }
                .start()

    }


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

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

    override val isRxbus: Boolean
        get() = true


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

        var provincename = bean.provincename
        var latitude = bean.latitude
        var longitude = bean.longitude
        if (type == 2) {

            lat_in = bean.latitude
            lng_in = bean.longitude
            area_in = bean.areacode
            province_in = bean.areacode.substring(0, 2) + "0000"
            city_in = bean.areacode.substring(0, 4) + "00"
            binding.viewEnter.getEtDetailedAddress()!!.setText(bean.position)
            binding.viewEnter.getTvCity()!!.text = bean.provincename + bean.cityname + bean.areaname
        } 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.CHOSE_CAR)])
    fun choseCar(weight: String) {
        //切换车辆
        binding.etSingCarNums.setText(weight)
    }


}

