package com.boman.web.core.service.vaccineInfo.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.DateUtils;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.domain.SysDictData;
import com.boman.web.core.domain.VaccineInfoOperation;
import com.boman.web.core.domain.VaccineInfoUser;
import com.boman.web.core.mapper.VaccineInfoOperationMapper;
import com.boman.web.core.mapper.VaccineInfoUserMapper;
import com.boman.web.core.service.vaccineInfo.IVaccineInfoService;

import org.springframework.stereotype.Service;
import com.boman.web.core.mapper.VaccineInfoMapper;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 疫苗信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-09-05
 */
@Service
public class VaccineInfoServiceImpl implements IVaccineInfoService {

    private static final String INSERT = "insert";
    private static final String EDIT = "edit";
    private static final String DELETE = "delete";

    @Resource
    private VaccineInfoMapper vaccineInfoMapper;
    @Resource
    private VaccineInfoOperationMapper vaccineInfoOperationMapper;
    @Resource
    private VaccineInfoUserMapper vaccineInfoUserMapper;

    /**
     * 查询疫苗信息
     *
     * @param id 疫苗信息ID
     * @return 疫苗信息
     */
    @Override
    public VaccineInfoOperation selectVaccineInfoById(Long id) {
        VaccineInfoOperation vaccineInfoOperation = vaccineInfoMapper.selectVaccineInfoById(id);
        String vaccineName = vaccineInfoOperation.getVaccineName();
        if (StringUtils.isNotBlank(vaccineName)){
            String dictValue = vaccineInfoMapper.selectSysDictDataByDictLabel(vaccineName);
            vaccineInfoOperation.setDictValue(dictValue);
        }
        return vaccineInfoOperation;
    }

    /**
     * 查询疫苗信息列表
     *
     * @param vaccineInfoOperation 疫苗信息
     * @return 疫苗信息
     */
    @Override
    public List<VaccineInfoOperation> selectVaccineInfoList(VaccineInfoOperation vaccineInfoOperation) {
        Map<String, Object> params = vaccineInfoOperation.getParams();
        String age = params.get("age").toString();
        if (StringUtils.isNotBlank(age)){
            String[] split = age.split("-");
            params.put("startAge",split[0]);
            if (split.length == 2){
                params.put("endAge",split[1]);
            }
        }
        //疫苗名称
        String vaccineName = vaccineInfoOperation.getVaccineName();
        //计次
        String jici = vaccineInfoOperation.getJici();
        //接种时间
        Date vaccinationTime = vaccineInfoOperation.getVaccinationTime();
        //接种地点
        String vaccinationPlace = vaccineInfoOperation.getVaccinationPlace();
        List<String> idCardS = new ArrayList<>();
        if (StringUtils.isNotBlank(vaccineName) || StringUtils.isNotBlank(jici) || vaccinationTime != null || StringUtils.isNotBlank(vaccinationPlace)){
            VaccineInfoUser vaccineInfoUser = new VaccineInfoUser();
            vaccineInfoUser.setVaccineName(vaccineName);
            vaccineInfoUser.setJici(jici);
            vaccineInfoUser.setVaccinationTime(vaccinationTime);
            vaccineInfoUser.setVaccinationPlace(vaccinationPlace);
            idCardS = vaccineInfoUserMapper.selectIdCardList(vaccineInfoUser);
            vaccineInfoOperation.setIdCardS(idCardS);
        }
        return vaccineInfoMapper.selectVaccineInfoList(vaccineInfoOperation);
    }

