package com.winsun.controller;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
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.utils.IDCardUtil;
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 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,
                                    YangChengTongrMapper yangChengTongrMapper, OrderMapper orderMapper
            , SysUserMapper userMapper) {
        PackageUpgradeController.appMapper = appMapper;
        PackageUpgradeController.packageMapper = packageMapper;
        PackageUpgradeController.yangChengTongrMapper = yangChengTongrMapper;
        PackageUpgradeController.orderMapper = orderMapper;
        PackageUpgradeController.userMapper = userMapper;
    }

    /**
     * 验证码
     *
     * @param selectOrder
     * @return
     */
    @RequestMapping(value = "sendVerificationCode", method = RequestMethod.POST)
    public ResponseData<List<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) ((Math.random() * 9 + 1) * 100000));
            log.info("验证码:" + s);
            //MessageUtil.sent(packageUpgrade.getAccNbr(),"4","您获取的验证码为："+s+",半小时内有效。");
            redisTemplate.opsForValue().set(servId, s, 30, TimeUnit.MINUTES);
            return ResponseData.success(null, "已发送验证码到手机：" + packageUpgrade.getAccNbr().substring(0, 3) + "****" + packageUpgrade.getAccNbr().substring(7, 11) + "验证码：" + s);
        }
        List<Map<String, Object>> list = new ArrayList<>();
        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);
        }
        if (selectOrder.length() == 18) {
            if (!IDCardUtil.IDCardValidate(selectOrder)) {
                return ResponseData.error("您的身份证输入有误，请重新输入！");
            }
            wrapper.like("social_id", selectOrder.substring(5, 18), SqlLike.LEFT);
        }
        if (selectOrder.length() == 11) {
            wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr", selectOrder);
        }

        List<Map<String, Object>> packageUpgrade = appMapper.selectMaps(wrapper);
        String nbr = null;
        if (packageUpgrade.size() > 1) {
            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));
                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(packageUpgrade);
        }
        if (packageUpgrade.size() == 1) {
            nbr = packageUpgrade.get(0).get("acc_nbr").toString();
        } else {
            return ResponseData.error("当前查询条件未查出套餐升级数据，如有疑问请联系客服！");
        }
        String s = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        log.info("验证码:" + s);
        //MessageUtil.sent(packageUpgrade.getAccNbr(),"4","您获取的验证码为："+s+",半小时内有效。");
        redisTemplate.opsForValue().set(selectOrder, s, 30, TimeUnit.MINUTES);
        return ResponseData.success(null, "已发送验证码到手机：" + nbr.substring(0, 3) + "****" + nbr.substring(7, 11) + "验证码：" + s);


    }


    /**
     * 查询套餐升级信息
     *
     * @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(servId).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);
            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(servId).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) {
        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());
        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
        String format = yyyyMMdd.format(date);
        String s = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        order.setOrderNumber("YRYM" + format + s);
        order.setHehuorenArea(sysUser.getSubstName());
        order.setHehuorenName(sysUser.getName());
        String schoolId = appMapper.selectSchoolId(partner);
        List<String> dudao = appMapper.selectsupervisorBySchool(schoolId);
        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, sysUser.getName());
        // 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) ((Math.random() * 9 + 1) * 1000));
            order.setId(id1);
            order.setOrderNumber("YRYM" + format + s1);
            order.setUserType(UserType.YCTK.getId());
            order.setAddress(addRess);
            order.setBusinessPackage("天翼羊城通手机卡业务");
            order.setUserSchool(userSchool);
            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, sysUser.getName());
            return ResponseData.success(id + ":" + id1, "下单成功！");
        }
        if (insert == 1) {
            return ResponseData.success(id);
        }
        return ResponseData.error("升级失败！");
    }


}
