package com.winsun.controller;

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.smsUtils.SendSmsAndMail;
import com.winsun.utils.RandomUtil;
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.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 首页同用接口
 *
 * @Author: chancy
 * @Date: 2020/3/9 10:16
 */
@Slf4j
@RestController
@RequestMapping("/choose") //
public class ChooseController {

    private static AppMapper appMapper;
    private static StudentListMapper stuListMapper;
    private static PackageMapper packageMapper;

    private static SchoolMapper schoolMapper;

    private static OrderMapper orderMapper;

    private static SysUserMapper userMapper;

    private static OrderHistoryMapper orderHistoryMapper;

    private static RhPhoneMapper rhPhoneMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    public ChooseController(AppMapper appMapper, PackageMapper packageMapper,SchoolMapper schoolMapper, OrderMapper orderMapper
            , SysUserMapper userMapper,StudentListMapper stuListMapper, OrderHistoryMapper orderHistoryMapper,RhPhoneMapper rhPhoneMapper) {
        ChooseController.appMapper = appMapper;
        ChooseController.packageMapper = packageMapper;
        ChooseController.schoolMapper = schoolMapper;
        ChooseController.orderMapper = orderMapper;
        ChooseController.userMapper = userMapper;
        ChooseController.stuListMapper = stuListMapper;
        ChooseController.orderHistoryMapper = orderHistoryMapper;
        ChooseController.rhPhoneMapper = rhPhoneMapper;
    }


    /**
     * 查询订单详情
     */
    @RequestMapping(value = "selectOrderInfo", method = RequestMethod.POST)
    public ResponseData<Order> selectOrderInfo(@RequestParam(value = "orderId",required = false) String orderId,@RequestParam(value = "orderSeq",required = false) String orderSeq) {
        try{
            Wrapper<Order> orderWrapper = new EntityWrapper<>();
            if(StringUtils.isBlank(orderSeq)&&StringUtils.isBlank(orderId)){
                return ResponseData.error("参数缺少");
            }
            orderWrapper.eq(StringUtils.isNotBlank(orderId), "id", orderId);
            orderWrapper.eq(StringUtils.isNotBlank(orderSeq), "kd_order_id", orderSeq);
            Order order = orderMapper.selectList(orderWrapper).get(0);
            orderId = order.getOrderId();

            log.info("" + "待识别".equals(order.getOrderStatus()));

            if("待活体".equals(order.getOrderStatus()) || "待识别".equals(order.getOrderStatus())){
                general(order);
            }
            order.setIdCard("");
            order.setGiftAccount("");
            order.setGiftCypher("");
            order.setNetPassword("");
            if(StringUtils.isNotBlank(order.getNetNumber())){
                String[] split = order.getNetNumber().split("@");
                order.setNetNumber(order.getNetNumber().substring(0,1)+"****"+split[1]);
            }
            if(StringUtils.isNotBlank(order.getContactNumber())&&order.getContactNumber().length()==11){
                order.setContactNumber(order.getContactNumber().substring(0,3)+"****"+order.getContactNumber().substring(7,11));
            }
            return ResponseData.success(order);
        }catch (Exception e){
            e.getMessage();
            return ResponseData.error("");
        }

    }