    /**
     * 新增疫苗信息
     *
     * @param vaccineInfoOperation 疫苗信息
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public int insertVaccineInfo(VaccineInfoOperation vaccineInfoOperation) {
        // 疫苗信息
//        genNowIn(vaccineInfoOperation);
        vaccineInfoOperation.setCreateTime(DateUtils.getNowDate());
        int info = vaccineInfoMapper.insertVaccineInfo(vaccineInfoOperation);
        //提取出用户接种疫苗信息列表
        List<VaccineInfoUser> vaccineInfoUserList = vaccineInfoOperation.getVaccineInfoUserList();
        if (vaccineInfoUserList != null && vaccineInfoUserList.size() > 0){
            for (VaccineInfoUser vaccineInfoUser : vaccineInfoUserList) {
                vaccineInfoUser.setIdCard(vaccineInfoOperation.getIdCard());
                vaccineInfoUser.setCreateBy(SecurityUtils.getUsername());
                vaccineInfoUserMapper.insertVaccineInfoUser(vaccineInfoUser);
            }
        }

        // 疫苗信息新增操作记录
        vaccineInfoOperation.setOperationType(INSERT);
        vaccineInfoOperation.setVaccineInfoId(vaccineInfoOperation.getId());
        vaccineInfoOperation.setCreateBy(SecurityUtils.getUsername());
        vaccineInfoOperationMapper.insertVaccineInfoOperation(vaccineInfoOperation);

        return info;
    }

    /**
     * 修改疫苗信息
     *
     * @param vaccineInfo 疫苗信息
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public int updateVaccineInfo(VaccineInfoOperation vaccineInfo) {
        vaccineInfo.setUpdateTime(DateUtils.getNowDate());
//        genNowIn(vaccineInfo);
        int info = vaccineInfoMapper.updateVaccineInfo(vaccineInfo);
        List<VaccineInfoUser> vaccineInfoUserList = vaccineInfo.getVaccineInfoUserList();
        if (vaccineInfoUserList != null && vaccineInfoUserList.size() > 0){
            for (VaccineInfoUser vaccineInfoUser : vaccineInfoUserList) {
                if (vaccineInfoUser.getId() != null){
                    vaccineInfoUser.setUpdateBy(SecurityUtils.getUsername());
                    vaccineInfoUserMapper.updateVaccineInfoUser(vaccineInfoUser);
                }else {
                    vaccineInfoUser.setIdCard(vaccineInfo.getIdCard());
                    vaccineInfoUser.setCreateBy(SecurityUtils.getUsername());
                    vaccineInfoUserMapper.insertVaccineInfoUser(vaccineInfoUser);
                }
            }
        }
        // 疫苗信息新增操作记录
        vaccineInfo.setOperationType(EDIT);
        vaccineInfo.setCreateTime(new Date());
        vaccineInfo.setCreateBy(SecurityUtils.getUsername());
        vaccineInfo.setVaccineInfoId(vaccineInfo.getId());
        vaccineInfoOperationMapper.insertVaccineInfoOperation(vaccineInfo);
        return info;
    }

    /**
     * 批量删除疫苗信息
     *
     * @param ids 需要删除的疫苗信息ID
     * @return 结果
     */
    @Override
    public int deleteVaccineInfoByIds(Long[] ids) {
        List<VaccineInfoOperation> vaccineInfos = vaccineInfoMapper.selectVaccineInfoByIds(ids);
        String userName = SecurityUtils.getUsername();
        for(VaccineInfoOperation vaccineInfoOperation : vaccineInfos) {
            // 疫苗信息新增操作记录
            vaccineInfoOperation.setOperationType(DELETE);
            vaccineInfoOperation.setCreateTime(new Date());
            vaccineInfoOperation.setCreateBy(userName);
            vaccineInfoOperation.setVaccineInfoId(vaccineInfoOperation.getId());
            vaccineInfoOperationMapper.insertVaccineInfoOperation(vaccineInfoOperation);
        }

        return vaccineInfoMapper.deleteVaccineInfoByIds(ids);
    }

    /**
     * 删除疫苗信息信息
     *
     * @param id 疫苗信息ID
     * @return 结果
     */
    @Override
    public int deleteVaccineInfoById(Long id) {
        VaccineInfoOperation vaccineInfo = vaccineInfoMapper.selectVaccineInfoById(id);
        vaccineInfo.setVaccineInfoId(id);
        vaccineInfo.setCreateBy(SecurityUtils.getUsername());
        vaccineInfo.setCreateTime(new Date());
        vaccineInfo.setOperationType(DELETE);
        return vaccineInfoMapper.deleteVaccineInfoById(id);
    }

    /**
     * 根据身份证号查询用户信息
     * @param vaccineInfo
     * @return
     */
    @Override
    public VaccineInfoOperation findHjInfo(VaccineInfoOperation vaccineInfo) {
        VaccineInfoOperation hjInfo = vaccineInfoMapper.findHjInfo(vaccineInfo);
        if (hjInfo == null){
            String idCard = vaccineInfo.getIdCard();
            if (StringUtils.isNotBlank(idCard)){
                //根据身份证提取出生日和性别,年龄
                String sex = getSex(idCard);
                Integer age = getAge(idCard);
                String birthday = getBirthday(idCard);
                vaccineInfo.setAge(age);
                vaccineInfo.setGender(sex);
                vaccineInfo.setBirthday(birthday);
                return vaccineInfo;
            }
        }
        return hjInfo;
    }


