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.Order;
import com.winsun.bean.School;
import com.winsun.bean.StudentLists;
import com.winsun.bean.SysUser;
import com.winsun.mapper.*;
import com.winsun.utils.MyBatisPlusUpdateUtils;
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;

    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;

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


    /**
     * 查询订单详情
     */
    @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();

            if("待活体".equals(order.getOrderStatus()) || "待识别".equals(order.getOrderStatus())){
                general(orderId);
            }
            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(String orderId) {
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("id", orderId);
        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());
            }
        });
    }

    //进入三大权益先查一个表 hhr_check_student_list（这个表临时建的）
    //若hhr_check_student_list表存在 就查订单表
    //订单表若存在直接下一步
    //若不存在就插入订单
    //若hhr_check_student_list表不存在直接下一步
    @RequestMapping(value = "/findStuentByIdCard")
    @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();
    }
}
