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.Package;
import com.winsun.bean.School;
import com.winsun.bean.SysUser;
import com.winsun.constant.OrderStatus;
import com.winsun.constant.UserType;
import com.winsun.mapper.*;
import com.winsun.utils.IDCardUtil;
import com.winsun.utils.PicturesUtil;
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.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.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 套餐升级
 */
@Slf4j
@RestController
@RequestMapping("/packageNewClothes")
public class PackageNewClothes {

    private static String PATHTYPE="idCard";

    private static AppMapper appMapper;

    private static PackageMapper packageMapper;

    private static SchoolMapper schoolMapper;

    private static OrderMapper orderMapper;

    private static SysUserMapper userMapper;

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

    /**
     * 查询用户学校适用套餐
     *
     * @param partner
     * @return
     */
    @RequestMapping(value = "selectSchoolPackage", method = RequestMethod.POST)
    public ResponseData<List<Package>> selectSchoolPackage(@RequestParam("partner") String partner) {
        String schoolId = appMapper.selectSchoolId(partner);
        List<String> packageIds = appMapper.selectPackageId(schoolId);
        List<Package> packages = new ArrayList<>();
        packageIds.forEach(packageId -> {
            Package package1 = packageMapper.selectById(packageId);
            packages.add(package1);
        });
        return ResponseData.success(packages);
    }

    /**
     * 手机号码获取 JT0001
     *
     * @param cardId     套餐ID
     * @param partner    用户ID
     * @param contNumber 套餐ID
     * @return
     */
    @RequestMapping(value = "getNumber", method = RequestMethod.POST)
    public ResponseData<JSONObject> getNumber(@RequestParam("cardId") String cardId, @RequestParam("partner") String partner, @RequestParam(value = "contNumber", required = false) String contNumber) {
        Package aPackage = packageMapper.selectById(cardId);
        String schoolId = appMapper.selectSchoolId(partner);
        School school = schoolMapper.selectById(schoolId);
        String xbId = aPackage.getXbId();
        String netId = school.getNetId();
        JSONObject jsonObject = null;
        try {
            jsonObject = XbkUtil.getNumberJT0001(contNumber, xbId, netId);
        } catch (Exception e) {
            log.error("JT0001获取手机号码接口异常", e.getMessage());
            ResponseData.error("手机号码获取失败，请重新获取。");
        }
        if (!"0".equals(jsonObject.getString("code"))) {
            return ResponseData.error(jsonObject.getString("msg"));
        }
        return ResponseData.success(jsonObject);
    }


    /**
     * 查询套餐详情
     *
     * @param packageId 套餐ID
     * @return
     */
    @RequestMapping(value = "selectPackageInfo", method = RequestMethod.POST)
    public ResponseData<Package> selectPackageInfo(@RequestParam("packageId") String packageId) {
        return ResponseData.success(packageMapper.selectById(packageId));
    }