    /**
     * 查询用户详情
     */
    @RequestMapping(value = "selectUserInfo", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> selectUserInfo(@RequestParam("partner") String partner) {
        SysUser sysUser = userMapper.selectById(partner);
        if(sysUser==null){
            return ResponseData.error("没有查到用户信息！");
        }
        String schoolId = appMapper.selectSchoolId(partner);
        String schoolName = appMapper.selectSchoolById(schoolId);
        Map<String, Object> map = new HashMap<>();
        map.put("schoolName", schoolName);
        map.put("substName", sysUser.getSubstName());
        map.put("name", sysUser.getName());
        map.put("id", sysUser.getId());
        map.put("account", sysUser.getAccount());
        map.put("phone", sysUser.getPhone());
        return ResponseData.success(map);
    }

    /**
     * 查询订单历史状态
     */
    @RequestMapping(value = "selectOrderHis", method = RequestMethod.POST)
    public ResponseData<List<Map<String, Object>>> selectOrderHis(@RequestParam(value = "orderId",required = false) String orderId,@RequestParam(value = "orderSeq",required = false) String orderSeq) {
        try{
            if(StringUtils.isNotBlank(orderSeq)){
                Wrapper<Order> wrapper2 = new EntityWrapper<>();
                wrapper2.eq(StringUtils.isNotBlank(orderSeq),"kd_order",orderSeq);
                List<Order> order = orderMapper.selectList(wrapper2);
                if(order.size()>0){
                    orderId = order.get(0).getOrderId();
                }
            }
            List<Map<String, Object>> list = appMapper.selectOrderHis(orderId);
            return ResponseData.success(list);
        }catch (Exception e){
            e.getMessage();
            return ResponseData.error("");
        }
    }

    /**
     * 查询学校信息
     */
    @RequestMapping(value = "selectSchoolInfo", method = RequestMethod.POST)
    public ResponseData<School> selectSchoolInfo(@RequestParam("partner") String partner) {
        String schoolId = appMapper.selectSchoolId(partner);
        School school = schoolMapper.selectById(schoolId);
        return ResponseData.success(school);
    }

    public static void general(Order order) {
        try{
            Map<String, Object> dataMapping = new HashMap<>();
            JSONObject jsonObject = XbkUtil.orderInfoJT0006(order.getXbOrderId());
            log.info("订单信息：" + JSONObject.toJSONString(order));
            log.info("小白卡获取状态:" + jsonObject);
            if (jsonObject.get("code") != null && jsonObject.get("code").toString().equals("0")) {
                String dataArray = jsonObject.getString("dataArray");
                Map<String,Object> map = JSON.parseObject(dataArray, HashMap.class);
                if (order.getOrderStatus().equals("待识别")) {
                    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") ){
                        Order updateOrder = new Order();
                        updateOrder.setOrderStatus("待处理");
                        if (order.getTjType().equals("0")) {
                            updateOrder.setOrderStatus("待活体");
                        }
                        OrderHistory orderHistory = new OrderHistory();
                        orderHistory.setOrderId(order.getId());
                        orderHistory.setCreateDate(new Date());
                        if (order.getTjType().equals("0")) {
                            orderHistory.setStatus("已上传三证等待活体");
                        } else {
                            orderHistory.setStatus("已上传三证等待配送后进行活体");
                        }
                        orderHistory.setOperator("省公司小白卡系统");
                        orderHistoryMapper.insert(orderHistory);
                        updateOrder.setId(order.getId());
                        orderMapper.updateById(updateOrder);
                        order.setOrderStatus("待活体");
                    }else if(map.get("orderState").toString().equals("1")) {
                        order.setOrderStatus("待支付");
                    }
                }
                if (order.getOrderStatus().equals("待活体")) {
                    if (map.get("orderState").toString().equals("13") || map.get("orderState").toString().equals("3")) {
                        System.out.println(SendSmsAndMail.sendSms(order.getContactNumber(), "", "3"));
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("order_status", "已完成");

                        try {
                            Order updateOrder = new Order();
                            updateOrder.setId(order.getId());
                            updateOrder.setOrderStatus("已完成");
                            orderMapper.updateById(updateOrder);
                            // 小白卡订单完成时，办理号码存入融合清单供办理融合业务使用
                            insertRhPhone(order.getBusinessNumber());
                            OrderHistory orderHistory = new OrderHistory();
                            orderHistory.setOrderId(order.getId());
                            orderHistory.setCreateDate(new Date());
                            orderHistory.setStatus("已活体认证");
                            orderHistory.setOperator("省公司小白卡系统");
                            orderHistoryMapper.insert(orderHistory);
                            order.setOrderStatus("已活体");
                        } catch (Exception e) {
                            log.error("更新待识别出错");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(order.getXbOrderId()+"订单更新失败",e.getMessage());
        }
    }

    //进入三大权益先查一个表 hhr_check_student_list（这个表临时建的）
    //若hhr_check_student_list表存在 就查订单表
    //订单表若存在直接下一步
    //若不存在就插入订单
    //若hhr_check_student_list表不存在直接下一步
    @RequestMapping(value = "/findStuentByIdCard",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ResponseData<Object> findStuentByIdCard(String idcard, String hhrId) {

        Wrapper<StudentLists> stuListWrapper = new EntityWrapper<>();
        if(idcard.length()==11){
            stuListWrapper.eq("phone",idcard);
        }else{
            stuListWrapper.eq("id_card",idcard);
        }
        List<StudentLists> lists = stuListMapper.selectList(stuListWrapper);
        log.info("------查询hhr_check_student_list有否能找到数据-----");
        //若hhr_check_student_list表存在 就查订单表
        if(lists.size()>0){
            StudentLists studentList = lists.get(0);
            log.info("------查询订单表有否能找到数据-----");
            Wrapper<Order> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq("user_type",'7');
            if(idcard.length()==11){
                //user_type=7 and (`contact_number` = ? or `id_card` = ?)
                orderWrapper.eq("contact_number",idcard);
            }else{
                orderWrapper.eq("id_card",idcard);
            }
            List<Order> orderList = orderMapper.selectList(orderWrapper);
            //若订单表不存在就插入订单
            if(orderList.size()==0){
                log.info("------订单表示查找到数据，插入一条新订单-------");
                //插入订单
                Order order = new Order();
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                uuid = uuid.substring(1, 12);
                order.setId(uuid);
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
                String orderNumber = "YRYM" + df.format(new Date()) + (int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000);
                order.setOrderNumber(orderNumber);
                order.setOrderStatus("待处理");
                order.setHehuorenId(hhrId);

                order.setCustomerName(studentList.getName());
                order.setContactNumber(studentList.getPhone());
                order.setIdCard(studentList.getIdCard());

                order.setKapin("三大权益");
                order.setUserType("7");
                SysUser sysUser = userMapper.selectById(hhrId);
                String schoolId = appMapper.selectSchoolId(hhrId);
                School school = schoolMapper.selectById(schoolId);
                if(sysUser != null && school != null) {
                    order.setHehuorenArea(sysUser.getSubstName());
                    order.setHehuorenName(sysUser.getName());
                    order.setHehuorenPhone(sysUser.getPhone());
                    order.setHehuorenSchool( school.getSchoolName());
                    order.setLzgh(school.getLzgh());
                }
                List<String> userId1 = appMapper.selectsupervisorBySchool(schoolId);
                SysUser user = userMapper.selectById(userId1.get(0));
                if(user != null) {
                    order.setSupervisorName(user.getName());
                }
                order.setCreateTime(new Date());

                try {
                    orderMapper.insert(order);
                }catch (Exception e) {
                    log.error("新用户提交异常:", e);
                    return ResponseData.error("新用户提交打败");
                }
                log.info("------order表新插入数据成功！！订单号："+orderNumber);
            }else{
                log.info("------订单表数据："+orderList.get(0));
            }
        }
        return ResponseData.success();
    }

    // 新用户完成存融合清单
    public static 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();
            }
        }
    }
}
