package auto_delivery

import (
	"crypto/rand"
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable"
	"git.rosy.net.cn/jx-callback/business/jxcallback/scheduler/defsch"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/partner"
	"math/big"
	"strings"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
)

var riderListInfo = make(map[string][]map[string]string, 0)

func Init() {
	if len(riderListInfo) != 0 {
		return
	}
	db := dao.GetDB()
	// 骑手列表
	configRiderList, err := dao.QueryConfigs(db, "riderList", "Sys", "")
	if err != nil {
		globals.SugarLogger.Errorf("抖音自动刷单获取骑手列表错误:%v", err)
		return
	}
	list := make(map[string][]map[string]string, 0)
	if len(configRiderList[0].Value) > 0 {
		if err := json.Unmarshal([]byte(configRiderList[0].Value), &list); err != nil {
			globals.SugarLogger.Errorf("抖音自动刷单获取骑手列表错误:%v", err)
			return
		}
	}

	// 获取刷单地址
	addressList, err := dao.QueryConfigs(db, "refundAddress", "Sys", "")
	if err != nil {
		globals.SugarLogger.Errorf("抖音自动刷单获取刷单地址列表错误:%v", err)
		return
	}

	for _, v := range strings.Split(addressList[0].Value, ",") {
		if _, ok := list[v]; ok && len(list[v]) >= 200 {
			continue
		}
		riderList, err := dao.GetAddressRiderInfo(db, v)
		if err != nil {
			globals.SugarLogger.Errorf("初始化各省份骑手信息错误:[%v]", err)
			return
		}
		addressRiderList := make([]map[string]string, 0)
		for i := 0; i < len(riderList); i++ {
			if len(riderList[i].CourierMobile) == 11 {
				riderMap := make(map[string]string, 1)
				riderMap[riderList[i].CourierName] = riderList[i].CourierMobile
				addressRiderList = append(addressRiderList, riderMap)
			}
			if len(addressRiderList) >= 200 {
				list[v] = addressRiderList
				break
			}
		}
	}

	listStr, err := json.Marshal(list)
	if err != nil {
		globals.SugarLogger.Errorf("Marshal 骑手信息错误:[%v]", err)
		return
	}

	if err := dao.UpdateOperatorConfig(string(listStr), "Sys", "riderList"); err != nil {
		globals.SugarLogger.Errorf("UpdateOperatorConfig 骑手配置信息错误:[%v]", err)
		return
	}
	riderListInfo = list
}

// AutoSettingFakeDelivery 抖音自动设置骑手, 推送假订单
func AutoSettingFakeDelivery() {
	db := dao.GetDB()

	// 查询需要刷单的门店
	configList, err := dao.QueryConfigs(db, "storeIdList", "Sys", "")
	if err != nil {
		globals.SugarLogger.Errorf("抖音自动刷单获取刷单门店列表错误:%v", err)
		return
	}
	if len(configList) != model.YES {
		globals.SugarLogger.Errorf("newConfig 刷单门店设置异常")
		return
	}

	// 获取刷单门店订单
	storeList := strings.Split(configList[0].Value, ",")
	for _, v := range storeList {
		if !strings.Contains(v, "-") {
			globals.SugarLogger.Errorf("newConfig 刷单门店配置异常")
			return
		}
		storeIdAndVendorId := strings.Split(v, "-")
		if len(storeIdAndVendorId) == model.NO {
			continue
		}
		orderList, err := dao.GetOrderListByStoreList(db, []int64{utils.Str2Int64(storeIdAndVendorId[0])}, utils.Str2Int(storeIdAndVendorId[1]))
		if err != nil {
			globals.SugarLogger.Errorf("获取门店刷单记录错误")
			continue
		}
		if len(orderList) == model.NO {
			continue
		}

		// 1.根据订单客户地址获取骑手列表
		riderKey := ""
		storeDetail, _ := dao.GetStoreDetail(db, utils.Str2Int(storeIdAndVendorId[0]), 0, "")
		if strings.Contains(storeDetail.Address, "重庆") || strings.Contains(storeDetail.Address, "上海") || strings.Contains(storeDetail.Address, "北京") || strings.Contains(storeDetail.Address, "天津") {
			riderKey = strings.Split(storeDetail.Address, "市")[0]
		} else if strings.Contains(storeDetail.Address, "省") {
			riderKey = strings.Split(storeDetail.Address, "省")[0]
		} else {
			place, err := dao.GetParentCodeByCode(db, storeDetail.CityCode)
			if err != nil {
				return
			}
			if strings.Contains(place.Name, "省") {
				riderKey = strings.Split(place.Name, "省")[0]
			} else {
				riderKey = strings.Split(place.Name, "市")[0]
			}
		}

		for _, order := range orderList {
			if len(riderListInfo[riderKey]) == model.NO {
				// 骑手列表
				configRiderList, err := dao.QueryConfigs(db, "riderList", "Sys", "")
				if err != nil {
					globals.SugarLogger.Errorf("抖音自动刷单获取骑手列表错误:%v", err)
					return
				}
				if err := json.Unmarshal([]byte(configRiderList[0].Value), &riderListInfo); err != nil {
					globals.SugarLogger.Errorf("抖音自动刷单获取骑手列表错误:%v", err)
					return
				}
			}
			randNumber, _ := rand.Int(rand.Reader, big.NewInt(int64(len(riderListInfo[riderKey]))))
			randTime := randNumber.Int64()
			if randTime < 0 {
				randTime = 1
			}
			if randTime >= int64(len(riderListInfo[riderKey])) {
				randTime = int64(len(riderListInfo[riderKey])) - 1
			}
			if (order.PhoneAscription == "" || strings.Split(order.PhoneAscription, "-")[0] != model.PhoneAscriptionAddressYes) && order.VendorID == model.VendorIDDD {
				continue
			}
			// 自动拣货
			if order.Status < model.OrderStatusFinishedPickup { // 未拣货
				handler := partner.GetPurchaseOrderHandlerFromVendorID(order.VendorID)
				flag := model.IsOrderDeliveryByStore(order) || model.IsOrderDeliveryBySelf(order)
				if err := handler.PickupGoods(order, flag, jxcontext.AdminCtx.GetUserName()); err != nil {
					partner.CurOrderManager.OnOrderMsg(order, tao_vegetable.OrderStatusPickedUp, fmt.Sprintf("自动拣货错误:[%v]", err))
					break
				}
				partner.CurOrderManager.OnOrderMsg(order, tao_vegetable.OrderStatusPickedUp, "fake自动拣货,已拣货")
			}
			//自动发单
			if len(riderListInfo[riderKey]) == 0 {
				globals.SugarLogger.Errorf("riderListInfo[riderKey][randTime] :%s,%s,%d", riderListInfo[riderKey][randTime], riderKey, randTime)
				break
			}
			for riderName, riderPhone := range riderListInfo[riderKey][randTime] {
				if err := defsch.FixedScheduler.SelfDeliveringAndUpdateStatus(jxcontext.AdminCtx, order.VendorOrderID, order.VendorID, jxcontext.AdminCtx.GetUserName(), riderName, riderPhone); err != nil {
					partner.CurOrderManager.OnOrderMsg(order, tao_vegetable.OrderStatusPickedUp, fmt.Sprintf("自动发货错误:[%v]", err))
					break
				}
				partner.CurOrderManager.OnOrderMsg(order, tao_vegetable.OrderStatusCallRider, "自动发货,出库")
			}
		}

	}

}
