package com.winsun.TimingTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.bean.Order;
import com.winsun.bean.OrderHistory;
import com.winsun.bean.SalesList;
import com.winsun.bean.SysUser;
import com.winsun.mapper.*;
import com.winsun.outSideSystem.IntelligenceSendOrder;
import com.winsun.service.ISalesListService;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import com.winsun.utils.XbkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@Configuration
@EnableScheduling
public class OrderTask {
    private static OrderMapper orderMapper;

    @Autowired
    private IntelligenceSendOrder intelligenceSendOrder;

    @Autowired
    private OrderHistoryMapper orderHistoryMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SalesListMapper salesListMapper;

    @Autowired
    private AppMapper appMapper;

    @Autowired
    private ISalesListService salesListService;
    @Autowired
    public OrderTask(OrderMapper orderMapper) {
        OrderTask.orderMapper = orderMapper;
    }

    /**
     * 定时器更新已送货订单
     */
    @Scheduled(cron = "0 0/5 * * * ? ")
    public void updateBeSendOrder() {
        log.info("开始更新已发货超过7天订单");
        int i = orderMapper.updateCompleteOrder();
        log.info("更新已送货订单成功：" + i);
    }

    /**
     * 更新移动卡的状态
     */
    @Scheduled(cron = "0 0/4 * * * ?")
    public void updateMobileCardStatus() {
        log.info("更新预制卡状态开始");
        // 有卡品id，并且未审核中的状态
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("order_status", "审核中");
        wrapper.isNull("kd_order_id");
        List<Order> orders = orderMapper.selectList(wrapper);

        // 循环请求获取数据
        for(Order order : orders) {
            if (StringUtils.isNotBlank(order.getOrderId())) {

                String s = intelligenceSendOrder.queryStatus( null, order.getOrderId());
                if (StringUtils.isNotBlank(s)) {
                    Order update = new Order();
                    update.setId(order.getId());
                    update.setUpdateTime(new Date());

                    JSONObject json = JSONObject.parseObject(s);
                    OrderHistory orderHistory = new OrderHistory();
                    orderHistory.setOrderId(order.getId());
                    orderHistory.setCreateDate(new Date());
                    orderHistory.setStatus("智能平台状态获取:"+json.get("stateName").toString());

                    // 未获取到需要的状态不做更新
                    if ("待配送".equals(json.get("stateName")) || "物流配送中".equals(json.get("stateName"))
                            || "配送成功【待收费】".equals(json.get("stateName")) || "归档".equals(json.get("stateName"))) {
                        orderHistory.setStatus("审核通过,等待配送");
                        orderHistoryMapper.insert(orderHistory);

                        update.setThStatus(json.get("orderStatus").toString());
                        update.setOrderStatus("待配送");
                        update.setMsg(json.get("stateName").toString());
                        orderMapper.updateById(update);

                    } else if (json.get("stateName").equals("待图片审核") || json.get("stateName").equals("作废")) {
                        orderHistory.setStatus(json.getString("orderStatus")+";"+json.getString("stateName"));
                        orderHistoryMapper.insert(orderHistory);
                        update.setThStatus(json.get("stateName").toString());
                        update.setMsg(json.getString("stateName"));
                        update.setOrderStatus("异常单");
                        orderMapper.updateById(update);
                    }
                }
            }
        }
        log.info("更新预制卡状态完成");
    }

