package com.hfkj.service.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.OrderUtil;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.dao.BsOrderGoodsMapper;
import com.hfkj.dao.GoodsLogisticsMapper;
import com.hfkj.entity.BsOrderGoods;
import com.hfkj.entity.BsOrderGoodsExample;
import com.hfkj.entity.GoodsLogistics;
import com.hfkj.entity.GoodsLogisticsExample;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.goods.BsOrderGoodsService;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.sysenum.order.OrderChildStatusEnum;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("bsOrderGoodsService")
public class BsOrderGoodsServiceImpl implements BsOrderGoodsService {

    // 缓存前缀KEY
    public final static String CACHE_KEY = "LOGISTICS:";
    // 订单缓存时间 7天
    public final static Integer CACHE_TIME = 60*30;

    @Resource
    private BsOrderGoodsMapper bsOrderGoodsMapper;
    @Resource
    private GoodsLogisticsMapper goodsLogisticsMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private BsOrderService orderService;


    @Override
    public void create(BsOrderGoods orderGoods) {
        bsOrderGoodsMapper.insert(orderGoods);
    }

    @Override
    public void update(BsOrderGoods orderGoods) {
        bsOrderGoodsMapper.updateByPrimaryKeySelective(orderGoods);
    }

    @Override
    public void delete(Long id, Boolean fullDelete) {
        if (fullDelete) {
            bsOrderGoodsMapper.deleteByPrimaryKey(id);
        } else {
            BsOrderGoods orderGoods = queryDetail(id);
            orderGoods.setStatus(0);
            orderGoods.setUpdateTime(new Date());
            update(orderGoods);
        }
    }

    @Override
    public BsOrderGoods findGoodsOrder(String orderNo) {
        BsOrderGoodsExample example = new BsOrderGoodsExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);

