package com.winsun.controller;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.bean.Package;
import com.winsun.bean.*;
import com.winsun.constant.OrderStatus;
import com.winsun.constant.UserType;
import com.winsun.mapper.*;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.IDCardUtil;
import com.winsun.utils.PicturesUtil;
import com.winsun.utils.ProduceIdUtil;
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.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 套餐新装
 *
 * @Author: chancy
 * @Date: 2020/2/25 11:14
 */
@Slf4j
@RestController
@RequestMapping("/packageUpgrade") //
public class PackageUpgradeController extends BaseController {
    private static AppMapper appMapper;

    private static QueryBysMapper queryBysMapper;

    private static PackageMapper packageMapper;

    private static YangChengTongrMapper yangChengTongrMapper;

    private static OrderMapper orderMapper;

    private static SysUserMapper userMapper;

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

    @Autowired
    public PackageUpgradeController(AppMapper appMapper, PackageMapper packageMapper, QueryBysMapper queryBysMapper,
                                    YangChengTongrMapper yangChengTongrMapper, OrderMapper orderMapper
            , SysUserMapper userMapper) {
        PackageUpgradeController.appMapper = appMapper;
        PackageUpgradeController.packageMapper = packageMapper;
        PackageUpgradeController.yangChengTongrMapper = yangChengTongrMapper;
        PackageUpgradeController.orderMapper = orderMapper;
        PackageUpgradeController.userMapper = userMapper;
        PackageUpgradeController.queryBysMapper = queryBysMapper;
    }

