package com.winsun.controller;

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.constant.OrderStatus;
import com.winsun.mapper.*;
import com.winsun.outSideSystem.IntelligenceSendOrder;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.PicturesUtil;
import com.winsun.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
  * 单宽进融
  * @author chengfengluo
  * @date 2021-01-26 17:30:39
  */
@RequestMapping("toIntegrate")
@RestController
@Slf4j
public class SingleBroadToIntegrateController {

    @Autowired
    private HhrUserMapper hhrUserMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderViewMapper orderViewMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UniversityInfoMapper universityInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KdPhoneMapper kdPhoneMapper;

    @Autowired
    private OrderHistoryMapper orderHistoryMapper;

    private static String TOINTEGRATE = "TOINTEGRATE";

    @Autowired
    private IntelligenceSendOrder intelligenceSendOrder;

    /**
     * 查询订单信息
     * @param orderSeq
     * @return
     */
    @PostMapping("getOrderSetMeal")
    public ResponseData<Map<String, Object>> getOrderBySeq(@RequestParam("orderSeq") String orderSeq) {
        Wrapper<OrderView> wrapper = new EntityWrapper<>();
        wrapper.eq("orderSeq", orderSeq);
        List<OrderView> orderViews = orderViewMapper.selectList(wrapper);
        if (orderViews != null && orderViews.size() > 0) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("orderSetMeal", orderViews.get(0).getOrderSetMeal());
            return ResponseData.success(resultMap);
        }else{
            return ResponseData.error("未查询到订单信息");
        }
    }

    /**
     * 获取大学宽带信息
     * @param universityId
     * @return
     */
    @PostMapping("getUniversityInfo")
    public ResponseData<Map<String, Object>> getUniversityInfo(@RequestParam("universityId") String universityId) {
        UniversityInfo universityInfo = universityInfoMapper.selectById(universityId);
        Map<String, Object> resultMap = new HashMap<>();
        if (universityInfo != null && StringUtils.isNotBlank(universityInfo.getExpenses())) {
            resultMap.put("expenses",universityInfo.getExpenses());
            resultMap.put("domainName", universityInfo.getUniversityDomainName());
            return ResponseData.success(resultMap);
        }
        return ResponseData.error("未找到当前合伙人大学宽带速率信息");
    }

    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @PostMapping("getCode")
    public ResponseData getCode(@RequestParam(value = "phone") String phone) {
        try{

            // 判断号码是否在优惠清单中，已有新用户订单或者再优惠号码清单中
            Wrapper<KdPhone> kdPhoneWrapper = new EntityWrapper<>();
            kdPhoneWrapper.eq("phone", phone);
            List<KdPhone> kdPhones = kdPhoneMapper.selectList(kdPhoneWrapper);
            Wrapper<Order> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq("user_type", "0");
            orderWrapper.eq("order_status", "已完成");
            orderWrapper.eq("business_number", phone);
            List<Order> orders = orderMapper.selectList(orderWrapper);
            if ((kdPhones != null && kdPhones.size() > 0) || (orders != null && orders.size() > 0)) {
                String random = String.valueOf((int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000));
                redisTemplate.opsForValue().set(SingleBroadToIntegrateController.TOINTEGRATE + phone, random, 30, TimeUnit.MINUTES);
                SendSmsAndMail.sendSms(phone, random, "7");
            }else{
                return ResponseData.error("该号码不在优惠清单中");
            }
        }catch(Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return ResponseData.error("获取验证码失败");
        }
        return ResponseData.success("获取验证码成功");
    }

    /**
     * 校验手机号码
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("checkPhoneAndCode")
    public ResponseData checkPhoneAndCode(@RequestParam("phone") String phone,
                                                               @RequestParam("code") String code) {
        Object o = redisTemplate.opsForValue().get(SingleBroadToIntegrateController.TOINTEGRATE + phone);
        if (o == null) {
            return ResponseData.error("请重新获取验证码");
        }
        if (!code.equals(o)) {
            return ResponseData.error("验证码错误");
        }
        redisTemplate.delete(SingleBroadToIntegrateController.TOINTEGRATE + phone);

        return ResponseData.success("校验成功");
    }

    /**
     * 获取 产品/大学单宽信息
     * @param hehuorenId
     * @return
     */
    @PostMapping("getProductBroadInfo")
    public ResponseData<Product> getProductBroadInfo(String hehuorenId) {

        // 产品名称、学校名称、套餐介绍（product_rf2）
        Map<String, Object> productByUserId = hhrUserMapper.getProductByUserId(hehuorenId);
        if (productByUserId != null && productByUserId.get("bandproduct_id") != null) {
            Product product = productMapper.selectById(productByUserId.get("bandproduct_id").toString());
            if (product == null) {
                return ResponseData.error("学校产品信息错误");
            }
            return ResponseData.success(product);
        }else{
            return ResponseData.error("该合伙人未配置学校产品");
        }
    }

    /**
     * 校验宽带账号，智能平台下单
     * @param request
     * @param toIntegrateOrderParam 下单参数
     * @return
     */
    @PostMapping("sendOrder")
    public ResponseData<Map<String, Object>> sendOrder(HttpServletRequest request,
                                                       @RequestParam("name") String name,
                                                       @RequestParam("netNumber") String netNumber,
                                                       @RequestParam("idCard") String idCard,
                                                       @RequestParam("businessNumber") String businessNumber,
                                                       @RequestParam("contactPhone") String contactPhone,
                                                       @RequestParam("rhTime") String rhTime,
                                                       @RequestParam("hehuorenId") String hehuorenId,
                                                       @RequestParam("imgUrl") String imgUrl) {
        ToIntegrateOrderParam toIntegrateOrderParam = new ToIntegrateOrderParam();
        toIntegrateOrderParam.setName(name);
        toIntegrateOrderParam.setNetNumber(netNumber);
        toIntegrateOrderParam.setIdCard(idCard);
        toIntegrateOrderParam.setBusinessNumber(businessNumber);
        toIntegrateOrderParam.setContactPhone(contactPhone);
        toIntegrateOrderParam.setRhTime(rhTime);
        toIntegrateOrderParam.setHehuorenId(hehuorenId);
        toIntegrateOrderParam.setImgUrl(imgUrl);
        // 正常下单保存到数据库中
        log.info(JSONObject.toJSONString(toIntegrateOrderParam));

        String imgFilePath = "";

        Map<String, Object> resultMap = new HashMap<>();

        // 查询订单类型为（3、5、9、10）的 !异常单
        List<Order> orders = orderMapper.selectRepeatOrder(toIntegrateOrderParam.getIdCard());
        if (orders != null && orders.size() != 0) {
            return ResponseData.error("已有其它订单");
        }

        // 获取合伙人信息
        HhrUser hhrUser = hhrUserMapper.selectById(toIntegrateOrderParam.getHehuorenId());

        String jiltKdy = "0";

        // 获取产品信息
        Product product = null;
        Map<String, Object> productByUserId = hhrUserMapper.getProductByUserId(toIntegrateOrderParam.getHehuorenId());
        if (productByUserId != null && productByUserId.get("bandproduct_id") != null) {
            product = productMapper.selectById(productByUserId.get("bandproduct_id").toString());
            if (product == null) {
                return ResponseData.error("学校产品信息错误");
            }
            if (productByUserId.get("jilt_kdy") != null) {
                jiltKdy = productByUserId.get("jilt_kdy").toString();
            }
        }else{
            return ResponseData.error("该合伙人未配置学校产品");
        }

        // 获取大学宽带信息
        UniversityInfo universityInfo = universityInfoMapper.selectById(product.getUniversityId());
        if (universityInfo == null) {
            return ResponseData.error("大学宽带信息获取失败，请联系督导配置");
        }
        // 判断是否在宽带清单中
        List<Map<String, Object>> maps = orderMapper.selectBroadList(
                toIntegrateOrderParam.getNetNumber() + universityInfo.getUniversityDomainName());
        String dmt = "";
        if (maps == null || maps.size() == 0) {
            return ResponseData.error("宽带号码不在清单中");
        }else{
            if (maps.get(0).get("id") != null) {
                dmt = maps.get(0).get("id").toString();
            }
        }

        // 保存到order_view
        OrderView orderView = new OrderView();
        orderView.setOrderSeq(RandomUtil.RandomNumber(20)); // 订单号码
        orderView.setProductName(product.getProductTitle()); // 产品名称
        orderView.setOrderSetMeal(universityInfo.getExpenses()); // 套餐
        orderView.setOrderUniversityName(universityInfo.getUniversityName()); // 学校
        orderView.setOrderName(toIntegrateOrderParam.getName()); // 姓名
        orderView.setOrderDate(new Date()); // 提交时间
        orderView.setStatus(OrderStatus.PENDINGSUBMISSION.getId()); // 订单状态(待提交)
        orderView.setOrderRegion(universityInfo.getUniversityRegion()); // 区域
        orderView.setIPay("0"); // 支付平台
        orderView.setPayType("1"); // 支付方式
        orderView.setWebOrderAmount("0"); // 产品价格
        orderView.setCustomerId("xyzxyql");  // 接入商
        orderView.setOrderPhone(toIntegrateOrderParam.getContactPhone()); // 联系电话
        orderView.setOrderNumber(toIntegrateOrderParam.getIdCard()); // 身份证号码

        orderView.setOrderCustomerType(universityInfo.getUniversityUserCategory()); // 用户类别

        orderView.setOrderCustomerRemarks(toIntegrateOrderParam.getBusinessNumber());
        orderView.setOrderCustomerAccount(
                toIntegrateOrderParam.getNetNumber() + universityInfo.getUniversityDomainName()); // 多媒体账号

        orderView.setExpenses(universityInfo.getExpenses()); // 套餐
        orderViewMapper.insert(orderView);
        // 获取签名图片地址
        if(StringUtils.isBlank(toIntegrateOrderParam.getImgUrl())){
            return ResponseData.error("签名失败！");
        }
        if(StringUtils.isNotBlank(toIntegrateOrderParam.getImgUrl())){
            imgFilePath  = PicturesUtil.uploadPictures(toIntegrateOrderParam.getImgUrl(), orderView.getOrderSeq(),"signImg");
        }
        // 保存到hhr_order
        Order order = new Order();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        uuid = uuid.substring(1, 12);
        order.setId(uuid);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); // 设置日期格式
        order.setOrderNumber("YRYM" + df.format(new Date()) + uuid);
        order.setOrderStatus("未下单"); // 订单状态
        order.setHehuorenId(toIntegrateOrderParam.getHehuorenId()); // 合伙人id
        order.setCustomerName(toIntegrateOrderParam.getName()); // 客户姓名
        order.setBusinessNumber(toIntegrateOrderParam.getBusinessNumber()); // 客户手机号码
        order.setIdCard(toIntegrateOrderParam.getIdCard()); // 客户身份证
        order.setCreateTime(new Date()); // 订单创建时间
        order.setKapin("单宽进融"); // 卡品
        order.setSignImg(imgFilePath); // 签名地址
        order.setDmtNumber(dmt); // 宽带接入号
        order.setUserType("10"); // 订单类型-单宽进融
        order.setKdOrderId(orderView.getOrderSeq()); // 宽带id
        order.setContactNumber(toIntegrateOrderParam.getContactPhone()); // 联系方式
        try {
            if (StringUtils.isNotBlank(toIntegrateOrderParam.getRhTime())) {
                order.setRhTime(df.parse(toIntegrateOrderParam.getRhTime())); // 融合时间
            }
        }catch(Exception e) {
            log.info(e.getMessage());
        }
        // 获取合伙人信息（账号、姓名、区域、学校）
        Map<String, Object> selectHehuorenInfo = hhrUserMapper.selectHehuorenInfo(toIntegrateOrderParam.getHehuorenId());
        if (!selectHehuorenInfo.isEmpty()) {
            if (selectHehuorenInfo.get("phone") != null) {
                order.setHehuorenPhone(selectHehuorenInfo.get("phone").toString());
            }
            if (selectHehuorenInfo.get("name") != null) {
                order.setHehuorenName(selectHehuorenInfo.get("name").toString());
            }
            if (selectHehuorenInfo.get("sub_name") != null) {
                order.setHehuorenArea(selectHehuorenInfo.get("sub_name").toString());
            }
            if (selectHehuorenInfo.get("school_name") != null) {
                order.setHehuorenSchool(selectHehuorenInfo.get("school_name").toString());
            }
        }

        // 获取督导信息（学校揽装工号、督导姓名）
        List<Map<String, Object>> selectSupervisor = hhrUserMapper.selectSupervisor(toIntegrateOrderParam.getHehuorenId());
        if (selectSupervisor != null && selectSupervisor.size() > 0) {
            if (selectSupervisor.get(0).get("ddname") != null) {
                order.setSupervisorName(selectSupervisor.get(0).get("ddname").toString());
            }
            if (selectSupervisor.get(0).get("lzgh") != null) {
                order.setLzgh(selectSupervisor.get(0).get("lzgh").toString());
            }
        }
        orderMapper.insert(order);

        // 无融合时间直接下单
        if (toIntegrateOrderParam.getRhTime() == null || StringUtils.isBlank(toIntegrateOrderParam.getRhTime())) {
            Wrapper<Order> wrapper = new EntityWrapper<>();
            wrapper.eq("id", uuid);
            new Thread(() -> {
                try {
                    intelligenceSendOrder.integrateSendOrder(order, true);
                }catch(Exception e) {
                    e.printStackTrace();
                    log.info("融合下单失败！");
                }
            }).start();
        }

        // 插入历史表
        OrderHistory orderHistory = new OrderHistory();
        orderHistory.setOrderId(uuid);
        orderHistory.setCreateDate(new Date());
        orderHistory.setOperator(toIntegrateOrderParam.getName());
        orderHistory.setStatus("甩单单宽进融下单成功");
        if ("1".equals(jiltKdy)) {
            orderHistory.setStatus("不甩单单宽进融下单成功");
        }
        orderHistoryMapper.insert(orderHistory);

        resultMap.put("kdId", orderView.getOrderSeq());
        resultMap.put("orderSetMeal", orderView.getOrderSetMeal());

        return ResponseData.success(resultMap, "下单成功");
    }

}