    /**
     * 15位身份证号
     */
    private static final Integer FIFTEEN_ID_CARD=15;
    /**
     * 18位身份证号
     */
    private static final Integer EIGHTEEN_ID_CARD=18;
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 根据身份证号获取性别
     * @param IDCard
     * @return
     */
    public static String getSex(String IDCard){
        String sex ="";
        if (StringUtils.isNotBlank(IDCard)){
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD){
                if (Integer.parseInt(IDCard.substring(14, 15)) % 2 == 0) {
                    sex = "女";
                } else {
                    sex = "男";
                }
                //18位身份证号
            }else if(IDCard.length() == EIGHTEEN_ID_CARD){
                // 判断性别
                if (Integer.parseInt(IDCard.substring(16).substring(0, 1)) % 2 == 0) {
                    sex = "女";
                } else {
                    sex = "男";
                }
            }
        }
        return sex;
    }


    /**
     * 根据身份证号获取年龄
     * @param IDCard
     * @return
     */
    public static Integer getAge(String IDCard){
        Integer age = 0;
        Date date = new Date();
        if (StringUtils.isNotBlank(IDCard)&& isValid(IDCard)){
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD){
                // 身份证上的年份(15位身份证为1980年前的)
                String uyear = "19" + IDCard.substring(6, 8);
                // 身份证上的月份
                String uyue = IDCard.substring(8, 10);
                // 当前年份
                String fyear = format.format(date).substring(0, 4);
                // 当前月份
                String fyue = format.format(date).substring(5, 7);
                if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) {
                    age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
                    // 当前用户还没过生
                } else {
                    age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
                }
                //18位身份证号
            }else if(IDCard.length() == EIGHTEEN_ID_CARD){
                // 身份证上的年份
                String year = IDCard.substring(6).substring(0, 4);
                // 身份证上的月份
                String yue = IDCard.substring(10).substring(0, 2);
                // 当前年份
                String fyear = format.format(date).substring(0, 4);
                // 当前月份
                String fyue = format.format(date).substring(5, 7);
                // 当前月份大于用户出身的月份表示已过生日
                if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) {
                    age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
                    // 当前用户还没过生日
                } else {
                    age = Integer.parseInt(fyear) - Integer.parseInt(year);
                }
            }
        }
        return age;
    }



    /**
     * 身份证验证
     * @param id 号码内容
     * @return 是否有效
     */
    public static boolean isValid(String id){
        Boolean validResult = true;
        //校验长度只能为15或18
        int len = id.length();
        if (len != FIFTEEN_ID_CARD && len != EIGHTEEN_ID_CARD){
            validResult = false;
        }
        //校验生日
        if (!validDate(id)){
            validResult = false;
        }
        return validResult;
    }

    /**
     * 校验生日
     * @param id
     * @return
     */
    private static boolean validDate(String id)
    {
        try
        {
            String birth = id.length() == 15 ? "19" + id.substring(6, 12) : id.substring(6, 14);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date birthDate = sdf.parse(birth);
            if (!birth.equals(sdf.format(birthDate))){
                return false;
            }
        }
        catch (ParseException e)
        {
            return false;
        }
        return true;
    }
    /**
     * 获取出生日期  yyyy年MM月dd日
     * @param IDCard
     * @return
     */
    public static String getBirthday(String IDCard){
        String birthday="";
        String year="";
        String month="";
        String day="";
        if (StringUtils.isNotBlank(IDCard)){
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD){
                // 身份证上的年份(15位身份证为1980年前的)
                year = "19" + IDCard.substring(6, 8);
                //身份证上的月份
                month = IDCard.substring(8, 10);
                //身份证上的日期
                day= IDCard.substring(10, 12);
                //18位身份证号
            }else if(IDCard.length() == EIGHTEEN_ID_CARD){
                // 身份证上的年份
                year = IDCard.substring(6).substring(0, 4);
                // 身份证上的月份
                month = IDCard.substring(10).substring(0, 2);
                //身份证上的日期
                day=IDCard.substring(12).substring(0,2);
            }
            birthday=year+"-"+month+"-"+day;
        }
        return birthday;
    }

    private void genNowIn(VaccineInfoOperation vaccineInfo) {
        // 现居地
        String nowIn = vaccineInfo.getProvince() + vaccineInfo.getCity() + vaccineInfo.getRegion();
        nowIn += vaccineInfo.getNowIn();
        vaccineInfo.setNowIn(nowIn);

        // 户籍
        String domic = vaccineInfo.getVillageTowns() + vaccineInfo.getVillage() + vaccineInfo.getVillagerGroup() + vaccineInfo.getDomicile();
        vaccineInfo.setDomicile(domic);
    }
}
