package com.mmc.iuav.user.service.dronepilot.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mmc.iuav.http.HttpsRequestUtil;
import com.mmc.iuav.page.PageResult;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
import com.mmc.iuav.user.constant.UserSystemConstant;
import com.mmc.iuav.user.constant.WxConstant;
import com.mmc.iuav.user.controller.userpoints.config.NumberOfUserPoints;
import com.mmc.iuav.user.controller.userpoints.config.UserPointsEnum;
import com.mmc.iuav.user.controller.wx.*;
import com.mmc.iuav.user.dao.UserSubInfoDao;
import com.mmc.iuav.user.dao.dronepilot.PilotCertificationDao;
import com.mmc.iuav.user.dao.userpoints.UserPointsDao;
import com.mmc.iuav.user.dao.userpoints.UserPointsDetailsDao;
import com.mmc.iuav.user.entity.CompanyInfoDO;
import com.mmc.iuav.user.entity.UserAccountDO;
import com.mmc.iuav.user.entity.dronepilot.*;
import com.mmc.iuav.user.entity.userpoints.UserPointsDO;
import com.mmc.iuav.user.entity.userpoints.UserPointsDetails;
import com.mmc.iuav.user.model.dto.LoginSuccessDTO;
import com.mmc.iuav.user.model.dto.dronepilot.*;
import com.mmc.iuav.user.model.qo.dronepilot.*;
import com.mmc.iuav.user.model.vo.CompanyInfoVO;
import com.mmc.iuav.user.model.vo.PilotAuditSumVO;
import com.mmc.iuav.user.model.vo.WxMsgVO;
import com.mmc.iuav.user.model.vo.dronepilot.PilotAbilityVO;
import com.mmc.iuav.user.model.vo.dronepilot.PilotCertificationVO;
import com.mmc.iuav.user.model.vo.userpoints.UserPointsVO;
import com.mmc.iuav.user.service.WxService;
import com.mmc.iuav.user.service.dronepilot.PilotCertificationService;
import com.mmc.iuav.user.util.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

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

/**
 * @Author small
 * @Date 2023/7/28 9:35
 * @Version 1.0
 */
@Service
public class PilotCertificationServiceImpl implements PilotCertificationService {

    @Autowired
    private PilotCertificationDao certificationDao;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserSystemConstant userSystemConstant;

    @Autowired
    private UserPointsDao userPointsDao;

    @Autowired
    private UserPointsDetailsDao userPointsDetailsDao;


    @Autowired
    private RestTemplate restTemplate;

    @Value("${iuav.ims.uri}")
    private String imsApp;

    @Autowired
    private WxService wxService;

    @Autowired
    private UserSubInfoDao userSubInfoDao;


    @Override
    public ResultBody insertPilot(PilotCertificationVO certificationVO, LoginSuccessDTO userLoginInfoFromRedis) {

        Integer count = certificationDao.selectRealNameAuth(userLoginInfoFromRedis.getUserAccountId());
        if (count == 0) {
            return ResultBody.error(ResultEnum.PLEASE_ERFORM_REAL_NAME_AUTHENTICATION_FIRST);
        }
        Integer integer = certificationDao.selectPilotCertification(userLoginInfoFromRedis.getUserAccountId());
        if (integer != 0) {
            return ResultBody.error(ResultEnum.I_HAVE_APPLIED_FOR_A_PILOT_LICENSE);
        }
        PilotCertificationDO pilotCertificationDO = new PilotCertificationDO(certificationVO, userLoginInfoFromRedis.getUserAccountId());
        certificationDao.insertPilot(pilotCertificationDO);
        List<PilotAbilityVO> pilotAbility = pilotCertificationDO.getPilotAbility();
        for (PilotAbilityVO pilotAbilityVO : pilotAbility) {
            pilotAbilityVO.setPilotCertificationId(pilotCertificationDO.getId());
        }
        certificationDao.insertAbility(pilotAbility);
        PilotCertificationLogDO pilotCertificationLog = new PilotCertificationLogDO(pilotCertificationDO, CertificationMessage.match(0));
        certificationDao.insertPilotLog(pilotCertificationLog);

        return ResultBody.success();
    }


    @Override
    public ResultBody<PilotAbilityDTO> abilityList() {
        List<PilotAbilityDO> abilityDOList = certificationDao.abilityList();
        List<PilotAbilityDTO> collect = abilityDOList.stream().map(PilotAbilityDO::buildPilotAbilityDTO).collect(Collectors.toList());
        return ResultBody.success(collect);
    }