    /**
     * 新开手机卡  预制卡
     *
     * @param site          省市县
     * @param address        详细地址
     * @param kapin         套餐名
     * @param idCardz       身份证正面地址
     * @param idCardf       身份证反面地址
     * @param idCardzs      手持身份证正面地址
     * @param studentCard   学生卡
     * @param remarks       备注
     * @param customerName  用户姓名
     * @param contactNumber 联系电话
     * @param cardId        套餐ID
     * @param partner       用户ID
     * @param idCard        用户身份证
     * @param userSchool    学校
     * @return
     */
    @RequestMapping(value = "newMobilePhoneCard", method = RequestMethod.POST)
    public ResponseData<String> newMobilePhoneCard(@RequestParam("contactNumber") String contactNumber, @RequestParam("site") String site
            , @RequestParam("studentCard") String studentCard, @RequestParam("address") String address, @RequestParam("cardId") String cardId
            , @RequestParam("customerName") String customerName, @RequestParam("partner") String partner
            , @RequestParam(value = "idCardzs") String idCardzs, @RequestParam(value = "idCardz") String idCardz, @RequestParam(value = "idCardf") String idCardf
            , @RequestParam(value = "remarks", required = false) String remarks, @RequestParam(value = "kapin") String kapin
            , @RequestParam(value = "idCard") String idCard, @RequestParam(value = "userSchool") String userSchool) {
        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        /**
         * 套餐验证
         */
        ResponseData<String> pac = packageVerification(partner, cardId);
        if(!pac.isSuccess()){
            return pac;
        }
        /**
         * 身份证验证
         */
        if(!IDCardUtil.IDCardValidate(idCard)){
            return ResponseData.error("您的身份证输入有误，请重新输入！");
        }
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -94);
        Date time = instance.getTime();
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("id_card",idCard);
        wrapper.gt("create_time", time);
        wrapper.ne("order_status", OrderStatus.ACCEPTEXCEPTCION.getName()).and().ne("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        List<Order> orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您已经存在新开卡的订单，不能再重复开卡！");
        }
        SysUser sysUser = userMapper.selectById(partner);
        Order order = new Order();
        String uuid = UUID.randomUUID().toString();
        String id=uuid.split("-")[0]+uuid.split("-")[1];
        order.setId(id);
        order.setIdCard(idCard);
        order.setOrderStatus("待处理");
        order.setAddress(address);
        order.setUserSchool(userSchool);
        order.setHehuorenId(partner);
        order.setSite(site);
        order.setKapin(kapin);
        order.setPackageId(cardId);
        order.setCustomerName(customerName);
        order.setContactNumber(contactNumber);
        order.setStudenCard(PicturesUtil.uploadPictures(studentCard, partner,PATHTYPE));
        order.setIdCardzs(PicturesUtil.uploadPictures(studentCard, partner,PATHTYPE));
        order.setIdCardz(PicturesUtil.uploadPictures(idCardz, partner,PATHTYPE));
        order.setIdCardf(PicturesUtil.uploadPictures(idCardf, partner,PATHTYPE));
        order.setRemarks(remarks);
        Date date = new Date();
        order.setCreateTime(date);
        order.setUserType(UserType.NEWCUSTOMER.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);
        // MessageUtil.sent(contactNumber,"4","");

        if (insert == 1) {
            appMapper.inserOrderHis(id, "资料已提交", date, sysUser.getName());
            return ResponseData.success(id);
        }
        return ResponseData.error("开卡失败！");
    }

    /**
     * 新开手机卡 天翼学生卡
     *
     * @param site          地址
     * @param kapin         套餐名
     * @param idCardz
     * @param idCardf
     * @param idCardzs
     * @param remarks       备注
     * @param studentNumber 学号
     * @param classNumber   班级
     * @param parentName    家长姓名
     * @param contactNumber 家长电话
     * @param cardId        套餐ID
     * @param customerName  学生姓名
     * @param partner       用户ID
     * @param idCard        家长身份证
     * @param userSchool    学校
     * @return
     */
    @RequestMapping(value = "skywingCard", method = RequestMethod.POST)
    public ResponseData<String> SkywingCard(@RequestParam("contactNumber") String contactNumber, @RequestParam("site") String site
            , @RequestParam("classNumber") String classNumber, @RequestParam("cardId") String cardId
            , @RequestParam("customerName") String customerName, @RequestParam("partner") String partner
            , @RequestParam(value = "idCardzs") String idCardzs, @RequestParam(value = "idCardz") String idCardz
            , @RequestParam(value = "parentName") String parentName, @RequestParam(value = "idCardf") String idCardf
            , @RequestParam(value = "remarks", required = false) String remarks, @RequestParam(value = "kapin") String kapin
            , @RequestParam(value = "idCard") String idCard, @RequestParam(value = "studentNumber") String studentNumber
            , @RequestParam(value = "userSchool") String userSchool) {

        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        /**
         * 套餐验证
         */
        ResponseData<String> pac = packageVerification(partner, cardId);
        if(!pac.isSuccess()){
            return pac;
        }
        /**
         * 身份证验证
         */
        if(!IDCardUtil.IDCardValidate(idCard)){
            return ResponseData.error("您的身份证输入有误，请重新输入！");
        }
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -94);
        Date time = instance.getTime();
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("id_card",idCard);
        wrapper.gt("create_time", time);
        wrapper.ne("order_status", OrderStatus.ACCEPTEXCEPTCION.getName()).and().ne("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        List<Order> orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您已经存在新开卡的订单，不能再重复开卡！");
        }
        SysUser sysUser = userMapper.selectById(partner);
        Order order = new Order();
        String uuid = UUID.randomUUID().toString();
        String id=uuid.split("-")[0]+uuid.split("-")[1];
        order.setId(id);
        order.setIdCard(idCard);
        order.setOrderStatus("待处理");
        order.setUserSchool(userSchool);
        order.setHehuorenId(partner);
        order.setSite(site);
        order.setKapin(kapin);
        order.setPackageId(cardId);
        order.setCustomerName(customerName);
        order.setContactNumber(contactNumber);
        //图片处理
        order.setIdCardzs(PicturesUtil.uploadPictures(idCardzs, partner,PATHTYPE));
        order.setIdCardz(PicturesUtil.uploadPictures(idCardz, partner,PATHTYPE));
        order.setIdCardf(PicturesUtil.uploadPictures(idCardf, partner,PATHTYPE));
        order.setRemarks(remarks);
        order.setClassNumber(classNumber);
        order.setParentName(parentName);
        order.setStudentNumber(studentNumber);
        Date date = new Date();
        order.setCreateTime(date);
        order.setUserType(UserType.NEWCUSTOMER.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);
        // MessageUtil.sent(contactNumber,"4","");
        if (insert == 1) {
            appMapper.inserOrderHis(id, "资料已提交", date, sysUser.getName());
            return ResponseData.success(id);
        }
        return ResponseData.error("开卡失败！");
    }

    /**
     * 新开手机卡 小白卡
     *
     * @param site           地址
     * @param kapin          套餐名
     * @param studentCard    学生卡
     * @param remarks        备注
     * @param customerName   用户姓名
     * @param contactNumber  联系电话
     * @param cardId         套餐ID
     * @param partner        用户ID
     * @param idCard         用户身份证
     * @param userSchool     学校
     * @param addRess        详细地址
     * @param businessNumber 办理号码
     * @return
     */
    @RequestMapping(value = "XiaoBaiCard", method = RequestMethod.POST)
    public ResponseData<String> XiaoBaiCard(@RequestParam("contactNumber") String contactNumber, @RequestParam(value = "site", required = false) String site
            , @RequestParam("studentCard") String studentCard, @RequestParam("cardId") String cardId, @RequestParam(value = "addRess", required = false) String addRess
            , @RequestParam("customerName") String customerName, @RequestParam("partner") String partner, @RequestParam("businessNumber") String businessNumber
            , @RequestParam(value = "remarks", required = false) String remarks, @RequestParam(value = "kapin") String kapin
            , @RequestParam(value = "idCard") String idCard, @RequestParam(value = "userSchool") String userSchool) {
        if (contactNumber.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        String schoolId = appMapper.selectSchoolId(partner);
        School school = schoolMapper.selectById(schoolId);
        String netId = school.getNetId();
        Package aPackage = packageMapper.selectById(cardId);
        String xbId = aPackage.getXbId();
        /**
         * 套餐验证
         */
        ResponseData<String> pac = packageVerification(partner, cardId);
        if(!pac.isSuccess()){
            return pac;
        }
        /**
         * 身份证验证
         */
        ResponseData<String> res = idCardVerification(idCard, customerName);
        if(!res.isSuccess()){
            return res;
        }
        /**
         * 小白卡下单
         */
        JSONObject jsonObject = null;
        try {
            jsonObject = XbkUtil.xbkOrderJT0002(businessNumber, idCard,
                    customerName, contactNumber, xbId, netId);
        } catch (Exception e) {
            log.error("小白卡下单接口调用异常", e.getMessage());
        }
        if (jsonObject == null) {
            return ResponseData.error("小白卡下单失败,如有疑问请联系客服,谢谢。");
        }
        if (!"0".equals(jsonObject.getString("code"))) {
            return ResponseData.error("小白卡下单失败,如有疑问请联系客服,谢谢。");
        }
        Map map = JSON.parseObject(jsonObject.getString("dataArray"), HashMap.class);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -94);
        Date time = instance.getTime();
        Wrapper<Order> wrapper = new EntityWrapper();
        wrapper.eq("id_card",idCard);
        wrapper.gt("create_time", time);
        wrapper.ne("order_status", OrderStatus.ACCEPTEXCEPTCION.getName()).and().ne("order_status", OrderStatus.SUCCESSFULDISTRIBUTION.getName());
        wrapper.eq("user_type", UserType.NEWCUSTOMER.getId());
        List<Order> orders = orderMapper.selectList(wrapper);
        if (orders.size() != 0) {
            return ResponseData.error("您已经存在新开卡的订单，不能再重复开卡！");
        }
        SysUser sysUser = userMapper.selectById(partner);
        Order order = new Order();
        String uuid = UUID.randomUUID().toString();
        String id=uuid.split("-")[0]+uuid.split("-")[1];
        order.setId(id);
        order.setIdCard(idCard);
        order.setXbOrderId(map.get("orderCode").toString());
        order.setOrderStatus("待识别");
        order.setUserSchool(userSchool);
        order.setHehuorenId(partner);
        order.setXbType(1);
        if(StringUtils.isNotBlank(site)){
            order.setSite(site);
        }
        if(StringUtils.isNotBlank(addRess)){
            order.setAddress(addRess);
        }
        order.setKapin(kapin);
        order.setPackageId(cardId);
        order.setCustomerName(customerName);
        order.setContactNumber(contactNumber);
        order.setRemarks(remarks);
        order.setStudenCard(PicturesUtil.uploadPictures(studentCard,partner,PATHTYPE));
        order.setBusinessNumber(businessNumber);
        Date date = new Date();
        order.setCreateTime(date);
        order.setUserType(UserType.NEWCUSTOMER.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());
        order.setHehuorenSchool(school.getSchoolName());
        order.setHehuorenPhone(sysUser.getPhone());
        List<String> userId = appMapper.selectsupervisorBySchool(schoolId);
        SysUser user = userMapper.selectById(userId.get(0));
        order.setSupervisorName(user.getName());
        order.setLzgh(school.getLzgh());
        Integer insert = orderMapper.insert(order);
        // MessageUtil.sent(contactNumber,"4","");

        if (insert == 1) {
            appMapper.inserOrderHis(id, "资料提交成功,等待上传证件", date, sysUser.getName());
            return ResponseData.success(map.get("orderCode").toString());
        }
        return ResponseData.error("开卡失败！");
    }

    /**
     * 身份证验证
     * @param idCard 身份证
     * @param customerName 姓名
     * @return
     */
    public static ResponseData<String> idCardVerification(String idCard,String customerName){
        JSONObject jsonObject1 = null;
        try {
            jsonObject1 = XbkUtil.idCardCheckJT0005(idCard, customerName);
        } catch (Exception e) {
            log.error("身份证验证接口调用异常", e.getMessage());
        }
        if (jsonObject1 == null) {
            log.info("身份证验证接口调用异常");
            return ResponseData.error("身份证验证失败。");
        }
        if (!"0".equals(jsonObject1.getString("code"))) {
            return ResponseData.error(jsonObject1.getString("msg"));
        }
        Integer i = Integer.parseInt(idCard.substring(6, 10));
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date timeDate = new Date();
        Integer age = Integer.parseInt(dateFormat.format(timeDate.getTime()));
        Integer time16 = Integer.parseInt(String.valueOf(i + 16) + idCard.substring(10, 14));
        Integer time25 = Integer.parseInt(String.valueOf(i + 25) + idCard.substring(10, 14));
        if (age < time16) {
            return ResponseData.error("根据工信部要求,未满16周岁的用户,应由法定代理人代为办理线上入网,如有疑问请联系客服,谢谢。");
        }
        if (age > time25) {
            return ResponseData.error("您已满25周岁,不符合办理条件,如有疑问请联系客服,谢谢。");
        }
        return ResponseData.success("OK");
    }

    /**
     * 查询当前用户是否适用此套餐
     *
     * @param partner
     * @return
     */
    public ResponseData<String> packageVerification(String partner,String packageID) {
        String schoolId = appMapper.selectSchoolId(partner);
        if(schoolId == null){
            return ResponseData.error("当前二维码已失效，如有疑问请联系客服！");
        }
        List<String> packageIds = appMapper.selectPackageId(schoolId);
        if(packageIds.contains(packageID)){
          return  ResponseData.success("ok");
        }
        return ResponseData.error("当前二维码无法办理此套餐，如有疑问请联系客服！");
    }

}
