package com.winsun.controller;

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.MyBatisPlusUpdateUtils;
import com.winsun.utils.PicturesUtil;
import com.winsun.utils.RandomUtil;
import com.winsun.utils.SaveAuthCodeUtil;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author xiangli
 * @Date 2020/4/21
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/codesManager") //
public class codeManagerController {
    @Autowired
    private RegularMapper regularMapper;
    @Autowired
    private KdPhoneMapper kdPhoneMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderViewMapper orderViewMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private XshInventoryMapper xshInventoryMapper;
    @Autowired
    private AuthCodeMapper authCodeMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UniversityInfoMapper universityInfoMapper;

    @Autowired
    private StudentCardMapper studentCardMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SaveAuthCodeUtil saveAuthCodeUtil;

    private static String PATH1 = "StudentCard1";
    private static String PATH2 = "StudentCard2";
    private static String PATH3 = "StudentCard3";
    private static String PATH4 = "StudentCard4";

    /**
     * 解锁用户
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "unlock", method = RequestMethod.POST)
    public ResponseData<String> unlock(String userId) {

        SysUser sysUser = sysUserMapper.selectById(userId);
        if (sysUser != null) {
            redisTemplate.delete("SYS_LOGIN_ERROR" + sysUser.getAccount());
            return ResponseData.success("成功");
        }else{
            return ResponseData.success("解锁失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "sendCodes", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> checkStudent(String phone) {

        Map<String, Object> map = new HashMap<>();
        if (phone.length() != 11) {
            map.put("code",2);
            return ResponseData.error("手机号码有误，请重新输入");
        }
        try {
            Wrapper<KdPhone> wrapper1 = new EntityWrapper<>();
            wrapper1.setSqlSelect("id,phone,tcName");
            wrapper1.eq("phone",phone);
            List<KdPhone> list = kdPhoneMapper.selectList(wrapper1);
            Wrapper<Order> wrapper2 = new EntityWrapper<>();
            wrapper2.eq("user_type","0");
            wrapper2.eq("order_status","已完成");
            wrapper2.eq("business_number",phone);
            List<Order> list1 = orderMapper.selectList(wrapper2);
            if(list.size()>0 || list1.size()>0){
//                生成6位随机数
                int veCode = (int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000);
//                MessageUtil.sent(packageUpgrade.getAccNbr(),"4","您获取的验证码为："+s+",半小时内有效。");
//                新框架短信验证码保存在Redis，但由于业务需要使用原来方式，存在数据库里
                redisTemplate.opsForValue().set(phone, String.valueOf(veCode), 30, TimeUnit.MINUTES);
                saveAuthCodeUtil.saveAuthCode(phone, String.valueOf(veCode)); // 临时保存数据库
                SendSmsAndMail.sendSms(phone,veCode + "",null,"7");
                log.info("验证码:" + veCode);
                map.put("code",1);
            }else{
                map.put("code",0);
            }
        } catch (Exception e) {
            log.error("获取验证码异常:", e);
            map.put("code",2);
        }
        return ResponseData.success(map);
    }


    @ResponseBody
    @RequestMapping(value = "sendCode", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> sendCode(String phone) {
        Map<String, Object> map = new HashMap<>();
        if (phone.length() != 11) {
            map.put("code",2);
            return ResponseData.error("手机号码有误，请重新输入");
        }

        try {
//          生成6位随机数
            int veCode = (int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000);
            redisTemplate.opsForValue().set(phone, String.valueOf(veCode), 30, TimeUnit.MINUTES);
            saveAuthCodeUtil.saveAuthCode(phone, String.valueOf(veCode)); // 临时保存数据库
            SendSmsAndMail.sendSms(phone,veCode + "",null,"7");
            log.info("验证码:" + veCode);
            map.put("code",1);
        } catch (Exception e) {
            log.error("获取验证码异常:", e);
            map.put("code",2);
        }
        return ResponseData.success(map);
    }
    @ResponseBody
    @RequestMapping(value = "checkCodes", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> checkCodes(String phone, String codes) {
        if(!StringUtils.isNotEmpty(phone)){
            return ResponseData.error("手机号不正确！");
        }
        if(!StringUtils.isNotEmpty(codes)){
            return ResponseData.error("验证码不能为空！");
        }
        String ver = null;
        try {
            ver = redisTemplate.opsForValue().get(phone).toString();
        } catch (NullPointerException n) {
            return ResponseData.error("验证码已失效，请发送验证码！");
        }
        if(ver.equals(codes)){
            Map<String,Object> map =  new HashMap<>();
            Wrapper<KdPhone> kdPhoneWrapper = new EntityWrapper<>();
            kdPhoneWrapper.setSqlSelect("id,phone,tcName");
            kdPhoneWrapper.eq("phone",phone);
            List<KdPhone> list = kdPhoneMapper.selectList(kdPhoneWrapper);
            if(list.size()>0){
                KdPhone kdPhone = list.get(0);
                map.put("tcName",kdPhone.getTcName());
            }
            return ResponseData.success(map);
        }
        return ResponseData.error( "验证码错误" );
    }

    /**
     * @param regularId 正则id
     * @return
     */
    @RequestMapping(value = "getRegularById", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData<Object> getRegularById(String regularId) {
        Wrapper<Regular> wrapper = new EntityWrapper<>();
        wrapper.eq("regular_id",regularId);
        wrapper.eq("is_show","1");
        List<Regular> regulars = regularMapper.selectList(wrapper);
//        Regular regulars = regularMapper.selectById(regularId);
        if(regulars !=null && regulars.size()>0){
            return ResponseData.success(regulars.get(0), "查询成功！");
        }
        return ResponseData.success();
    }
    //检查学生证号是否在学生清单内
    @ResponseBody
    @RequestMapping(value="queryStuNo", method = RequestMethod.POST)
    public ResponseData<Object> queryStuNo(String stuNumber){
        if(StringUtils.isEmpty(stuNumber)){
            return ResponseData.error("学生号不能为空");
        }
        XshInventory xshQd = xshInventoryMapper.selectById(stuNumber);
        if(xshQd == null){
            return ResponseData.error("学生号不在清单内！");
        }
        return ResponseData.success();
    }

    /**
     * 业务预受理表参数
     * @param request
     * @param response
     * @param callback
     * @return
     * @throws IOException
     */
    @PostMapping("findReportMap")
    public ResponseData<Map<String,Object>> findReportMap(HttpServletRequest request, HttpServletResponse response, String callback) throws IOException {
        String prices = null;
        String byStr = null;
        String mealStr = null;
        String month = null;
        String expenses = "";
        String product_price = ""; // 资费
        String identifying = ""; // 提速包：
        String identifying_price = ""; // 提速包资费
        String identifyingStr = ""; // 提速包
        String tyMeal = "";
        String university_domain_name = ""; // 后缀

        boolean speed_up = true;
        boolean product_price_CB = false;
        boolean new_clothes_CB = false;
        boolean setMealCB = false;

        String isFromRh = request.getParameter("isFromRh"); // 融合
        String productId = request.getParameter("productId"); // 产品id
        String setMealIndex = request.getParameter("setMealIndex");//产品下标
        String sl = request.getParameter("sl"); // 宽带提速速率
        // 校验参数
        if (StringUtils.isBlank(isFromRh) || StringUtils.isBlank(productId)) {
            return ResponseData.error("签名页参数缺失");
        }

        if (StringUtils.isBlank(productId)) {
            return ResponseData.error("请重新选择产品");
        }
        Product product = productMapper.selectById(productId);

        if (product == null) {
            return ResponseData.error("未找到产品信息，请重写进入下单");
        }
        UniversityInfo universityInfo = universityInfoMapper.selectById(product.getUniversityId());

        if (universityInfo == null) {
            return ResponseData.error("未找到大学宽带信息，请重写进入下单");
        }

        String[] rateArry = product.getProductRate().split(",");    // 年月（包年,包月）
        String[] mealArry = product.getProductMeal().split(",");  // 套餐 （4M，8M，20M等）
        String[] priceArry = product.getProductPrice().split(",");    // 金额（300,30）
        if("true".equals(isFromRh)) {
            rateArry = product.getProductRhRate().split(","); // 年月（包年,包月）
            priceArry = product.getProductPrice().split(","); // 金额（300,30）
        }
        Integer index = 0;
        if(StringUtils.isNotBlank(setMealIndex)){
            index = Integer.parseInt(setMealIndex);
        }

        byStr = rateArry[index];
        mealStr = mealArry[index];
        prices = priceArry[index];
        if(byStr.equals("包年")){
            month = "12";
        }else{
            month = "1";
        }

        new_clothes_CB = true;
        tyMeal = "预付费校园";
        setMealCB = true;


        // 融合/提速  提速包：
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        if(StringUtils.isNotBlank(universityInfo.getIdentifying())){
            identifying = universityInfo.getIdentifying().toString();
        }
        if(StringUtils.isNotBlank(universityInfo.getExpenses())){
            expenses = universityInfo.getExpenses();
        }
        if(StringUtils.isNotBlank(expenses)){
            expenses = expenses.replace("M","");
        }

        university_domain_name = universityInfo.getUniversityDomainName();
        if(StringUtils.isNotBlank(university_domain_name)){
            university_domain_name = university_domain_name.replace("@","");
        }

        product_price_CB = true;
        if(identifying.contains("免费")){
            identifying_price = "0";
            identifyingStr = identifying;
        }else{
            Matcher m = p.matcher(identifying);
            identifying_price = m.replaceAll("").trim();
            if(StringUtils.isNotBlank(identifying)){
                identifyingStr = identifying.substring(0,8);
            }
        }

        if(StringUtils.isNotBlank(sl)){
            new_clothes_CB = false;
        }

        //  单宽
        if(StringUtils.isBlank(isFromRh) && StringUtils.isBlank(sl)){
            identifying_price = "";
            identifyingStr = "";
            tyMeal = "";
            setMealCB = false;
            product_price_CB = false;
            speed_up = false;
            expenses = "";
            university_domain_name = "";
        }
//      返回的参数
        Map<String, Object> mapData = new HashMap<>();
        mapData.put("channel_number",""); // 渠道工号
        mapData.put("student_name",""); // 姓名
        mapData.put("student_number",""); // 学号
        mapData.put("contact_number",""); // 联系方式
        mapData.put("id_card",""); // 身份证号码
        mapData.put("universityName",product.getProductUniversity()); //学校：
        mapData.put("department",""); // 系
        mapData.put("setClass",""); // 班级
        mapData.put("dormitory",""); // 宿舍
        mapData.put("setMealCB",setMealCB); // 我要办理天翼@_@套餐 checkbox
        mapData.put("tyMeal",tyMeal); // 我要办理天翼@_@套餐
        mapData.put("setMealIndex",setMealIndex); // 套餐下标
        mapData.put("upgradeCB",false); // 我要办理老用户套餐升级： checkbox
        mapData.put("upgrade",""); // 我要办理老用户套餐升级：
        mapData.put("original_package",""); // 原套餐：
        mapData.put("new_package",""); // 转新套餐：
        mapData.put("new_clothes_CB",new_clothes_CB); // 新装 checkbox
        mapData.put("change_CB",false); // 变更 checkbox
        mapData.put("product_price",prices); // 资费
        mapData.put("month",month); // 包年/包月 12/1
        mapData.put("product_other",""); // （其他）
        mapData.put("speed_up",speed_up); // 我要办理宽带提速： checkbox
        mapData.put("product_price_CB",product_price_CB); // 在原基础宽带资费外每月低消/加价 checkbox
        mapData.put("product_price_up",identifying_price); // 在原基础宽带资费外每月低消/加价____元
        mapData.put("expenses",expenses); // 宽带提速 ______M
        mapData.put("university_domain_name",university_domain_name); // 账号为______@______后缀
        mapData.put("phone_CB",false); // 只为手机号 checkbox
        mapData.put("phone_TD",""); // 只为手机号____退订
        mapData.put("phone_TD_price",""); // 退订每月____元
        mapData.put("phone_product_meal",""); // 提速至____M
        mapData.put("acceleration_package_CB",false); // 办理加速包 checkbox
        mapData.put("business_number",""); // 办理加速包 手机号为：
        mapData.put("identifying",identifying); // 办理加速包:
        mapData.put("identifying_price",identifying_price); // 办理__元
        mapData.put("identifyingStr",identifyingStr); // 办理加速包
        mapData.put("university_package_number",""); // 揽装工号：
        mapData.put("remarks",""); // 其他备注：

        return ResponseData.success(mapData);
    }

    @PostMapping("selectOrder")
    public ResponseData<Object> selectOrder(HttpServletRequest request, HttpServletResponse response){
        try{
            Map<String, Object> mapData = new HashMap<>();
            String idCard = request.getParameter("idCard"); // 身份证号
            String accountNumber = request.getParameter("accountNumber");// 多媒体账号
            String userName = request.getParameter("userName");// 客户名字
            String orderCustomerAccount = request.getParameter("orderCustomerAccount");// 多媒体账号 去除后缀
            String partner = request.getParameter("partner");// 合伙人ID
            if("12518".equals(partner)){ // 特定学校：华软教师办理通道
                Wrapper<Teacher> wrapperT = new EntityWrapper<>();
                wrapperT.eq(StringUtils.isNotBlank(orderCustomerAccount),"student_number",orderCustomerAccount);
                List<Teacher> teacherList = teacherMapper.selectList(wrapperT);
                // 请输入t+工号
                // 姓名填写不正确
                if(teacherList!=null && teacherList.size()>0){
                    if(!teacherList.get(0).getStuName().equals(userName)){
                        mapData.put("code", 3);
                        return ResponseData.error(mapData,"姓名填写不正确");
                    }
                }else {
                    mapData.put("code", 4);
                    return ResponseData.error(mapData,"教师工号不存在，请输入t+工号");
                }
            }

            // 判断身份证号是否在清单中
            Wrapper<Order> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq(StringUtils.isNotBlank(idCard), "id_card", idCard);
            orderWrapper.in("user_type","3,5,9,10");
            orderWrapper.ne("order_status","异常单");
            orderWrapper.ne("order_status","已完成");
            List<Order> order = orderMapper.selectList(orderWrapper);
            if(order.size()>0){
                Wrapper<OrderView> wrapper = new EntityWrapper<>();
                wrapper.eq(StringUtils.isNotBlank(order.get(0).getKdOrderId()), "orderSeq", order.get(0).getKdOrderId());
                List<OrderView> orderViews = orderViewMapper.selectList(wrapper);

                if ("未支付".equals(order.get(0).getOrderStatus())) {
                    mapData.put("orderSeq", orderViews.get(0).getOrderSeq());
                    mapData.put("userType", order.get(0).getUserType());
                    mapData.put("kapin", order.get(0).getKapin());
                    mapData.put("code", 2);
                    return ResponseData.error(mapData,"你已存在未支付的订单，请前往支付页面，若已支付，请等待支付状态更新");
                }else{
                    mapData.put("orderSeq", orderViews.get(0).getOrderSeq());
                    mapData.put("userType", order.get(0).getUserType());
                    mapData.put("kapin", order.get(0).getKapin());
                    mapData.put("code", 0); //不可重复下单"你已存在正在处理的订单，请勿重复下单"
                    return ResponseData.error(mapData,"你已存在正在处理的订单，请勿重复下单");
                }
            }

            // 判断是否在宽带清单中
            List<Map<String, Object>> accountNumberList = orderMapper.checkOldKdUser(accountNumber);
            //  查询多媒体账号在甲方提供清单中是否存在
            if(!accountNumberList.isEmpty() && accountNumberList.size() > 0) {  //已存在纪录
                mapData.put("code", 1);
                return ResponseData.error(mapData,"该账号已存在");
            } else {
                //  查询多媒体账号在订单表是否存在
                List<Map<String, Object>> maps = orderMapper.checkOldhhrOrder(accountNumber);
                if(!maps.isEmpty() && maps.size()>0){
                    mapData.put("code", 1);
                    return ResponseData.error(mapData,"该账号已存在");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return ResponseData.error("连接超时，请重试");
        }
        return ResponseData.success();
    }

    /**
     * 学生证证件照上传
     * @param idCard
     * @param userName
     * @param orderPhone
     * @param linkPhone
     * @param file1
     * @param file2
     * @param file3
     * @param file4
     * @return
     */
    @RequestMapping(value = "uploadCard", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData<String> uploadStuCard(String userName, String orderPhone, String linkPhone,
                                              String idCard,String file1,String file2,String file3,String file4) {

        if (StringUtils.isBlank(userName)) {
            return ResponseData.error("请填写姓名");
        }

        if (StringUtils.isBlank(orderPhone)) {
            return ResponseData.error("请填写订单号码");
        }

        if (StringUtils.isBlank(linkPhone)) {
            return ResponseData.error("请填写联系号码");
        }

        if (StringUtils.isBlank(idCard)) {
            return ResponseData.error("请填写身份证号码");
        }

        Wrapper<StudentCard> wrapper = new EntityWrapper<>();
        wrapper.eq("order_phone", orderPhone);
        wrapper.eq("id_card", idCard);
        StudentCard student = new StudentCard();
        student.setUserName(userName);
        student.setOrderPhone(orderPhone);
        student.setLinkPhone(linkPhone);
        student.setIdCard(idCard);
        student.setUploadDate(new Date());
        if(StringUtils.isNotBlank(file1)){
            String file01 = PicturesUtil.uploadPictures(file1, orderPhone,PATH1);
            student.setStudentCardUrl(file01);
        }
        if(StringUtils.isNotBlank(file2)){
            String file02 = PicturesUtil.uploadPictures(file2,orderPhone,PATH2);
            student.setOtherImgUrl1(file02);
        }
        if(StringUtils.isNotBlank(file3)){
            String file03 = PicturesUtil.uploadPictures(file3, orderPhone,PATH3);
            student.setOtherImgUrl2(file03);
        }
        if(StringUtils.isNotBlank(file4)){
            String file04 = PicturesUtil.uploadPictures(file4, orderPhone,PATH4);
            student.setOtherImgUrl3(file04);
        }
        Integer integer1 = studentCardMapper.update(student,wrapper);
        if(integer1==1){
            return ResponseData.success("更新成功！");
        }else{
            student.setIsFirstUpload(1);
            student.setFirstUploadDate(new Date());
            studentCardMapper.insert(student);
            return ResponseData.success("上传成功！");
        }
    }
}
