package com.winsun.controller;

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 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.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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<String> sendVerificationCode(@RequestParam("selectOrder") String selectOrder) {
        Wrapper<PackageUpgrade> wrapper = new EntityWrapper();
        if (selectOrder.contains("@")) {
            wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr2", selectOrder);
            List<Map<String, Object>> packageUpgrade = appMapper.selectPackage(wrapper);
            String nbr = null;
            if (packageUpgrade.size() != 0) {
                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("已发送验证码到手机：" + nbr.substring(0, 3) + "****" + nbr.substring(7, 11) + "验证码：" + s);
        }
        if (selectOrder.length() == 18) {
            wrapper.eq(StringUtils.isNotBlank(selectOrder), "social_id", selectOrder);
            List<Map<String, Object>> packageUpgrade = appMapper.selectPackage(wrapper);
            String nbr = null;
            if (packageUpgrade.size() != 0) {
                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("已发送验证码到手机：" + nbr.substring(0, 3) + "****" + nbr.substring(7, 11) + "验证码：" + s);
        }
        if (selectOrder.length() == 11) {
            wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr", selectOrder);
            List<Map<String, Object>> packageUpgrade = appMapper.selectPackage(wrapper);
            String nbr = null;
            if (packageUpgrade.size() != 0) {
                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("已发送验证码到手机：" + nbr.substring(0, 3) + "****" + nbr.substring(7, 11) + "验证码：" + s);
        }
        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) {
        if (redisTemplate.opsForValue().get(selectOrder).toString().equals(verificationCode)) {
            Wrapper<PackageUpgrade> wrapper = new EntityWrapper();
            Wrapper<Package> wrapper1 = new EntityWrapper();
            Wrapper<Package> wrapper2 = new EntityWrapper();
            if (selectOrder.contains("@")) {
                wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr2", selectOrder);
                List<Map<String, Object>> packageUpgrade = appMapper.selectPackage(wrapper);
                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.remove("social_id");
                map.put("oldPackage", packages1.get(0));
                map.put("newPackage", packages2.get(0));
                return ResponseData.success(map);
            }
            if (selectOrder.length() == 18) {
                wrapper.eq(StringUtils.isNotBlank(selectOrder), "social_id", selectOrder);
                List<Map<String, Object>> packageUpgrade = appMapper.selectPackage(wrapper);
                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("oldPackage", packages1.get(0));
                map.put("newPackage", packages2.get(0));
                return ResponseData.success(map);
            }
            if (selectOrder.length() == 11) {
                wrapper.eq(StringUtils.isNotBlank(selectOrder), "acc_nbr", selectOrder);
                List<Map<String, Object>> packageUpgrade = appMapper.selectPackage(wrapper);
                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("oldPackage", packages1.get(0));
                map.put("newPackage", packages2.get(0));
                return ResponseData.success(map);
            }
        }
        return ResponseData.error("验证码有误");
    }

    /**
     * 套餐升级
     *
     * @param servId
     * @param contactNumber   联系号码
     * @param oldUserId
     * @param businessNumber  办理号码
     * @param cardId          套餐ID
     * @param customerName    客户姓名
     * @param userId
     * @param nowPackage      现有套餐
     * @param partner         用户ID
     * @param businessPackage 办理套餐
     * @param is_yct          羊城通
     * @param mark            羊城通是否办理(空为不办理，不为空就办理)
     * @param addRess         地址（办理羊城通才使用，正常订单为空）
     * @param custName        姓名 （办理羊城通才使用，正常订单为空）
     * @param userSchool      学校 （办理羊城通才使用，正常订单为空）
     * @return
     */
    @RequestMapping(value = "oldUserUpade", method = RequestMethod.POST)
    public ResponseData<String> oldUserUpade(@RequestParam("contactNumber") String contactNumber, @RequestParam("oldUserId") String oldUserId
            , @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 = "is_yct", required = false) String is_yct
            , @RequestParam(value = "mark", required = false) String mark, @RequestParam(value = "addRess", required = false) String addRess
            , @RequestParam(value = "servId") String servId, @RequestParam(value = "custName", required = false) String custName
            , @RequestParam(value = "userSchool", required = false) String userSchool) {
        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("business_number", businessNumber);
        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.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);
        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.setCustomerName(custName);
            yangChengTong.setContactAddress(addRess);
            yangChengTong.setContactPhone(contactNumber);
            yangChengTong.setCustomerPhone(businessNumber);
            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("升级失败！");
    }



}