    /**
     * 定时器更新智能平台状态
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateStatus() {

        // 获取审核中的订单
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("order_status", "审核中");
        wrapper.isNotNull("kd_order_id");
        wrapper.or();
        wrapper.eq("order_status", "待配送");
        wrapper.isNotNull("kd_order_id");
        List<Order> orders = orderMapper.selectList(wrapper);

        // 循环请求获取数据
        for(Order order : orders) {
            if (StringUtils.isNotBlank(order.getKdOrderId())) {
                String s = intelligenceSendOrder.queryStatus(order.getKdOrderId(), null);
                if (StringUtils.isNotBlank(s)) {
                    Order update = new Order();
                    update.setId(order.getId());
                    update.setUpdateTime(new Date());

                    JSONObject json = JSONObject.parseObject(s);
                    OrderHistory orderHistory = new OrderHistory();
                    orderHistory.setOrderId(order.getId());
                    orderHistory.setCreateDate(new Date());
                    orderHistory.setStatus("智能平台状态获取");

                    // 未获取到需要的状态不做更新
                    if ("归档".equals(json.getString("orderStatus")) || "受理成功【待收费】".equals(json.getString("orderStatus"))
                        || "已收费【待竣工】".equals(json.getString("orderStatus")) || "受理成功".equals(json.getString("orderStatus"))) {
                        orderHistory.setStatus("订单已完成");
                        orderHistoryMapper.insert(orderHistory);

                        update.setThStatus(json.get("orderStatus").toString());
                        update.setOrderStatus("已完成");
                        orderMapper.updateById(update);

                        // 下发短信
                        SendSmsAndMail.sendSms2(order.getContactNumber(),
                                order.getNetNumber(),
                                order.getNetPassword(), "12");
                    }else if("作废".equals(json.get("orderStatus")) || "受理异常".equals(json.get("orderStatus"))){
                        orderHistory.setStatus("订单异常请联系管理员");
                        orderHistoryMapper.insert(orderHistory);

                        update.setThStatus(json.get("orderStatus").toString());
                        update.setOrderStatus("异常单");
                        update.setMsg(json.get("stateName").toString());
                        orderMapper.updateById(update);
                    }
                }
            }
        }
    }

    @Scheduled(cron = "0 0 0 * * ? ")
    //@Scheduled(cron = "0/5 * * * * ? ")
    //@Scheduled(fixedRate=1000*60)
    @PostMapping("/orderTask")
    public void general() throws ParseException {
        log.info("更新小白卡订单");
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("order_status", "待识别");
        List<Order> orders = orderMapper.selectList(wrapper);
        orders.forEach(order -> {
            try {
                Map<String, Object> dataMapping = new HashMap<>();
                JSONObject jsonObject = XbkUtil.orderInfoJT0006(order.getXbOrderId());
                String dataArray = jsonObject.getString("dataArray");
                Map<String,Object> Map = JSON.parseObject(dataArray, HashMap.class);
                Wrapper<Order> wrapper1 = new EntityWrapper();
                wrapper1.eq("xb_order_id",Map.get("orderCode"));
                wrapper1.eq("id",order.getId());
                if(Map.get("orderState").toString().equals("3") || Map.get("orderState").toString().equals("13") ||
                        Map.get("orderState").toString().equals("8") || Map.get("orderState").toString().equals("22") ||
                        Map.get("orderState").toString().equals("21") ){
                    dataMapping.put("order_status", "待处理");
                }
                if(Map.get("orderState").toString().equals("10") || Map.get("orderState").toString().equals("11")){
                    dataMapping.put("order_status", "异常单");
                    dataMapping.put("success_time", new Date());
                }
                orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper1);
                log.info(order.getXbOrderId()+"订单已更新");
            } catch (Exception e) {
                log.error(order.getXbOrderId()+"订单更新失败",e.getMessage());
            }
        });

        Wrapper<Order> wrapper2 = new EntityWrapper();
        wrapper2.eq("order_status", "待活体");
        List<Order> orders1 = orderMapper.selectList(wrapper2);
        orders1.forEach(order -> {
            try {
                JSONObject jsonObject = XbkUtil.orderInfoJT0006(order.getXbOrderId());
                String dataArray = jsonObject.getString("dataArray");
                Map<String,Object> Map = JSON.parseObject(dataArray, HashMap.class);
                Wrapper<Order> wrapper1 = new EntityWrapper();
                wrapper1.eq("xb_order_id",Map.get("orderCode"));
                wrapper1.eq("id",order.getId());
                Map<String, Object> dataMapping = new HashMap<>();
                if(Map.get("orderState").toString().equals("3") || Map.get("orderState").toString().equals("13")){
                    dataMapping.put("order_status", "已完成");
                    // 存销售清单
                    insertCompleteOrder(order);
                }
                if(Map.get("orderState").toString().equals("10") || Map.get("orderState").toString().equals("11")){
                    dataMapping.put("order_status", "异常单");
                }
                dataMapping.put("success_time", new Date());
                orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper1);
                log.info(order.getXbOrderId()+"订单已更新");
            } catch (Exception e) {
                log.error(order.getXbOrderId()+"订单更新失败",e.getMessage());
            }
        });

    }
    // 新用户完成存销售清单
    public void insertCompleteOrder(Order order){
        try{
            SysUser sysUser = sysUserMapper.selectById(order.getHehuorenId());
            Date date = new Date();
            SalesList salesOrder = new SalesList();
            salesOrder.setOrderPhone(order.getBusinessNumber());
            salesOrder.setUserId(order.getHehuorenId());
            salesOrder.setSalesSchool(order.getHehuorenSchool());
            salesOrder.setCreateTime(date);
            salesOrder.setStatus("1");
            salesOrder.setSalesSubst(order.getHehuorenArea());
            salesOrder.setName(order.getHehuorenName());
            salesOrder.setOrderType(order.getUserType());
            salesOrder.setOrderNum(order.getOrderNumber());
            salesOrder.setOldCombo(order.getKapin());
            salesOrder.setDelFlag("0");
            salesOrder.setLockState("否");

            salesOrder.setPreType("");

            salesOrder.setMonthAmount(0D);
            salesOrder.setMonthBonus(0D);
            salesOrder.setNonSendBonus(0D);
            salesOrder.setSendBonus(0D);
            salesOrder.setAllBonus(0D);


            salesOrder.setAccount(sysUser.getAccount());
            log.info("新用户完成存销售清单:"+salesOrder);
            ResponseData<String> stringResponseData = salesListService.addSalesList(salesOrder);
            if(stringResponseData.getState() != null && "error".equals(stringResponseData.getState())){
                appMapper.inserOrderHis(order.getOrderId(), "新用户完成存销售清单:"+stringResponseData.getMsg(), new Date(), "");
            }
            log.info("新用户完成存销售清单:"+order.getOrderId()+":"+stringResponseData);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
