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.bean.*;
import com.winsun.mapper.*;
import com.winsun.outSideSystem.IntelligenceSendOrder;
import com.winsun.outSideSystem.IntelligenceSendOrders;
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.RestController;

import java.text.ParseException;
import java.util.*;

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

    @Autowired
    private IntelligenceSendOrder intelligenceSendOrder;
    @Autowired
    private IntelligenceSendOrders intelligenceSendOrders;

    @Autowired
    private OrderHistoryMapper orderHistoryMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SalesListMapper salesListMapper;

    @Autowired
    private OrderViewMapper orderViewMapper;

    @Autowired
    private AppMapper appMapper;

    @Autowired
    private ISalesListService salesListService;

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

    @Autowired
    private RhPhoneMapper rhPhoneMapper;

    private static Set<String> schoolSet = new HashSet<>();

    {
        schoolSet.add("星海音乐学院");
        schoolSet.add("广州美术学院");
    }

    /**
     * 定时器更新已送货订单
     */
    @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() throws Exception {
        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 body = intelligenceSendOrders.queryStatus(order.getOrderId());
                if (StringUtils.isNotBlank(body)) {
                    Order update = new Order();
                    update.setId(order.getId());
                    update.setUpdateTime(new Date());

                    JSONObject json = JSONObject.parseObject(body);
                    Map<String, Object> map = JSONObject.parseObject(json.getString("data"));
                    List<Object> list = (List<Object>) map.get("q");
                    Map<String, Object> map2 = (Map<String, Object>) list.get(0);
                    Map<String, Object> orderStatus = (Map<String, Object>) map2.get("订单当前状态");

                    OrderHistory orderHistory = new OrderHistory();
                    orderHistory.setOrderId(order.getId());
                    orderHistory.setCreateDate(new Date());
                    orderHistory.setStatus("智能平台状态获取:" + orderStatus.get("订单状态名称").toString());

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

                        update.setThStatus(orderStatus.get("订单状态名称").toString());
                        update.setOrderStatus("待配送");
                        update.setMsg(orderStatus.get("订单状态名称").toString());
                        orderMapper.updateById(update);

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

    //@Scheduled(cron = "0 0/4 * * * ?")
    public void updateMobileCardStatus2() {
        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() throws Exception {
        log.info("更新宽带和预制卡状态开始");
        // 获取审核中的订单
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("order_status", "审核中");
        wrapper.isNotNull("kd_order_id");
        wrapper.or();
        wrapper.eq("order_status", "待配送");
        wrapper.isNotNull("order_id");
        List<Order> orders = orderMapper.selectList(wrapper);


        // 循环请求获取数据
        for (Order order : orders) {
            if (StringUtils.isNotBlank(order.getOrderId())) {
                String boday = intelligenceSendOrders.queryStatus(order.getOrderId());
                if (StringUtils.isNotBlank(boday)) {
                    Order update = new Order();
                    update.setId(order.getId());
                    update.setUpdateTime(new Date());

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


                    JSONObject json = JSONObject.parseObject(boday);
                    Map<String, Object> map = JSONObject.parseObject(json.getString("data"));
                    List<Object> list = (List<Object>) map.get("q");
                    Map<String, Object> map2 = (Map<String, Object>) list.get(0);
                    Map<String, Object> orderStatus = (Map<String, Object>) map2.get("订单当前状态");

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

                        update.setThStatus(orderStatus.get("订单状态名称").toString());
                        update.setOrderStatus("已完成");
                        orderMapper.updateById(update);

                        //查询该订单的学校名称
                        String schoolName = orderViewMapper.selectByKdOrderId(order.getKdOrderId());

                        if (schoolSet.contains(schoolName)) {
                            order.setNetNumber(order.getNetNumber().split("@")[0]);
                        }

                        // 下发短信
                        SendSmsAndMail.sendSms(order.getContactNumber(),
                                order.getNetNumber(),
                                order.getNetPassword(), "12");
                    } else if ("作废".equals(orderStatus.get("订单状态名称").toString()) || "下单异常".equals(orderStatus.get("订单状态名称").toString())) {
                        orderHistory.setStatus("订单异常请联系管理员");
                        orderHistoryMapper.insert(orderHistory);
                        update.setThStatus(orderStatus.get("订单状态名称").toString());
                        update.setOrderStatus("异常单");
                        update.setMsg(orderStatus.get("订单状态名称").toString());
                        orderMapper.updateById(update);
                    }else if ("待下单人修改".equals(orderStatus.get("订单状态名称").toString())){
                        update.setMsg(orderStatus.get("订单状态名称").toString());
                        update.setThStatus(orderStatus.get("订单状态名称").toString());
                        update.setOrderStatus("异常单");
                        if (orderStatus.get("订单当前状态|状态备注").toString().contains("停机")||orderStatus.get("订单当前状态|状态备注").toString().contains("欠费")){
                            update.setMsg("停机/名下欠费");
                        }else if (orderStatus.get("订单当前状态|状态备注").toString().contains("黑名单")){
                            update.setMsg("身份证黑名单");
                        }
                        orderMapper.updateById(update);
                    }
                }
            }
        }
        log.info("更新宽带和预制卡状态结束");
    }


    /**
     * 定时器更新智能平台状态
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void updateStatus3() throws Exception {
        log.info("开始更新宽带状态为异常单但中台状态为带下单人修改的订单");
        // 获取审核中的订单
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("order_status", "异常单");
        wrapper.isNotNull("kd_order_id");
        wrapper.eq("th_status","待下单人修改");

        List<Order> orders = orderMapper.selectList(wrapper);


        // 循环请求获取数据
        for (Order order : orders) {
            Date createTime = order.getCreateTime();
            int i = Integer.parseInt(String.valueOf((new Date().getTime() - createTime.getTime()) / (1000 * 60 * 60 * 24)));
            if (StringUtils.isNotBlank(order.getOrderId()) && i <= 7) {
                String boday = intelligenceSendOrders.queryStatus(order.getOrderId());
                if (StringUtils.isNotBlank(boday)) {
                    Order update = new Order();
                    update.setId(order.getId());
                    update.setUpdateTime(new Date());

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


                    JSONObject json = JSONObject.parseObject(boday);
                    Map<String, Object> map = JSONObject.parseObject(json.getString("data"));
                    List<Object> list = (List<Object>) map.get("q");
                    Map<String, Object> map2 = (Map<String, Object>) list.get(0);
                    Map<String, Object> orderStatus = (Map<String, Object>) map2.get("订单当前状态");

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

                        update.setThStatus(orderStatus.get("订单状态名称").toString());
                        update.setOrderStatus("已完成");
                        orderMapper.updateById(update);

                        //查询该订单的学校名称
                        String schoolName = orderViewMapper.selectByKdOrderId(order.getKdOrderId());

                        if (schoolSet.contains(schoolName)) {
                            order.setNetNumber(order.getNetNumber().split("@")[0]);
                        }

                        // 下发短信
                        SendSmsAndMail.sendSms(order.getContactNumber(),
                                order.getNetNumber(),
                                order.getNetPassword(), "12");
                    } else if ("作废".equals(orderStatus.get("订单状态名称").toString()) || "下单异常".equals(orderStatus.get("订单状态名称").toString())) {
                        orderHistory.setStatus("订单异常请联系管理员");
                        orderHistoryMapper.insert(orderHistory);
                        update.setThStatus(orderStatus.get("订单状态名称").toString());
                        update.setOrderStatus("异常单");
                        update.setMsg(orderStatus.get("订单状态名称").toString());
                        orderMapper.updateById(update);
                    }else if (!"待下单人修改".equals(orderStatus.get("订单状态名称").toString())){
                        update.setMsg(null);
                        update.setThStatus(orderStatus.get("订单状态名称").toString());
                        update.setOrderStatus("审核中");
                        orderMapper.updateById(update);
                    }
                }
            }
        }
        log.info("结束更新宽带状态为待处理且中台状态为带下单人修改的订单");
    }

    //@Scheduled(cron = "0 0/5 * * * ?")
    public void updateStatus2() throws Exception {

        // 获取审核中的订单
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("order_status", "审核中");
        wrapper.isNotNull("order_id");
        wrapper.or();
        wrapper.eq("order_status", "待配送");
        wrapper.isNotNull("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);

                        //查询该订单的学校名称
                        String schoolName = orderViewMapper.selectByKdOrderId(order.getKdOrderId());

                        if (schoolSet.contains(schoolName)){
                            order.setNetNumber(order.getNetNumber().split("@")[0]);
                        }

                        // 下发短信
                        SendSmsAndMail.sendSms(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 * * * ? ")
    //@Scheduled(cron = "0/5 * * * * ? ")
    //@Scheduled(fixedRate=1000*60)
    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 ("1".equals(order.getIsDelivery())) {
                        dataMapping.put("order_status", "待活体");
                    }
                    dataMapping.put("update_time", new Date());
                    appMapper.inserOrderHis(order.getId(), "上传证件受理成功，等待督导处理:" + Map.get("orderState").toString(), new Date(), "定时器查询");
                }
                if (Map.get("orderState").toString().equals("10") || Map.get("orderState").toString().equals("11")) {
                    dataMapping.put("order_status", "异常单");
                    appMapper.inserOrderHis(order.getId(), "上传证件受理失败，已设为异常单" + Map.get("orderState").toString(), 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", "已完成");
                    dataMapping.put("update_time", new Date());
                    dataMapping.put("success_time", new Date());
                    // 小白卡订单完成时，办理号码存入融合清单供办理融合业务使用
                    insertRhPhone(order.getBusinessNumber());
                    // 存销售清单
                    insertCompleteOrder(order);
                    appMapper.inserOrderHis(order.getId(), "订单已完成，省合伙人返回状态码：" + Map.get("orderState").toString(), new Date(), "定时器查询");
                }
                if (Map.get("orderState").toString().equals("10") || Map.get("orderState").toString().equals("11")) {
                    dataMapping.put("order_status", "异常单");
                    appMapper.inserOrderHis(order.getId(), "订单受理失败，已设为异常单，省合伙人返回状态码：" + Map.get("orderState").toString(), 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();
        }
    }

    // 新用户完成存融合清单
    public void insertRhPhone(String data) {
        Wrapper<RhPhone> wrapper = new EntityWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(data), "phone", data);
        List<RhPhone> list = rhPhoneMapper.selectList(wrapper);
        if (list.size() == 0) {
            RhPhone rhPhone = new RhPhone();
            rhPhone.setPhone(data);
            try {
                log.info("新用户完成存融合清单:" + rhPhone);
                rhPhoneMapper.insert(rhPhone);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
