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

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.StringUtils;
import com.boman.domain.VaccineInfoUser;
import com.boman.web.core.mapper.SyncMapper;
import com.boman.web.core.mapper.VaccineInfoUserMapper;
import com.boman.web.core.service.TableServiceCmdService;
import com.boman.web.core.service.vaccineInfo.IVaccineInfoUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author tjf
 * @Date: 2021/09/07/9:57
 */
@Service
public class VaccineInfoUserServiceImpl implements IVaccineInfoUserService {
    Logger LOGGER = LoggerFactory.getLogger(SyncMapper.class);
    @Resource
    private VaccineInfoUserMapper vaccineInfoUserMapper;
    @Resource
    private SyncMapper syncMapper;
    @Resource
    private TableServiceCmdService cmdService;

    /**
     * 批量删除用户接种疫苗信息
     *
     * @param ids 需要删除的用户接种疫苗信息ID
     * @return
     */
    @Override
    public int deleteVaccineInfoUserByIds(Long[] ids) {
        return vaccineInfoUserMapper.deleteVaccineInfoUserByIds(ids);
    }

    /**
     * 根据身份证号查询用户疫苗信息集合
     *
     * @param vaccineInfoUser
     * @return
     */
    @Override
    public List<VaccineInfoUser> selectInfoUserByIdCard(VaccineInfoUser vaccineInfoUser) {
        String idCard = vaccineInfoUser.getIdCard();
        List<VaccineInfoUser> list = new ArrayList();
        if (StringUtils.isNotBlank(idCard)) {
            list = vaccineInfoUserMapper.selectVaccineInfoUserByIdCard(idCard.trim());
        }
        return list;
    }

    /**
     * 省，市，区
     * 户籍地详细地址
     * 现居住地地址
     * 年龄
     * 是否完成
     * 剂次
     * 疫苗名称
     * 接种情况（是/否）
     * 人群分类
     */
  /*  public void syncData222() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取疫苗信息，每次处理1000条
        int counts = syncMapper.selectCount("select count(1) from vaccine_info");
        int count = 1;
//        int counts = 1;
        int times = counts / 1000;
        int startPagte = 0;
        int endPage = 1000;

        for (int i = 0; i < times + 1; i++) {
            List<JSONObject> vaccInfos = this.getVaccInfo(startPagte, endPage);
            // 身份证号码
            List<String> idCards = new ArrayList<>();
            Map<String, JSONObject> vannInfoMap = new HashMap<>();
            for (JSONObject vanninfo : vaccInfos) {
                String idcard = vanninfo.getString("id_card");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id_card", idcard);
                // 省
                jsonObject.put("province", "安徽省");
                // 市
                jsonObject.put("city", "安庆市");
                // 区
                jsonObject.put("region", "潜山市");
                vannInfoMap.put(idcard, jsonObject);
                idCards.add(idcard);
            }

            List<JSONObject> updateLists = new ArrayList<>();
            // 获取居住详细地址
            List<JSONObject> hujiInfos = this.getHujiInfo(idCards);
            for (JSONObject huji : hujiInfos) {
                String idcard = huji.getString("zjhm");
                JSONObject update = vannInfoMap.get(idcard);

                // 户籍地地址
                String hjdz = huji.getString("hjdxz");
                if (StringUtils.isNotEmpty(hjdz)) {
                    update.put("domicile", hjdz);
                }

                // 现居地详细地址
                String xxdz = huji.getString("akmdz");
                if (StringUtils.isNotEmpty(xxdz)) {
                    update.put("now_in", xxdz);
                }
            }
            int secCount = 1;
            // 查询疫苗是否完成
            for (String icsard : idCards) {
                JSONObject update = vannInfoMap.get(icsard);
                JSONObject userInfo = this.getvaccUser(icsard);
                if (userInfo != null) {
                    // 接种情况
                    update.put("is_vaccination", "是");
                    // 疫苗名称
                    update.put("vaccine_name", userInfo.getString("prod"));
                    // 剂次
                    update.put("jici", userInfo.getString("jici"));
                    // 最后一次接种时间
                    update.put("vaccination_time", userInfo.getString("v_date"));
                    // 最后一次接种地点
                    update.put("vaccination_place", userInfo.getString("vaccination_place"));
                    // 是否完成
                    String progress = this.getIsSuccess(userInfo);
                    update.put("progress", progress);
                    if (progress.equals("否")) {
                        // 下次应接时间
                        String nextTime = this.getTime(userInfo, sdf);
                        update.put("vaccine_time_next", nextTime);
                    }
                    // 生产厂家
                    update.put("manufacturer", userInfo.getString("manufacturer"));
                    // 联系方式
                    update.put("phone_num", userInfo.getString("phone_num"));
                    // 工作单位
                    update.put("work_unit", userInfo.getString("work_unit"));
                    // 年龄
                    String ageStr = userInfo.getString("csrq");
                    int age = getAge(ageStr, icsard);
                    update.put("age", age + "");

                    update.put("should_be", "否");
                } else {
                    update.put("progress", "否");
                    update.put("is_vaccination", "否");
                    update.put("should_be", "是");
                }

                System.out.println("secCount: " + secCount);
                secCount++;
            }
            this.updateData(new ArrayList(vannInfoMap.values()), count);
            count++;
            startPagte += 1000;
        }
    }*/