        List<BsOrderGoods> list = bsOrderGoodsMapper.selectByExample(example);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public BsOrderGoods findGoodsOrderLogisticsNo(String logisticsNo) {
        BsOrderGoodsExample example = new BsOrderGoodsExample();
        example.createCriteria().andStatusNotEqualTo(0).andLogisticsNoEqualTo(logisticsNo);

        List<BsOrderGoods> list = bsOrderGoodsMapper.selectByExample(example);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public BsOrderGoods findGoodsOrderByChild(String orderChildNo) {
        BsOrderGoodsExample example = new BsOrderGoodsExample();
        example.createCriteria().andChildOrderNoEqualTo(orderChildNo);

        List<BsOrderGoods> list = bsOrderGoodsMapper.selectByExample(example);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public BsOrderGoods queryDetail(Long id) {
        return bsOrderGoodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public BsOrderGoods queryDetailByMap(Map<String, Object> map) {
        return null;
    }

    @Override
    public List<BsOrderGoods> getList(Map<String, Object> map) {
        BsOrderGoodsExample example = new BsOrderGoodsExample();
        BsOrderGoodsExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "merId") != null) {
            criteria.andMerIdEqualTo(MapUtils.getLong(map, "merId"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "logisticsNo"))) {
            criteria.andLogisticsNoEqualTo(MapUtils.getString(map, "logisticsNo"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "orderNo"))) {
            criteria.andOrderNoEqualTo(MapUtils.getString(map, "orderNo"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "childOrderNo"))) {
            criteria.andChildOrderNoEqualTo(MapUtils.getString(map, "childOrderNo"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "userPhone"))) {
            criteria.andUserPhoneEqualTo(MapUtils.getString(map, "userPhone"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "logisticsStatus"))) {
            if (MapUtils.getString(map , "logisticsStatus").equals("待发货")) {
                criteria.andLogisticsStatusIsNull();
            } else {
                criteria.andLogisticsStatusEqualTo(MapUtils.getString(map, "logisticsStatus"));
            }

        }
        if (MapUtils.getLong(map, "goodsType") != null) {
            criteria.andGoodsTypeIdEqualTo(MapUtils.getLong(map, "goodsType"));
        }
        if (MapUtils.getLong(map, "goodsBrand") != null) {
            criteria.andGoodsBrandIdEqualTo(MapUtils.getLong(map, "goodsBrand"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "goodsSpecsName"))) {
            criteria.andGoodsSpecsNameEqualTo(MapUtils.getString(map, "goodsSpecsName"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "platformCode"))) {
            criteria.andPlatformCodeEqualTo(MapUtils.getString(map, "platformCode"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "goodsName"))) {
            criteria.andGoodsNameLike("%"+MapUtils.getString(map, "goodsName")+"%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "deliveryAddress"))) {
            criteria.andDeliveryAddressLike("%"+MapUtils.getString(map, "deliveryAddress")+"%");
        }
        if (MapUtils.getInteger(map, "payType") != null) {
            criteria.andPayTypeEqualTo(MapUtils.getInteger(map, "payType"));
        }
        if (MapUtils.getLong(map, "createTimeS") != null) {
            criteria.andCreateTimeGreaterThanOrEqualTo(new Date(MapUtils.getLong(map, "createTimeS")));
        }
        if (MapUtils.getLong(map, "createTimeE") != null) {
            criteria.andCreateTimeLessThan(new Date(MapUtils.getLong(map, "createTimeE")));
        }
        if (MapUtils.getInteger(map, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(map, "status"));
        } else {
            criteria.andStatusNotEqualTo(0);
        }
        example.setOrderByClause("create_time desc");
        return bsOrderGoodsMapper.selectByExample(example);
    }

    @Override
    public List<BsOrderGoods> getList() {
        BsOrderGoodsExample example = new BsOrderGoodsExample();

        return bsOrderGoodsMapper.selectByExample(example);
    }

    @Override
    public GoodsLogistics findGoodsLogistics(Long orderGoodsId) {
        GoodsLogisticsExample example = new GoodsLogisticsExample();
        GoodsLogisticsExample.Criteria criteria = example.createCriteria();

        criteria.andOrderIdEqualTo(orderGoodsId).andStatusEqualTo(1);

        List<GoodsLogistics> logistics = goodsLogisticsMapper.selectByExample(example);

        if (logistics.size() > 0) {
            return logistics.get(0);
        }

        return null;
    }

    @Override
    public GoodsLogistics findGoodsLogisticsByNum(String num) {
        GoodsLogisticsExample example = new GoodsLogisticsExample();
        GoodsLogisticsExample.Criteria criteria = example.createCriteria();

        criteria.andNumberEqualTo(num).andStatusEqualTo(1);

        List<GoodsLogistics> logistics = goodsLogisticsMapper.selectByExample(example);

        if (logistics.size() > 0) {
            return logistics.get(0);
        }

        return null;
    }

    @Override
    public GoodsLogistics editLogistics(JSONObject jsonObject) {

        JSONObject info = (JSONObject) jsonObject.getJSONArray("info").get(0);

        GoodsLogistics logistics = findGoodsLogisticsByNum(info.getString("mailNo"));

        if (logistics == null) {
            logistics = new GoodsLogistics();
        }

        logistics.setTaskNo(jsonObject.getString("orderNo"));

        logistics.setTheLastTime(info.getDate("theLastTime"));
        logistics.setTheLastMessage(info.getString("theLastMessage"));
        logistics.setTakeTime(info.getString("takeTime"));
        logistics.setNumber(info.getString("mailNo"));
        logistics.setLogisticsStatus(info.getString("logisticsStatus"));
        logistics.setExpressCompanyName(info.getString("logisticsCompanyName"));
        logistics.setLogisticsStatusDesc(info.getString("logisticsStatusDesc"));
        logistics.setLogisticsTraceDetails(info.getString("logisticsTraceDetailList"));
        logistics.setStatus(1);
        if ( logistics.getId() == null || !Objects.equals(logistics.getOrderId(), jsonObject.getLong("orderId"))) {
            logistics.setOrderId(jsonObject.getLong("orderId"));
            logistics.setCreateTime(new Date());
            goodsLogisticsMapper.insert(logistics);
        } else {
            logistics.setOrderId(jsonObject.getLong("orderId"));
            goodsLogisticsMapper.updateByPrimaryKeySelective(logistics);
        }

        return logistics;
    }

    @Override
    public Object getLogisticsMsg(String logisticsNo , String mobile) {
        JSONObject jsonObjects = OrderUtil.getLogisticsMsg(logisticsNo , mobile);
        if (jsonObjects == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂未发货！");
        }
        System.out.println("======================================" + jsonObjects);
        return editLogistics((JSONObject) jsonObjects.get("data"));
    }



    @Override
    public void confirmReceipt(Long orderGoodsId) {
        BsOrderGoods orderGoods = queryDetail(orderGoodsId);
        if (orderGoods == null ||
                orderGoods.getStatus() == 1 ||
                orderGoods.getStatus() == 5 ||
                orderGoods.getStatus() == 6 ||
                orderGoods.getStatus() == 7 ||
                orderGoods.getStatus() == 8) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态，不支持确认收货！");
        }


        // 子订单完成
        orderService.childOrderComplete(orderGoods.getChildOrderNo());
        orderGoods.setStatus(OrderChildStatusEnum.status3.getCode());
        orderGoods.setUpdateTime(new Date());
        orderGoods.setFinishTime(new Date());
        update(orderGoods);
        // 删除缓存
        orderService.cacheDelete(orderGoods.getOrderNo());
    }
}