    @Override
    public ResultBody updatePilot(PilotCertificationVO certificationVO, LoginSuccessDTO userLoginInfoFromRedis) {
        certificationDao.deleteAbility(certificationVO.getId());
        PilotCertificationDO pilotCertificationDO = new PilotCertificationDO(certificationVO, userLoginInfoFromRedis.getUserAccountId());
        Integer count = certificationDao.selectPilotCount(pilotCertificationDO.getId(), userLoginInfoFromRedis.getUserAccountId());
        if (count == 0) {
            return ResultBody.error(ResultEnum.CAN_NOT_CHANGE_THE_APPLICATION_OF_OTHERS);
        }
        certificationDao.updatePilot(pilotCertificationDO);
        List<PilotAbilityVO> pilotAbility = pilotCertificationDO.getPilotAbility();
        for (PilotAbilityVO pilotAbilityVO : pilotAbility) {
            pilotAbilityVO.setPilotCertificationId(pilotCertificationDO.getId());
        }
        certificationDao.insertAbility(pilotAbility);
        PilotCertificationLogDO pilotCertificationLog = new PilotCertificationLogDO(pilotCertificationDO, CertificationMessage.match(0));
        certificationDao.insertPilotLog(pilotCertificationLog);
        return ResultBody.success();
    }

    @Override
    public PageResult pilotList(PilotCertificationQO param) {
        Integer pageNo = param.getPageNo();
        param.buildCurrentPage();
        List<PilotCertificationDO> pilotList = certificationDao.pilotList(param);
        extracted(pilotList);
        if (param.getAbilityId() != null) {
            for (PilotCertificationDO pilotCertificationDO : pilotList) {
                ArrayList<PilotAbilityVO> list = new ArrayList<>();
                List<PilotAbilityVO> pilotAbility = pilotCertificationDO.getPilotAbility();
                for (PilotAbilityVO pilotAbilityVO : pilotAbility) {
                    if (pilotAbilityVO.getAbilityId().equals(param.getAbilityId())) {
                        list.add(pilotAbilityVO);
                    }
                }
                if (list.size() == 0) {
                    pilotCertificationDO.setPilotAbility(null);
                }
            }
            pilotList = pilotList.stream().filter(t -> t.getPilotAbility() != null).collect(Collectors.toList());
        }
        List<PilotCertificationDTO> collect = pilotList.stream().map(PilotCertificationDO::buildPilotCertificationDTO).collect(Collectors.toList());
        collect = collect.stream().skip((pageNo - 1) * param.getPageSize()).limit(param.getPageSize()).
                collect(Collectors.toList());

        Integer tokenUserId = param.getTokenUserId();
        if (tokenUserId!=null){
            List<ForumAttentionDO> info = info(param.getTokenUserId());
            for (ForumAttentionDO forumAttentionDO : info) {
            for (PilotCertificationDTO pilotCertificationDTO : collect) {
                    if (forumAttentionDO.getMutualAttention().equals(true)){
                        if (pilotCertificationDTO.getUserAccountId().equals(forumAttentionDO.getUserAccountId())||
                        pilotCertificationDTO.getUserAccountId().equals(forumAttentionDO.getAttentionUserAccountId())){
                            pilotCertificationDTO.setStatus(true);
                        }
                    }
                    if (forumAttentionDO.getMutualAttention().equals(false)){
                        if (pilotCertificationDTO.getUserAccountId().equals(forumAttentionDO.getUserAccountId())){
                            pilotCertificationDTO.setStatus(true);
                        }
                    }
                }
            }
        }
        PageResult pageResult = PageResult.buildPage(pageNo, param.getPageSize(), pilotList.size(), collect);
        return pageResult;
    }


    public List<ForumAttentionDO> info( Integer userAccountId) {
        String token = null;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("token", token);
        HttpEntity<String> entity = new HttpEntity<>(userAccountId.toString(), headers);
        ResponseEntity<String> exchange = restTemplate.exchange(imsApp + "/release/dynamic/getPilot?userAccountId=" + userAccountId , HttpMethod.GET, entity, String.class);
        Object body = exchange.getBody();
        JSONObject jsonObject1 = JSONObject.parseObject(body.toString());
        List<Map> mapList = (List<Map>)jsonObject1.get("result");
        List<ForumAttentionDO> forumAttentionDOS = JSON.parseArray(JSON.toJSONString(mapList), ForumAttentionDO.class);
        return forumAttentionDOS;
    }


