package com.reptileclient.jlifeapp.schedule;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.reptileclient.jlifeapp.dao.jz.*;
import com.reptileclient.jlifeapp.entity.jz.*;
import com.reptileclient.jlifeapp.util.DateUtils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author fuxubing
 *  * 增量新增流程：
 * 1，同步服务付款单到JzOrder表
 * 2，根据同步内容 生成Customer 并更新JzOrder表的外键user_Id
 * 3, 同步服务单到JzBookOrder表
 * 4，根据serviceContactNo主订单号 关联JzOrder和JzBookOrder表的Order_Id
 *  * 差异数据同步
 *  1，取服务付款单支付状态为：已服务、已取消、已完成 （600条数据）
 *  2，如果发现JzOrder表状态和获取盒马数据不一致，更新JzOrder和JzBookOrder
 */
@Async
@Component
public class JzOrderTask {
    private static final Logger logger = LoggerFactory.getLogger(JzOrderTask.class);
    @Resource
    private JzBookOrderMapper jzBookOrderMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private CustomerClientMapper customerClientMapper;
    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource
    private JzShopMapper jzShopMapper;


    /**
     * 每天3点执行一次,将盒马服务单payment_no is null的数据转为jz_order订单
     */
    //@Scheduled(cron = "0 */1 * * * ?")
//    @Scheduled(cron = "0 0 3 * * ?")
    public void runTask() {
        logger.info("开始执行盒马服务单payment_no为空的数据转为jz_order订单");//其他渠道，非盒马订单 只有服务单，没有付款单

        new Thread(() -> {
            List<JzBookOrder> jzBookOrders = jzBookOrderMapper.selectListByPaymentNo();

            jzBookOrders.forEach(item -> {
                //客户
                CustomerClient customerClient = insertCustomerClient(item.getPhone(), item.getUserName(), item.getAddress());
                //订单
                Order order = insertOrder(customerClient.getId().intValue(), item);
                //订单商品
                insertGoods(order, item);
                //更新payment_no
                item.setPaymentNo(item.getBookOrderNo().toString());
                jzBookOrderMapper.updateByPrimaryKeySelective(item);
            });
        }).start();
    }


    /**
     * 订单状态设置
     *
     * @param status
     * @return
     */
    private Short setOrderStatus(Integer status) {
        short orderStatus = 101;
        if (4 == status) {
            orderStatus = 202;
        } else if (0 == status || 1 == status || 3 == status || 5 == status) {
            orderStatus = 201;
        } else if (9 == status) {
            orderStatus = 301;
        } else if (2 == status) { //服务已提供
            orderStatus = 401;
        }
        return orderStatus;
    }


    /**
     * 订单插入
     *
     * @param userId
     * @param jzBookOrder
     * @return
     */
    private Order insertOrder(int userId, JzBookOrder jzBookOrder) {
        Order order = orderMapper.selectByOrderSn(jzBookOrder.getBookOrderNo().toString());
        if (null != order) {
            //删除订单
            orderMapper.deleteByPrimaryKey(order.getId());
            //删除订单商品
            orderGoodsMapper.deleteByOrderId(order.getId());
        }
        order = new Order();
        order.setUserId(userId);
        order.setOrderSn(jzBookOrder.getBookOrderNo().toString());
        order.setOrderStatus(setOrderStatus(jzBookOrder.getStatusCode()));
        order.setOrderChannel(4);
        order.setOrderDate(jzBookOrder.getBookTime());
        order.setOrderServiceStatus(jzBookOrder.getStatusCode().shortValue());
        JzShop jzShop = jzShopMapper.selectByShopName(jzBookOrder.getShopName());
        if (null != jzShop) {
            order.setOrderShopId(jzShop.getId());
        }

        order.setConsignee(jzBookOrder.getUserName());
        order.setMobile(jzBookOrder.getPhone());
        if (StringUtils.isNotBlank(jzBookOrder.getPayFee())) {
            order.setOrderPrice(new BigDecimal(jzBookOrder.getPayFee()));
            order.setActualPrice(new BigDecimal(jzBookOrder.getPayFee()));
        }else {
        	 order.setOrderPrice(BigDecimal.ZERO);
             order.setActualPrice(BigDecimal.ZERO);
        }
        order.setPayTime(DateUtil.parseDateTime(jzBookOrder.getCreateTime()));
        DateTime parse = DateUtil.parse(jzBookOrder.getCreateTime());
        order.setCreateTime(parse);
        order.setImportTime(new Date());
        order.setDeleted(true);
        orderMapper.insertSelective(order);
        return order;
    }

    /**
     * 插入客户
     *
     * @param phone
     * @return
     */
    private CustomerClient insertCustomerClient(String phone, String userName,String address) {
        CustomerClient customerClient = customerClientMapper.selectByTel(phone);
        if (null == customerClient) {
            customerClient = new CustomerClient();
            customerClient.setCustomerNo(customerClientMapper.selectCustomerNo());
            customerClient.setTel(phone);
            customerClient.setCustomerAddr(address);
            if (StringUtils.isNotBlank(userName)) {
                customerClient.setCustomerName(userName);
            }
            customerClient.setChannelId(4);
            customerClient.setSource("hema");
            customerClientMapper.insertSelective(customerClient);
        }
        return customerClient;
    }

    /**
     * 新增商品
     *
     * @param order
     * @param jzBookOrder
     */
    private void insertGoods(Order order, JzBookOrder jzBookOrder) {
        Goods goods = goodsMapper.selectByGoodsSn(jzBookOrder.getItemId().toString());
        if (null == goods) {
            goods = new Goods();
            goods.setGoodsSn(jzBookOrder.getItemId().toString());
            goods.setCategoryId(0);
            goods.setName(jzBookOrder.getItemName());
            if (StringUtils.isNotBlank(jzBookOrder.getPayFee())) {
                goods.setCounterPrice(new BigDecimal(jzBookOrder.getPayFee()));
                goods.setRetailPrice(new BigDecimal(jzBookOrder.getPayFee()));
            }
            goods.setDeleted(true);
            goods.setCreateTime(new Date());
            goodsMapper.insertSelective(goods);
        }
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderId(order.getId());
        orderGoods.setGoodsId(goods.getId());
        orderGoods.setGoodsName(jzBookOrder.getItemName());
        orderGoods.setGoodsSn(jzBookOrder.getItemId().toString());
        if (StringUtils.isNotBlank(jzBookOrder.getPayFee())) {
            orderGoods.setPrice(new BigDecimal(jzBookOrder.getPayFee()));
        } else {
            orderGoods.setPrice(BigDecimal.ZERO);
        }

        orderGoods.setAddTime(DateUtil.parseDateTime(jzBookOrder.getCreateTime()));
        orderGoods.setDeleted(true);
        orderGoodsMapper.insertSelective(orderGoods);
    }

}