    /**
     * 验证码
     *
     * @param selectOrder
     * @return
     */
    @RequestMapping(value = "sendVerificationCode", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> sendVerificationCode(@RequestParam("selectOrder") String selectOrder, @RequestParam(value = "servId", required = false) String servId) {
        if (StringUtils.isNotBlank(servId)) {
            PackageUpgrade packageUpgrade = appMapper.selectById(servId);
            String s = String.valueOf((int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000));
            log.info("验证码:" + s);
            //MessageUtil.sent(packageUpgrade.getAccNbr(),"4","您获取的验证码为："+s+",半小时内有效。");
            redisTemplate.opsForValue().set(servId, s, 30, TimeUnit.MINUTES);
            return ResponseData.success(new HashMap<>(), "已发送验证码到手机：" + packageUpgrade.getAccNbr().substring(0, 3) + "****" + packageUpgrade.getAccNbr().substring(7, 11) + "验证码：" + s);
        }

        Wrapper<PackageUpgrade> wrapper = new EntityWrapper();
        wrapper.setSqlSelect("serv_id", "cust_name", "user_type", "school_name", "acc_nbr", "acc_nbr2", "cdma_disc_desc", "is_bltc1"
                , "is_bltc2", "is_bltc3", "speed_kd", "wxcl");
        if (selectOrder.contains("@")) {
            wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr2", selectOrder);
        }
        Wrapper<QueryBys> queryBysWrapper = new EntityWrapper<>();
        Map<String, Object> objMap = new HashMap();
        if (selectOrder.length() == 18) {
            if (!IDCardUtil.IDCardValidate(selectOrder)) {
                return ResponseData.error("您的身份证输入有误，请重新输入！");
            }
            wrapper.like("social_id", selectOrder.substring(5, 18), SqlLike.LEFT);
            queryBysWrapper.eq(StringUtils.isNotBlank(selectOrder), "id_card", selectOrder);
        }
        if (selectOrder.length() == 11) {
            wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr", selectOrder);
            queryBysWrapper.eq(StringUtils.isNotBlank(selectOrder), "phone", selectOrder);
        }

        //查找毕业生清单表
        List<Map<String, Object>> queryBys = queryBysMapper.selectMaps(queryBysWrapper);
        if (queryBys.size() > 0) {
            objMap.put("isBys", true);
            return ResponseData.success(objMap);
        }else{
            objMap.put("isBys", false);
            //查找存量表是否存在
            List<Map<String, Object>> packageUpgrade = appMapper.selectMaps(wrapper);
            List<Map<String,Object>> packageYCSLL = appMapper.selectYCSLL(selectOrder);
            String nbr = null;
            if (packageUpgrade.size() > 0) {
                nbr = packageUpgrade.get(0).get("acc_nbr").toString();
                //是存量 跳转到套餐升级
                objMap.put("isStock", true);
                for (Map<String, Object> map : packageUpgrade) {
                    map.put("acc_nbr", map.get("acc_nbr").toString().substring(0, 3) + "****" + map.get("acc_nbr").toString().substring(7, 11));
                }
                objMap.put("count", packageUpgrade.size());
                objMap.put("data", packageUpgrade);
                objMap.put("isYcsll",false);
            }else if (packageYCSLL.size() > 0){
                nbr = packageYCSLL.get(0).get("acc_nbr").toString();
                for (Map<String, Object> map : packageYCSLL) {
                    map.put("acc_nbr", map.get("acc_nbr").toString().substring(0, 3) + "****" + map.get("acc_nbr").toString().substring(7, 11));
                }
                objMap.put("small", false);
                objMap.put("isBys", false);
                objMap.put("isStock", false);
                objMap.put("count", packageYCSLL.size());
                objMap.put("isYcsll",true);
                objMap.put("data", packageYCSLL);
            }else {
                //不是存量  跳转到三大权益
                objMap.put("isStock", false);
                return ResponseData.error(objMap,"当前查询条件未查出套餐升级数据，如有疑问请联系客服！");
            }
            String s = String.valueOf((int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000));
            log.info("验证码:" + s);
            SendSmsAndMail.sendSms(selectOrder,s,"7");
            redisTemplate.opsForValue().set(selectOrder, s, 30, TimeUnit.MINUTES);
            return ResponseData.success(objMap, "已发送验证码到手机：" + nbr.substring(0, 3) + "****" + nbr.substring(7, 11));
        }
    }

    /**
     * 查询套餐升级信息 2021-04-15 新需求修改
     */
    @RequestMapping(value = "selectPackageNew",method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseData<Map<String,Object>> selectPackageNew(@RequestParam("acc_nbr")String acc_nbr, @RequestParam(value = "servId", required = false) String servId){
        try {
            Map<String, Object> map = new HashMap<>();

            //查找毕业生清单
            Wrapper<QueryBys> queryBysWrapper = new EntityWrapper<>();
            queryBysWrapper.eq(StringUtils.isNotBlank(acc_nbr), "phone", acc_nbr);
            List<Map<String, Object>> queryBys = queryBysMapper.selectMaps(queryBysWrapper);
            if(queryBys != null && queryBys.size()>0){
                map.put("isBys", true);
                return ResponseData.success(map);
            }
            log.info("存量升级查询号码："+acc_nbr);
            //查找存量升级清单
            Wrapper<PackageUpgrade> wrapper = new EntityWrapper();
            wrapper.setSqlSelect("serv_id", "acc_nbr", "cdma_disc_desc", "is_bltc1", "is_bltc2", "is_bltc3", "wxcl");
            if (StringUtils.isNotBlank(servId)) {
                wrapper.eq(StringUtils.isNotBlank(servId), "serv_id", servId);
            } else {
                wrapper.eq(StringUtils.isNotBlank(acc_nbr), "acc_nbr", acc_nbr);
            }
            wrapper.isNotNull("wxcl");
            List<Map<String, Object>> packageUpgrade = appMapper.selectMaps(wrapper);
            if (packageUpgrade.size() > 0) {
                log.info("存量升级查询结果："+packageUpgrade.get(0).toString());
                map.put("isBys", false);
                map.put("isStock", true);
                map.put("isYcsll",false);
                Wrapper<Package> wrapper1 = new EntityWrapper();
                Wrapper<Package> wrapper2 = new EntityWrapper();
                if (packageUpgrade.get(0).get("cdma_disc_desc").equals("(预付费)天翼不限量99元套餐201802")) {
                    String is_bltc1 = packageUpgrade.get(0).get("is_bltc1").toString();
                    String is_bltc2 = packageUpgrade.get(0).get("is_bltc2").toString();
                    String is_bltc3 = packageUpgrade.get(0).get("is_bltc3").toString();
                    if (is_bltc1.equals("是") && is_bltc2.equals("否") && is_bltc3.equals("否")) {
                        packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-49元畅享");
                    } else if (is_bltc1.equals("否") && is_bltc2.equals("是") && is_bltc3.equals("是")) {
                        packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-29元畅享");
                    } else if (is_bltc1.equals("否") && is_bltc2.equals("是") && is_bltc3.equals("否")) {
                        packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-39元畅享");
                    }
                }
                wrapper1.eq("package_name", packageUpgrade.get(0).get("cdma_disc_desc"));
                List<Package> packages1 = packageMapper.selectList(wrapper1);
                wrapper2.eq("package_name", packageUpgrade.get(0).get("wxcl"));
                List<Package> packages2 = packageMapper.selectList(wrapper2);
                if (packages2.size() == 0) {
                    return ResponseData.error("当前查询条件未查出套餐升级数据，如有疑问请联系客服！");
                }
                log.info("新套餐："+acc_nbr+":"+packages2.get(0).toString());
                map = packageUpgrade.get(0);
                map.put("acc_nbr", map.get("acc_nbr").toString().substring(0, 3) + "****" + map.get("acc_nbr").toString().substring(7, 11));

                if (packages1.size() == 0) {
                    map.put("oldPackage", null);
                } else {
                    map.put("oldPackage", packages1.get(0));
                    log.info("旧套餐："+acc_nbr+":"+packages1.get(0).toString());
                }
                map.put("newPackage", packages2.get(0));

                String s = String.valueOf((int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000));
                log.info("验证码:" + s);
                SendSmsAndMail.sendSms(acc_nbr,s,"7");
                redisTemplate.opsForValue().set(acc_nbr, s, 30, TimeUnit.MINUTES);

                return ResponseData.success(map, "已发送验证码到手机：" + acc_nbr.substring(0, 3) + "****" + acc_nbr.substring(7, 11));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseData.error("当前号码未查出套餐升级数据，如有疑问请联系客服！");
    }

    /**
     *  套餐升级下单 2021-04-15 新需求修改
     * @param customerName
     * @param contactNumber
     * @param authCode
     * @param partner
     * @param businessNumber
     * @param idCard
     * @param oldPackage
     * @param newPackage
     * @param signUrl
     * @return
     */
    @RequestMapping(value = "oldUserUpadeNew", method = RequestMethod.POST)
    public ResponseData<String> oldUserUpadeNew(@RequestParam("customerName") String customerName,
                                                @RequestParam("contactNumber") String contactNumber,
                                                @RequestParam("authCode") String authCode,
                                                @RequestParam("partner") String partner,
                                                @RequestParam("businessNumber") String businessNumber,
                                                @RequestParam("idCard") String idCard,
                                                @RequestParam("oldPackage") String oldPackage,
                                                @RequestParam("newPackage") String newPackage,
                                                @RequestParam("newPackage_id") String newPackage_id,
                                                @RequestParam("signUrl") String signUrl,
                                                @RequestParam(value = "sell",required = false) String sell) {
        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        // 短信校验
        Object o = redisTemplate.opsForValue().get(businessNumber);

        if (o == null) {
            return ResponseData.error("请重新发送短信验证码");
        }

        if(!authCode.equals(o.toString())) {
            return ResponseData.error("短信验证码错误！");
        }
        SysUser sysUser = userMapper.selectById(partner);
        if (sysUser == null) {
            return ResponseData.error("当前二维码已失效，如有疑问请联系客服！");
        }
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(businessNumber),"business_number",businessNumber);
        wrapper.eq(StringUtils.isNotBlank(newPackage),"kapin",newPackage);
        wrapper.eq("user_type", UserType.OLDCUSTOMER.getId());
        wrapper.ne("order_status", "异常单");
        List<Order> orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("套餐升级订单已存在，请不要重复申请！");
        }
        Order order = new Order();
        String uuid = UUID.randomUUID().toString();
        String id = uuid.split("-")[0] + uuid.split("-")[1];
        order.setId(id);
        order.setIdCard(idCard);
        order.setKapin(newPackage);
        order.setOrderStatus(OrderStatus.PENDINGACCEPTANCE.getName());
        order.setHehuorenId(partner);
        //合伙人字段
        List<Map<String,Object>> partnerInfo  = userMapper.findPartnerById(partner);
        if(!partnerInfo.isEmpty()) {
            order.setHehuorenArea(partnerInfo.get(0).get("area").toString());
            order.setHehuorenName(partnerInfo.get(0).get("name").toString()+sell);
            order.setHehuorenSchool(partnerInfo.get(0).get("school").toString());
            order.setHehuorenPhone(partnerInfo.get(0).get("account").toString());
        }
        order.setPackageId(newPackage_id);
        order.setCustomerName(customerName);
        order.setBusinessNumber(businessNumber);
        order.setContactNumber(contactNumber);
        Date date = new Date();
        order.setCreateTime(date);
        order.setNowPackage(oldPackage);
        order.setBusinessPackage(newPackage);
        order.setUserId(businessNumber);
        order.setUserType(UserType.OLDCUSTOMER.getId());
        order.setOrderNumber("YRYM" + ProduceIdUtil.getId());
        String path = PicturesUtil.uploadPictures(signUrl, order.getId(),"signImg");
        order.setSignImg(path);
        String schoolId = appMapper.selectSchoolId(partner);
        List<String> dudao = appMapper.selectsupervisorBySchool(schoolId);
        if (dudao != null || dudao.size() != 0) {
            SysUser user = userMapper.selectById(dudao.get(0));
            order.setSupervisorName(user.getName());
        }
        Integer insert = orderMapper.insert(order);
        appMapper.inserOrderHis(id, "存量升级成功", date, "用户："+customerName);
        if (insert == 1) {
            return ResponseData.success(id,"存量升级成功");
        }
        return ResponseData.error("升级失败！");
    }
    /**
     * 查询套餐升级信息 旧
     *
     * @param selectOrder 查询的手机号、身份证、宽带账号
     * @param verificationCode 验证码
     * @return
     */
    @RequestMapping(value = "selectPackage", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> selectPackage(@RequestParam("selectOrder") String selectOrder, @RequestParam("verificationCode") String verificationCode, @RequestParam(value = "servId", required = false) String servId) {
        String ver = null;
        Wrapper<PackageUpgrade> wrapper = new EntityWrapper();
        wrapper.setSqlSelect("serv_id", "cust_name", "user_type", "school_name", "acc_nbr", "acc_nbr2", "cdma_disc_desc", "is_bltc1"
                , "is_bltc2", "is_bltc3", "speed_kd", "wxcl");
        if (StringUtils.isNotBlank(servId)) {
            wrapper.eq(StringUtils.isNotBlank(servId), "serv_id", servId);
            try {
                ver = redisTemplate.opsForValue().get(selectOrder).toString();
            } catch (NullPointerException n) {
                return ResponseData.error("验证码已失效，请重新获取！");
            }
        } else {
            if (selectOrder.length() == 11) {
                wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr", selectOrder);
            }
            if (selectOrder.length() == 18) {
                wrapper.eq(StringUtils.isNotBlank(selectOrder), "social_id", selectOrder);
            }
            try {
                ver = redisTemplate.opsForValue().get(selectOrder).toString();
            } catch (NullPointerException n) {
                return ResponseData.error("验证码已失效，请重新获取！");
            }
        }

        if (ver.equals(verificationCode)) {
            List<Map<String, Object>> packageUpgrade = appMapper.selectMaps(wrapper);
            if (packageUpgrade.size() > 0) {
                Wrapper<Package> wrapper1 = new EntityWrapper();
                Wrapper<Package> wrapper2 = new EntityWrapper();
                if (packageUpgrade.get(0).get("cdma_disc_desc").equals("(预付费)天翼不限量99元套餐201802")) {
                    String is_bltc1 = packageUpgrade.get(0).get("is_bltc1").toString();
                    String is_bltc2 = packageUpgrade.get(0).get("is_bltc2").toString();
                    String is_bltc3 = packageUpgrade.get(0).get("is_bltc3").toString();
                    if (is_bltc1.equals("是") && is_bltc2.equals("否") && is_bltc3.equals("否")) {
                        packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-49元畅享");
                    } else if (is_bltc1.equals("否") && is_bltc2.equals("是") && is_bltc3.equals("是")) {
                        packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-29元畅享");
                    } else if (is_bltc1.equals("否") && is_bltc2.equals("是") && is_bltc3.equals("否")) {
                        packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-39元畅享");
                    }
                }
                wrapper1.eq("name", packageUpgrade.get(0).get("cdma_disc_desc"));
                List<Package> packages1 = packageMapper.selectList(wrapper1);
                wrapper2.eq("package_name ", packageUpgrade.get(0).get("wxcl"));
                List<Package> packages2 = packageMapper.selectList(wrapper2);
                if (packages2.size() == 0) {
                    return ResponseData.error("您没有升级套餐");
                }
                Map<String, Object> map = packageUpgrade.get(0);
                map.put("acc_nbr", map.get("acc_nbr").toString().substring(0, 3) + "****" + map.get("acc_nbr").toString().substring(7, 11));
                if (map.containsKey("acc_nbr2")) {
                    String[] split = map.get("acc_nbr2").toString().split("@");
                    map.put("acc_nbr", map.get("acc_nbr2").toString().substring(0, 4) + "*****@" + split[1]);
                }
                if (packages1.size() == 0) {
                    map.put("oldPackage", null);
                } else {
                    map.put("oldPackage", packages1.get(0));
                }
                map.put("newPackage", packages2.get(0));
                return ResponseData.success(map);
            }

        }
        return ResponseData.error("验证码有误");
    }

    /**
     * 查询套餐升级信息
     *
     * @param selectOrder      查询的手机号、身份证、宽带账号
     * @param verificationCode 验证码
     * @return
     */
    @RequestMapping(value = "selectPackageUpgrade", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> selectPackageUpgrade(@RequestParam("selectOrder") String selectOrder,
                                                                  @RequestParam("verificationCode") String verificationCode,
                                                                  @RequestParam(value = "servId", required = false) String servId) {
        String ver = null;
        Wrapper<PackageUpgrade> wrapper = new EntityWrapper();
        wrapper.setSqlSelect("serv_id", "cust_name", "user_type", "school_name", "acc_nbr", "acc_nbr2", "cdma_disc_desc", "is_bltc1"
                , "is_bltc2", "is_bltc3", "speed_kd", "wxcl");
        if (StringUtils.isNotBlank(servId)) {
            wrapper.eq(StringUtils.isNotBlank(servId), "serv_id", servId);
            try {
                ver = redisTemplate.opsForValue().get(selectOrder).toString();
            } catch (NullPointerException n) {
                return ResponseData.error("验证码已失效，请重新登入！");
            }
        } else {
            if (selectOrder.contains("@")) {
                wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr2", selectOrder);
            }
            if (selectOrder.length() == 11) {
                wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr", selectOrder);
            }
            if (selectOrder.length() == 18) {
                wrapper.eq(StringUtils.isNotBlank(selectOrder), "social_id", selectOrder);
            }
            try {
                ver = redisTemplate.opsForValue().get(selectOrder).toString();
            } catch (NullPointerException n) {
                return ResponseData.error("验证码已失效，请重新登入！");
            }
        }
        if (ver.equals(verificationCode)) {
            Wrapper<Package> wrapper1 = new EntityWrapper();
            Wrapper<Package> wrapper2 = new EntityWrapper();
            List<Map<String, Object>> packageUpgrade = appMapper.selectMaps(wrapper);
            if (packageUpgrade.get(0).get("cdma_disc_desc").equals("(预付费)天翼不限量99元套餐201802")) {
                String is_bltc1 = packageUpgrade.get(0).get("is_bltc1").toString();
                String is_bltc2 = packageUpgrade.get(0).get("is_bltc2").toString();
                String is_bltc3 = packageUpgrade.get(0).get("is_bltc3").toString();
                if (is_bltc1.equals("是") && is_bltc2.equals("否") && is_bltc3.equals("否")) {
                    packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-49元畅享");
                } else if (is_bltc1.equals("否") && is_bltc2.equals("是") && is_bltc3.equals("是")) {
                    packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-29元畅享");
                } else if (is_bltc1.equals("否") && is_bltc2.equals("是") && is_bltc3.equals("否")) {
                    packageUpgrade.get(0).put("cdma_disc_desc", "(预付费)天翼不限量99元套餐201802-39元畅享");
                }
            }
            wrapper1.eq("name", packageUpgrade.get(0).get("cdma_disc_desc"));
            List<Package> packages1 = packageMapper.selectList(wrapper1);
            wrapper2.eq("package_name ", packageUpgrade.get(0).get("wxcl"));
            List<Package> packages2 = packageMapper.selectList(wrapper2);
            Map<String, Object> map = packageUpgrade.get(0);
            if (packages1.size() == 0) {
                map.put("oldPackage", null);
            } else {
                map.put("oldPackage", packages1.get(0).getPackageName());
            }
            map.put("newPackage", packages2.get(0).getPackageName());
            map.put("newPackageId", packages2.get(0).getId());
            if (map.containsKey("acc_nbr2")) {
                String[] split = map.get("acc_nbr2").toString().split("@");
                map.put("acc_nbr", map.get("acc_nbr2").toString().substring(0, 4) + "*****@" + split[1]);
            }
            return ResponseData.success(map);
        }
        return ResponseData.error("验证码有误");
    }

    /**
     * 套餐升级
     *
     * @param servId
     * @param contactNumber   联系号码
     * @param businessNumber  办理号码
     * @param cardId          套餐ID
     * @param customerName    客户姓名
     * @param userId          老用户Id
     * @param nowPackage      现有套餐
     * @param partner         合伙人ID
     * @param businessPackage 办理套餐
     * @param mark            羊城通是否办理(空为不办理，不为空就办理)
     * @param addRess         地址（办理羊城通才使用，正常订单为空）
     * @param userSchool      学校 （办理羊城通才使用，正常订单为空）
     * @return
     */
    @RequestMapping(value = "oldUserUpade", method = RequestMethod.POST)
    public ResponseData<String> oldUserUpade(@RequestParam("contactNumber") String contactNumber
            , @RequestParam("businessNumber") String businessNumber, @RequestParam("cardId") String cardId
            , @RequestParam("customerName") String customerName, @RequestParam("userId") String userId
            , @RequestParam("nowPackage") String nowPackage, @RequestParam("partner") String partner
            , @RequestParam("businessPackage") String businessPackage, @RequestParam(value = "servId") String servId
            , @RequestParam(value = "mark", required = false) String mark, @RequestParam(value = "addRess", required = false) String addRess
            , @RequestParam(value = "userSchool", required = false) String userSchool
            , @RequestParam(value = "imgUrl", required = false) String imgUrl) {
        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.ne("order_status", "已完成").and().ne("order_status", "异常单");
        wrapper.eq("user_id", userId);
        wrapper.eq("user_type", UserType.OLDCUSTOMER.getId());
        List<Order> orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("套餐升级订单已存在，请不要重复申请！");
        }
        PackageUpgrade packageUpgrade = appMapper.selectById(servId);
        SysUser sysUser = userMapper.selectById(partner);
        if (sysUser == null) {
            return ResponseData.error("当前二维码已失效，如有疑问请联系客服！");
        }
        Order order = new Order();
        String uuid = UUID.randomUUID().toString();
        String id = uuid.split("-")[0] + uuid.split("-")[1];
        order.setId(id);
        order.setIdCard(packageUpgrade.getSocialId());
        order.setKapin(businessPackage);
        order.setOrderStatus(OrderStatus.PENDINGACCEPTANCE.getName());
        order.setHehuorenId(partner);
        order.setPackageId(cardId);
        order.setCustomerName(customerName);
        order.setBusinessNumber(businessNumber);
        order.setContactNumber(contactNumber);
        Date date = new Date();
        order.setCreateTime(date);
        order.setNowPackage(nowPackage);
        order.setBusinessPackage(businessPackage);
        order.setUserId(userId);
        order.setUserType(UserType.OLDCUSTOMER.getId());
        order.setOrderNumber("YRYM" + ProduceIdUtil.getId());
        order.setHehuorenArea(sysUser.getSubstName());
        order.setHehuorenName(sysUser.getName());
        String path = PicturesUtil.uploadPictures(imgUrl, order.getId(),"signImg");
        order.setSignImg(path);
        String schoolId = appMapper.selectSchoolId(partner);
        List<String> dudao = appMapper.selectsupervisorBySchool(schoolId);
        if (dudao == null || dudao.size() == 0) {
            return ResponseData.error("当前学校未配置督导！");
        }
        SysUser user = userMapper.selectById(dudao.get(0));
        order.setSupervisorName(user.getName());
        String schoolName = appMapper.selectSchoolById(schoolId);
        order.setHehuorenSchool(schoolName);
        order.setHehuorenPhone(sysUser.getPhone());
        Integer insert = orderMapper.insert(order);
        appMapper.inserOrderHis(id, "下单成功", date, customerName);
        // MessageUtil.sent(contactNumber,"4","");
        if (StringUtils.isNotBlank(mark)) {
            String uuid1 = UUID.randomUUID().toString();
            String id1 = uuid1.split("-")[0] + uuid1.split("-")[1];
            String s1 = String.valueOf((int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 1000));
            order.setId(id1);
            order.setOrderNumber("YRYM" + ProduceIdUtil.getId());
            order.setUserType(UserType.YCTK.getId());
            order.setAddress(addRess);
            order.setBusinessPackage("天翼羊城通手机卡业务");
            order.setUserSchool(userSchool);
            order.setOrderStatus(OrderStatus.ACCEPTANCESUCCESSFUL.getName());
            order.setSuccessTime(new Date());
            insert += orderMapper.insert(order);
            YangChengTong yangChengTong = new YangChengTong();
            yangChengTong.setSchool(schoolName);
            yangChengTong.setContactAddress(addRess);
            yangChengTong.setContactPhone(contactNumber);
            yangChengTong.setCustomerPhone(businessNumber);
            yangChengTong.setCustomerName(customerName);
            insert += yangChengTongrMapper.insert(yangChengTong);
            appMapper.inserOrderHis(id1, "下单成功", date, customerName);
            return ResponseData.success(id + ":" + id1, "下单成功！");
        }
        if (insert == 1) {
            return ResponseData.success(id);
        }
        return ResponseData.error("升级失败！");
    }
    /**
     * 查询套餐升级信息
     *
     * @param selectOrder      查询的手机号、身份证、宽带账号
     * @param verificationCode 验证码
     * @return
     */
    @RequestMapping(value = "checkoutAuthCodeYcsll", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> checkoutAuthCodeYcsll(@RequestParam("id")String id,@RequestParam("selectOrder") String selectOrder, @RequestParam("verificationCode") String verificationCode) {
        String ver = null;
        try {
            ver = redisTemplate.opsForValue().get(selectOrder).toString();
        } catch (NullPointerException n) {
            return ResponseData.error("验证码已失效，请重新获取！");
        }
        if(ver.equals(verificationCode)){
            try{
                insertYcsll(id,selectOrder);
            }catch(Exception e){
                e.printStackTrace();
                return ResponseData.error("提交失败，请重试！");
            }
            return ResponseData.success();
        }
        return null;
    }
    /**
     * 插入预存送流量完成数据
     * */
    public void insertYcsll(String partner, String acc_nbr){
        Order order = new Order();
        List<Map<String,Object>> list = appMapper.selectYCSLL(acc_nbr);
        //合伙人字段
        List<Map<String,Object>> partnerInfo  = userMapper.findPartnerById(partner);

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        uuid = uuid.substring(1, 12);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String orderNumber = "YRYM" + df.format(new Date()) + uuid;
        order.setId(uuid);
        order.setOrderNumber(orderNumber);
        order.setOrderStatus("已完成");
        order.setBusinessPackage("预存送流量");
        order.setUserType("1");
        order.setCreateTime(new Date());
        order.setHehuorenId(partner);
        if(list.size() > 0){
            order.setNowPackage(list.get(0).get("now_package").toString());
            order.setContactNumber(list.get(0).get("acc_nbr").toString());
            if(!partnerInfo.isEmpty()) {
                order.setHehuorenArea(partnerInfo.get(0).get("area").toString());
                order.setHehuorenName(partnerInfo.get(0).get("name").toString());
                order.setHehuorenSchool(partnerInfo.get(0).get("school").toString());
                order.setHehuorenPhone(partnerInfo.get(0).get("account").toString());
            }
            List<Map<String, Object>> list2 = orderMapper.selectOrderYcsll(list.get(0).get("acc_nbr").toString());
            if(list2.size() > 0){
                // 更新hhr_order
                Wrapper<Order> orderWrapper = new EntityWrapper<>();
                orderWrapper.eq("id", list2.get(0).get("id"));
                orderMapper.update(order,orderWrapper);
            }else{
                orderMapper.insert(order);
            }
        }
    }

    /**
     * 5G加装包
     * @param partner
     * @param customerName
     * @param authCode
     * @param contactNumber
     * @param businessNumber
     * @param kapin
     * @param idCard
     * @param oldPackage
     * @param signUrl
     * @return
     */
    @RequestMapping(value = "addPackageOrder",method = RequestMethod.POST)
    public ResponseData<String> addPackageOrder(@RequestParam("partner")String partner,  // 合伙人id
                                                @RequestParam("customerName")String customerName,  //用户名称
                                                @RequestParam("authCode") String authCode,   //验证码
                                                @RequestParam("contactNumber")String contactNumber, // 联系号码
                                                @RequestParam("businessNumber")String businessNumber, // 办理号码
                                                @RequestParam("kapin")String kapin,   // 新卡品
                                                @RequestParam("idCard")String idCard,  // 身份证号
                                                @RequestParam("oldPackage")String oldPackage,  // 老卡品
                                                @RequestParam("signUrl")String signUrl,  // 签名
                                                @RequestParam(value = "sell",required = false)String sell){

        // 短信校验
        Object o = redisTemplate.opsForValue().get(businessNumber);

        if (o == null) {
            return ResponseData.error("请重新发送短信验证码");
        }

        if(!authCode.equals(o.toString())) {
            return ResponseData.error("短信验证码错误！");
        }

        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(businessNumber),"business_number",businessNumber);
        wrapper.eq(StringUtils.isNotBlank(kapin),"kapin",kapin);
        wrapper.ne("order_status", "异常单");
        List<Order> orders = orderMapper.selectList(wrapper);
        if(orders!=null && orders.size()>0){
            return ResponseData.error("5G升级订单已存在，请不要重复申请！");
        }
        Order order = new Order();
        Integer integer = 0;
        //合伙人字段
        List<Map<String,Object>> partnerInfo  = userMapper.findPartnerById(partner);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        uuid = uuid.substring(1, 12);
        Date data = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String orderNumber = "YRYM" + df.format(new Date()) + uuid;
        order.setId(uuid);
        order.setOrderNumber(orderNumber);
        order.setCustomerName(customerName);
        order.setContactNumber(contactNumber);
        order.setBusinessNumber(businessNumber);
        order.setKapin(kapin);
        order.setIdCard(idCard);
        order.setOrderStatus("待受理");
        order.setUserType("1"); // 老客户办理
        order.setNowPackage(oldPackage);
        order.setBusinessPackage("5G加装包");
        order.setHehuorenId(partner);
        if(!partnerInfo.isEmpty()) {
            order.setHehuorenArea(partnerInfo.get(0).get("area").toString());
            order.setHehuorenName(partnerInfo.get(0).get("name").toString()+sell);
            order.setHehuorenSchool(partnerInfo.get(0).get("school").toString());
            order.setHehuorenPhone(partnerInfo.get(0).get("account").toString());
        }
        order.setCreateTime(data);
        order.setUpdateTime(data);
        order.setSignImg(PicturesUtil.uploadPictures(signUrl, orderNumber, "signImg"));
        try{
            integer = orderMapper.insert(order);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(integer == 1){
            return ResponseData.success(uuid,"5G加装包升级成功");
        }
        return ResponseData.error("5G升级订单失败，请重试！");
    }
}