    @Override
    public PilotCertificationDTO detailPilot(Integer id) {
        PilotCertificationDO certificationDO = certificationDao.detailPilot(id);
        int yearsOfWorking = 0;
        yearsOfWorking = getYearsOfWorking(certificationDO.getTimeOfApplication());
        Integer Working = certificationDO.getYearsOfWorking();
        yearsOfWorking = yearsOfWorking + Working;
        certificationDO.setYearsOfWorking(yearsOfWorking);

        certificationDO.setAge(getAgeByBirth(certificationDO.getBirthday()));
        PilotCertificationDTO pilotCertificationDTO = certificationDO.buildPilotCertificationDTO();
        return pilotCertificationDTO;
    }

    @Override
    public PilotCertificationDTO userDetailPilot(Integer userAccountId) {
        PilotCertificationDO certificationDO = certificationDao.userDetailPilot(userAccountId);
        if (certificationDO == null) {
            return null;
        }
        int yearsOfWorking = 0;
        yearsOfWorking = getYearsOfWorking(certificationDO.getTimeOfApplication());
        Integer Working = certificationDO.getYearsOfWorking();
        yearsOfWorking = yearsOfWorking + Working;
        certificationDO.setYearsOfWorking(yearsOfWorking);

        certificationDO.setAge(getAgeByBirth(certificationDO.getBirthday()));
        PilotCertificationDTO pilotCertificationDTO = certificationDO.buildPilotCertificationDTO();
        return pilotCertificationDTO;
    }

    @Override
    public PageResult backListPilot(PilotCertificationQO param, LoginSuccessDTO userLoginInfoFromRedis) {
        Integer pageNo = param.getPageNo();
        param.buildCurrentPage();
        List<PilotCertificationDO> pilotList = certificationDao.pilotList(param);
        extracted(pilotList);
        if (param.getAbilityId() != null) {
            for (PilotCertificationDO pilotCertificationDO : pilotList) {
                ArrayList<PilotAbilityVO> list = new ArrayList<>();
                List<PilotAbilityVO> pilotAbility = pilotCertificationDO.getPilotAbility();
                for (PilotAbilityVO pilotAbilityVO : pilotAbility) {
                    if (pilotAbilityVO.getAbilityId().equals(param.getAbilityId())) {
                        list.add(pilotAbilityVO);
                    }
                }
                if (list.size() == 0) {
                    pilotCertificationDO.setPilotAbility(null);
                }
            }
            pilotList = pilotList.stream().filter(t -> t.getPilotAbility() != null).collect(Collectors.toList());
        }
        List<PilotCertificationDTO> collects = pilotList.stream().map(PilotCertificationDO::buildPilotCertificationDTO).collect(Collectors.toList());
        for (PilotCertificationDTO certificationDTO:collects) {
            Integer userAccountId = certificationDTO.getUserAccountId();
            if (certificationDao.selectCompanyByUserId(userAccountId) < 1) {
                continue;
            }else {
                FlyingTeam flyingTeam  = certificationDao.selectCompanyNameByFlyingUserId(userAccountId);
                certificationDTO.setFlyingTeam(flyingTeam.getCompanyName());
                certificationDTO.setBackUserId(flyingTeam.getBackUserId());
            }
        }
        Integer backUserId = param.getBackUserId();
        if(backUserId == null) {
        collects = collects.stream().skip((pageNo - 1) * param.getPageSize()).limit(param.getPageSize()).
                collect(Collectors.toList());
        }else {
            collects = collects.stream().filter(collect -> backUserId.equals(collect.getBackUserId())).skip((pageNo - 1) * param.getPageSize()).limit(param.getPageSize()).
                    collect(Collectors.toList());
        }
        PageResult pageResult = PageResult.buildPage(pageNo, param.getPageSize(), pilotList.size(), collects);
        return pageResult;
    }