    @Override
    public List<JSONObject> syncData() throws Exception {
        List<JSONObject> datas = new ArrayList<>();
        try{


            List<JSONObject> jz = this.getvaccUser();
            Map<String, JSONObject> vannInfoMap = new HashMap<>();

            for (JSONObject jsonObject : jz) {
                String idCard = jsonObject.getString("idCard");
                JSONObject update = new JSONObject();
                update.put("id_card", idCard);
                vannInfoMap.put(idCard, update);
            }
            List<JSONObject> vaccInfos = this.getVaccInfo();
            for (JSONObject vanninfo : vaccInfos) {
                String idCard = vanninfo.getString("id_card");
                JSONObject update = vannInfoMap.get(idCard);
                String progress = vanninfo.getString("progress");
                if(update == null) {
                    update = new JSONObject();
                    update.put("id_card", idCard);
                    update.put("should_slow", "否");
                    update.put("should_be", "是");
                }else {
                    if("否".equals(progress)) {
                        update.put("should_slow", "是");
                    }else {
                        update.put("should_slow", "否");
                    }
                    update.put("should_be", "否");
                }
                System.out.println(update.toJSONString());
                datas.add(update);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return datas;
    }

    private List<JSONObject> getVaccInfo() {
        String sql = "select id_card,progress from vaccine_info";
        List<JSONObject> objs = syncMapper.selectBySql(sql);
        return objs;
    }

    private List<JSONObject> getHujiInfo(List<String> idCards) {
        if (idCards == null || idCards.size() <= 0) {
            return new ArrayList<>();
        }
        String sql = "select * from hj_hj where zjhm in (";
        String cond = "";
        for (String idCard : idCards) {
            cond += "'" + idCard + "'" + ",";
        }
        sql += cond.substring(0, cond.length() - 1) + ")";
        List<JSONObject> objs = syncMapper.selectBySql(sql);
        return objs;
    }

    /*private JSONObject getvaccUser(String idcard) {
        String sql = "SELECT id,`接种日期` as v_date,`生产厂家` as prod,`接种针次` as jici, "
                + " `人群分类` as crowd_classification, `接种单位` as vaccination_place," +
                " `电话号码` as phone_num , `出生日期` as 'csrq', `工作单位` as work_unit,  `生产厂家` as manufacturer"
                + " FROM ymjz WHERE `身份证` = '" + idcard + "' ORDER BY `接种日期` desc limit 1";
        List<JSONObject> objs = syncMapper.selectBySql(sql);
        if (objs != null && objs.size() > 0) {
            return objs.get(0);
        }
        return null;
    }*/

    private List<JSONObject> getvaccUser() {
        String sql = "SELECT `身份证` as idCard FROM ymjz ";
        List<JSONObject> objs = syncMapper.selectBySql(sql);

        return objs;
    }

    private String getTime(JSONObject userInfo, SimpleDateFormat sdf) throws Exception {
        String prod = userInfo.getString("prod");
        String time = userInfo.getString("v_date");
        Date preDate = sdf.parse(time);
        if (prod.equals("北京科兴中维")) {
            return newDate(preDate, 14, sdf);
        } else if (prod.equals("北京生物")) {
            return newDate(preDate, 21, sdf);
        } else if (prod.equals("兰州生物")) {
            return newDate(preDate, 21, sdf);
        } else if (prod.equals("深圳康泰")) {
            return newDate(preDate, 28, sdf);
        } else if (prod.equals("安徽智飞")) {
            return newDate(preDate, 28, sdf);
        }
        return "";
    }

    private String newDate(Date date, int day, SimpleDateFormat sdf) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);
        String newTime = sdf.format(calendar.getTime());
        return newTime;
    }

    private String getIsSuccess(JSONObject userInfo) {
        String prod = userInfo.getString("prod");
        String jici = userInfo.getString("jici");
        if (prod.equals("北京科兴中维")) {
            if (jici.equals("2")) {
                return "是";
            } else {
                return "否";
            }
        } else if (prod.equals("北京生物")) {
            if (jici.equals("2")) {
                return "是";
            } else {
                return "否";
            }
        } else if (prod.equals("兰州生物")) {
            if (jici.equals("2")) {
                return "是";
            } else {
                return "否";
            }
        } else if (prod.equals("深圳康泰")) {
            if (jici.equals("2")) {
                return "是";
            } else {
                return "否";
            }
        } else if (prod.equals("安徽智飞")) {
            if (jici.equals("3")) {
                return "是";
            } else {
                return "否";
            }
        }

        return "否";
    }

    /**
     * 获取年龄
     *
     * @param birthDayStr
     * @return
     * @throws Exception
     */
    public int getAge(String birthDayStr, String idcard) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDay = null;
        try {
            birthDay = sdf.parse(birthDayStr);
        } catch (Exception e) {
            System.out.println("idCard:" + idcard);
            return 0;
        }


        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

    public int updateData(List<JSONObject> dataList, int count) {

        for (JSONObject jsonObject : dataList) {
            try {
                LOGGER.info("已处理 count: {} \r\n", count);
                syncMapper.updateData(jsonObject, (String) jsonObject.getString("id_card"));
            } catch (Exception e) {
                LOGGER.info("错误数据: {} \r\n 新增的数据为: {}", jsonObject);
            }
        }
        return dataList.size();
    }
}