    @Override
    public ResultBody getPilotAuditSum() {
        PilotAuditSumVO pilotAuditSumVO = new PilotAuditSumVO();
        pilotAuditSumVO.setFailPilotAuditSum(certificationDao.getPilotAuditSum(2));
        pilotAuditSumVO.setPassPilotAuditSum(certificationDao.getPilotAuditSum(1));
        pilotAuditSumVO.setUnAuditedPilotSum(certificationDao.getPilotAuditSum(0));
        return ResultBody.success(pilotAuditSumVO);
    }


    @Override
    public ResultBody<PilotReasonDTO> backListReason() {
        List<PilotReasonDO> pilotReasonDOS = certificationDao.backListReason();
        List<PilotReasonDTO> collect = pilotReasonDOS.stream().map(PilotReasonDO::buildPilotReasonDTO).collect(Collectors.toList());
        return ResultBody.success(collect);
    }

    @Override
    public ResultBody updateRemark(PilotRemarkQO param, LoginSuccessDTO userLoginInfoFromRedis) {
        certificationDao.updateRemark(param);
        return ResultBody.success();
    }

    @Override
    public ResultBody updateAuditStatus(PilotAuditStatusQO param, LoginSuccessDTO userLoginInfoFromRedis) {
        int i = certificationDao.selectFirstApprove(param.getId());
        UserAccountDO userAccountDO = certificationDao.selectUserAccountId(param);
        extracted(param, i, userAccountDO);
        param.setOperatorUserId(userLoginInfoFromRedis.getUserAccountId());
        certificationDao.updateAuditStatus(param);

        //审核通过
        if (param.getAuditStatus() == 1) {
            String pilotApplyPhone = certificationDao.getPilotApplyPhone(param.getId());
            SmsUtil.sendPassPilotApply(pilotApplyPhone);

            // 审核通过，通过公众号发布消息通知
            WxMsgVO ws = new WxMsgVO();
            String unionId = userAccountDO.getUnionId();
            // 查询对应的openId(touser)
            String touser = userSubInfoDao.getUserSubInfoByUnionId(unionId).getOpenId();
            JSONObject jsonObject = spellMsg("飞手执照及能力认证","审核通过");
            ws.setTouser(touser);
            ws.setTemplateId("9qvgBhfW9yoQJY91iMfhrog8y5eZUPSbo9PLvQzS_vk");
            ws.setDataObject(jsonObject);
            wxService.sendSubTemplateMsg(ws);
        }

        PilotCertificationLogDO pilotCertificationLog = new PilotCertificationLogDO(userAccountDO.getId(), userLoginInfoFromRedis.getUserAccountId(), CertificationMessage.match(param.getAuditStatus()));
        certificationDao.insertPilotLog(pilotCertificationLog);
        SendCertificationMessage match = SendCertificationMessage.match(param.getAuditStatus());

        this.sendMsgFlyerInfoAuth(userAccountDO, match.getMessage(), param);
        return ResultBody.success();
    }


    private void extracted(PilotAuditStatusQO param, int i, UserAccountDO userAccountDO) {
        if (param.getAuditStatus() == 1 && i == 0) {
            //积分
            extracted(userAccountDO.getId());
        }
        if (param.getAuditStatus() == 1) {
            param.setIsFirstApprove(1);
        }
        if (param.getAuditStatus() == 2 && i == 0) {
            param.setIsFirstApprove(0);
        }
        if (param.getAuditStatus() == 2 && i == 1) {
            param.setIsFirstApprove(1);
        }
    }


    private void sendMsgFlyerInfoAuth(UserAccountDO userAccountDO, String message, PilotAuditStatusQO param) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");// 设置日期格式
        String date = df.format(new Date());
        JSONObject value1 = new JSONObject();
        value1.put("value", date);
        JSONObject value2 = new JSONObject();
        value2.put("value", userAccountDO.getOperatorUserName());
        JSONObject value3 = new JSONObject();
        value3.put("value", message);
        JSONObject value4 = new JSONObject();
        CertificationMessage match = CertificationMessage.match(param.getAuditStatus());
        //不通过原因
        String reason = null;
        if (param.getAuditStatus() == 1) {
            reason = userAccountDO.getUserName() + match.getMessage();
        }
        if (param.getAuditStatus() == 2) {
            PilotReasonDO pilotReasonDO = certificationDao.selectPilotReason(param.getReasonId());
            reason = pilotReasonDO.getReason();
        }
        value4.put("value", reason);
        JSONObject datad = new JSONObject();
        datad.put("date2", value1);
        datad.put("name3", value2);
        datad.put("phrase5", value3);
        datad.put("thing4", value4);
        AppletMsgVOS appletMsgVO = new AppletMsgVOS();
        appletMsgVO.setTouser(userAccountDO.getOpenId());
        appletMsgVO.setTemplate_id(WxMsgTemplete.FW_CHECK_FLYER_AUTH_INFO);
        appletMsgVO.setPage("pages/welcome/index");
        appletMsgVO.setData(datad);
        appletMsgVO.setMiniprogram_state(userSystemConstant.getMiniProgramState());
        appletMsgVO.setLang("zh_CN");
        sendUserAppletMsg(appletMsgVO);
    }

    private void extracted(Integer id) {
        UserPointsVO userPointsVO = new UserPointsVO(id, NumberOfUserPoints.match(2).getMessage());
        //积分
        UserPointsDO pointsDO = userPointsDao.selectUserPoints(userPointsVO.getUserAccountId());
        UserPointsDO points = null;
        if (pointsDO != null) {
            Integer totalPoints = userPointsVO.getTotalPoints();
            Integer totalPoints1 = pointsDO.getTotalPoints();
            totalPoints += totalPoints1;
            userPointsVO.setTotalPoints(totalPoints);
            points = new UserPointsDO(userPointsVO);
            userPointsDao.updatePoints(points);
        } else if (pointsDO == null) {
            points = new UserPointsDO(userPointsVO);
            userPointsDao.insertPoints(points);
        }
        UserPointsDetails userPointsDetails = new UserPointsDetails(id, NumberOfUserPoints.match(2).getMessage(), UserPointsEnum.match(2).getMessage());
        userPointsDetailsDao.insertPointsDetails(userPointsDetails);
    }

    /**
     * 小程序-用户端-发送消息
     */
    public ResultBody sendUserAppletMsg(AppletMsgVOS aMsg) {
        System.out.println("###########开始发送-小程序-用户端消息##########");
        String accessToken = null;
        try {
            accessToken = getStableAccessToken();
            System.out.println("accesstoken:" + accessToken);
        } catch (Exception e) {
            System.out.println("accessToken获取失败:" + e.getMessage());
            return ResultBody.error(ResultEnum.WX_ACCESS_TOKEN_ERROR.getResultCode(),
                    ResultEnum.WX_ACCESS_TOKEN_ERROR.getResultMsg() + e.getMessage());
        }
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
            aMsg.setData(WxApiUtilS.buildMsgJson(aMsg.getData()));
            System.out.println(aMsg);

            String param = JsonUtil.parseObjToJson(aMsg);
            System.out.println("参数：" + param);
            String result = HttpsOpenUtil.httpSendPost(url, param);
            JSONObject resJson = JSONObject.parseObject(result);
            if ("40001".equals(resJson.getString("errcode"))) {
                UserSystemConstant userSystemConstant = new UserSystemConstant();
                stringRedisTemplate.delete(createWxToken(userSystemConstant.getWxAppId()));
                System.out.println("accessToken二次获取失败:" + resJson);
                return ResultBody.error(ResultEnum.WX_ACCESS_TOKEN_ERROR.getResultCode(),
                        ResultEnum.WX_ACCESS_TOKEN_ERROR.getResultMsg() + resJson);
            }
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("系统异常：" + e.getMessage());
        }
        System.out.println("###########结束发送-小程序-消息##########");
        return ResultBody.success();
    }

    public String getStableAccessToken() {
        //token有效期为7200s，需要保存起来，先从redis中获取accessToken，没有则请求获取
        String accessToken = stringRedisTemplate.opsForValue().get(WxConstant.IUAV_MINI_PROGRAM_STABLE_ACCESS_TOKEN);
        if (org.apache.commons.lang.StringUtils.isBlank(accessToken)) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("grant_type", "client_credential");
            params.put("appid", userSystemConstant.getWxAppId());
            params.put("secret", userSystemConstant.getWxAppSecret());
            String stableAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/stable_token";
            String res = null;
            try {
                res = HttpsRequestUtil.httpsRequest(stableAccessTokenUrl, "POST", null, JSONObject.toJSONString(params));
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject tokenResult = JSONObject.parseObject(res);
            if (res.indexOf("access_token") == -1) {
                return null;
            }
            accessToken = tokenResult.getString("access_token");
            long expiresIn = tokenResult.getLong("expires_in");
            //保存进redis
            stringRedisTemplate.opsForValue().set(WxConstant.IUAV_MINI_PROGRAM_STABLE_ACCESS_TOKEN, accessToken, expiresIn, TimeUnit.SECONDS);
            return accessToken;
        }
        return accessToken;
    }

    /**
     * 生成微信api的access_token的key
     */
    public static String createWxToken(String wxAppid) {
        StringBuffer key = new StringBuffer();
        key.append("WX_ACCESS_TOKEN_");
        key.append(wxAppid);
        return key.toString();
    }


    @Override
    public PageResult backPilotLogList(PilotCertificationLogQO param, LoginSuccessDTO userLoginInfoFromRedis) {
        Integer pageNo = param.getPageNo();
        param.buildCurrentPage();
        List<PilotCertificationLogDO> logList = certificationDao.backPilotLogList(param);
        List<PilotCertificationLogDTO> collect = logList.stream().map(PilotCertificationLogDO::buildPlotCertificationLogDTO).collect(Collectors.toList());
        collect = collect.stream().skip((pageNo - 1) * param.getPageSize()).limit(param.getPageSize()).
                collect(Collectors.toList());
        PageResult pageResult = PageResult.buildPage(pageNo, param.getPageSize(), logList.size(), collect);
        return pageResult;
    }

    /**
     * 工作年限的计算/年龄
     *
     * @param pilotCertificationDOS
     */
    private void extracted(List<PilotCertificationDO> pilotCertificationDOS) {
        int ageByBirth = 0;
        int yearsOfWorking = 0;
        for (PilotCertificationDO pilotCertificationDO : pilotCertificationDOS) {
            Date birthday = pilotCertificationDO.getBirthday();
            ageByBirth = getAgeByBirth(birthday);
            pilotCertificationDO.setAge(ageByBirth);
            yearsOfWorking = getYearsOfWorking(pilotCertificationDO.getTimeOfApplication());
            Integer Working = pilotCertificationDO.getYearsOfWorking();
            yearsOfWorking = yearsOfWorking + Working;
            pilotCertificationDO.setYearsOfWorking(yearsOfWorking);
        }
    }


    public static int getYearsOfWorking(Date yearsOfWorking) {
        //获取当前时间
        Calendar cal = Calendar.getInstance();
        //获取出生日期的Calendar对象
        Calendar bir = Calendar.getInstance();
        bir.setTime(yearsOfWorking);
        //如果出生日期大于当前日期，则返回0
        if (cal.before(yearsOfWorking)) {
            return 0;
        }
        //取出当前年月日
        int nowYear = cal.get(Calendar.YEAR);
        int nowMonth = cal.get(Calendar.MONTH);
        int nowDay = cal.get(Calendar.DAY_OF_MONTH);

        //取出出生日期的年月日
        int birthYear = bir.get(Calendar.YEAR);
        int birthMonth = bir.get(Calendar.MONTH);
        int birthDay = bir.get(Calendar.DAY_OF_MONTH);

        //计算年份
        int age = nowYear - birthYear;

        //计算月份和日，看看是否大于当前月日，如果小于则减去一岁
        if (nowMonth < birthMonth || (nowMonth == birthMonth && nowDay < birthDay)) {
            age--;
        }
        return age;
    }

    public static int getAgeByBirth(Date birthday) {
        //获取当前时间
        Calendar cal = Calendar.getInstance();
        //获取出生日期的Calendar对象
        Calendar bir = Calendar.getInstance();
        bir.setTime(birthday);
        //如果出生日期大于当前日期，则返回0
        if (cal.before(birthday)) {
            return 0;
        }
        //取出当前年月日
        int nowYear = cal.get(Calendar.YEAR);
        int nowMonth = cal.get(Calendar.MONTH);
        int nowDay = cal.get(Calendar.DAY_OF_MONTH);

        //取出出生日期的年月日
        int birthYear = bir.get(Calendar.YEAR);
        int birthMonth = bir.get(Calendar.MONTH);
        int birthDay = bir.get(Calendar.DAY_OF_MONTH);

        //计算年份
        int age = nowYear - birthYear;

        //计算月份和日，看看是否大于当前月日，如果小于则减去一岁
        if (nowMonth < birthMonth || (nowMonth == birthMonth && nowDay < birthDay)) {
            age--;
        }
        return age;
    }

    @Override
    public PilotCertificationInteriorDTO interiorDetailPilot(Integer userAccountId) {
        PilotCertificationDO certificationDO = certificationDao.interiorDetailPilot(userAccountId);
        if (certificationDO == null) {
            return null;
        }
        int yearsOfWorking = 0;
        yearsOfWorking = getYearsOfWorking(certificationDO.getTimeOfApplication());
        Integer Working = certificationDO.getYearsOfWorking();
        yearsOfWorking = yearsOfWorking + Working;
        certificationDO.setYearsOfWorking(yearsOfWorking);

        certificationDO.setAge(getAgeByBirth(certificationDO.getBirthday()));
        PilotCertificationInteriorDTO pilotCertificationInteriorDTO = certificationDO.buildInterior();
        return pilotCertificationInteriorDTO;
    }

    @Override
    public ResultBody insertPilotJoinTeam(Integer pilotId,Integer backId) {
        certificationDao.insertPilotJoinTeam(pilotId,backId);
        return ResultBody.success();
    }


    /**
     * 查找属于自己飞手团队的飞手
     * @param param
     * @return {@link PageResult}
     */
    @Override
    public PageResult selectPilotListByTeam(PilotTeamQO param,Integer backId) {
        param.setBackId(backId);
        Integer pageNo = param.getPageNo();
        param.buildCurrentPage();
        List<PilotCertificationDO> pilotList = certificationDao.selectPilotListByTeam(param);
        extracted(pilotList);
        List<PilotCertificationDTO> collect = pilotList.stream().map(PilotCertificationDO::buildPilotCertificationDTO).collect(Collectors.toList());
        collect = collect.stream().skip((pageNo - 1) * param.getPageSize()).limit(param.getPageSize()).
                collect(Collectors.toList());
        PageResult pageResult = PageResult.buildPage(pageNo, param.getPageSize(), pilotList.size(), collect);
        return pageResult;
    }

    @Override
    public ResultBody selectPilotByPhone(String phoneNumber) {
        int i = certificationDao.selectPilotTeamByPhone(phoneNumber);
        if (1 == i) {
            return ResultBody.error("飞手已经加入团队");
        }else {
            PilotCertificationDO pilotCertificationDO = certificationDao.selectPilotByPhone(phoneNumber);
            if (pilotCertificationDO == null) {
                return ResultBody.error("没有查到");
            }
            PilotCertificationDTO pilotCertificationDTO = pilotCertificationDO.buildPilotCertificationDTO();
            return ResultBody.success(pilotCertificationDTO);
        }
    }


    @Override
    public ResultBody updatePilotStatus(Integer userId, Integer pilotStatus) {
        int i = certificationDao.updatePilotStatus(userId, pilotStatus);
        if(0==i) {
            return ResultBody.error("请不要重复操作");
        }else {
            return ResultBody.success();
        }
    }

    @Override
    public ResultBody selectCompanyInfoByPilotId(Integer pilotId) {
        CompanyInfoDO companyInfoDO = certificationDao.selectCompanyInfoByPilotId(pilotId,0);
        if (companyInfoDO == null) {
            return ResultBody.success();
        }
        CompanyInfoVO companyInfoVO = companyInfoDO.buildCompanyInfoVO();
        return ResultBody.success(companyInfoVO);
    }

    @Override
    public ResultBody deletePilotFromTeam(Integer pilotId) {
        certificationDao.deletePilotFromTeam(pilotId);
        return ResultBody.success();
    }

    @Override
    public List<Integer> selectPilotIdList(Integer backUserId) {
        Integer userAccountId = certificationDao.selectUserIdByBackUserId(backUserId);
        List<Integer> userIdList = certificationDao.selectPilotIdList(backUserId);
        userIdList.add(userAccountId);
        return userIdList;
    }

    public JSONObject spellMsg(String name, String result){
        JSONObject data=new JSONObject();

        //申请项目{{thing3.DATA}}
        JSONObject thing3=new JSONObject();
        thing3.put("value",name);
        data.put("thing3",thing3);

        //审核时间{{time6.DATA}}
        JSONObject time6=new JSONObject();
        time6.put("value",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        data.put("time6",time6);

        //审核结果{{thing5.DATA}}
        JSONObject thing5=new JSONObject();
        thing5.put("value",result);
        data.put("thing5",thing5);

        return data;
    }
}
