package com.yinet.hbzwfw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yinet.common.utils.AesUtil;
import com.yinet.common.utils.bean.BeanUtils;
import com.yinet.common.utils.http.HttpUtils;
import com.yinet.common.utils.security.Md5Utils;
import com.yinet.hbzwfw.domain.HbzwfwUser;
import com.yinet.hbzwfw.domain.RegisterUser;
import com.yinet.hbzwfw.mapper.HbzwfwMapper;
import com.yinet.hbzwfw.service.HbzwfwService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 现场取号列表Service业务层处理
 *
 * @author yinet
 * @date 2019-09-02
 */
@Service
public class HbzwfwServiceImpl implements HbzwfwService {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
    @Autowired
    private HbzwfwMapper hbzwfwMapper;
    private static final String M = "男", F = "女";

    @Override
    public String regUser(String appmark, String appsecret, RegisterUser registerUser) {
        log.info("[  开始注册  ]");
        log.info("appmark = {} , appsecret = {}", appmark, appsecret);
        log.info("RegisterUser未格式化 = {}", registerUser.toString());
        String url = "http://www.hbzwfw.gov.cn/hbjis/front/register/personalRegister.do";
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String sign = Md5Utils.hash(appmark + appsecret + time);
        if (registerUser.getPapersnumber() != null && !registerUser.getPapersnumber().isEmpty()) {
            registerUser.setLoginname(registerUser.getPapersnumber());
            registerUser.setPwd(registerUser.getPapersnumber().substring(12, registerUser.getPapersnumber().length()));
            registerUser.setAge(getPersonAgeFromIdCard(registerUser.getPapersnumber()));
            registerUser.setPaperstype("1");
            if (registerUser.getName() == null || registerUser.getName().equals("")) {
                registerUser.setName(registerUser.getPapersnumber());
            }
        } else {
            return "未输入身份证号！";
        }
        if (M.equals(registerUser.getSex())) {
            registerUser.setSex("1");
        } else if (F.equals(registerUser.getSex())) {
            registerUser.setSex("0");
        }
        String json = "";
        try {
            ObjectMapper mapper = new ObjectMapper();
            json = mapper.writeValueAsString(registerUser);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (json == null || json.isEmpty() || json.length() < 1) {
            json = JSON.toJSONString(registerUser);
        }
        log.info("RegisterUser = {}", json);
        String params = AesUtil.encrypt(json, appsecret);
        String param = "appmark=" + appmark + "&time=" + time + "&sign=" + sign + "&params=" + params;
        String result = HttpUtils.sendGet(url, param);
        try {
            int count = hbzwfwMapper.selectCountByIdCard(registerUser.getPapersnumber());
            if (count == 0) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                HbzwfwUser user = new HbzwfwUser();
                BeanUtils.copyBeanProp(user, registerUser);
                user.setAppmark(appmark);
                user.setSubmitTime(new Date());
                if ("1".equals(registerUser.getSex())) {
                    user.setSex(M);
                } else if ("0".equals(registerUser.getSex())) {
                    user.setSex(F);
                }
                String retcode = jsonObject.getString("retcode");
                String message = jsonObject.getString("message");
                boolean isSuccess = retcode != null && retcode.equals("000000");
                user.setType(isSuccess ? "1" : "0");
                user.setMsg(message);
                int i = hbzwfwMapper.insertHbzwfwUser(user);
            } else {
                log.info("数据库中已存在此人 idCard = {} ", registerUser.getPapersnumber());
            }
        } catch (Exception e) {
            return result;
        }
        log.info("[  结束注册  ]");
        return result;
    }

    /**
     * 根据身份证号计算年龄
     *
     * @param pensonnelIdCard
     * @return
     */
    public String getPersonAgeFromIdCard(String pensonnelIdCard) {

        //截取身份证中出行人出生日期中的年、月、日
        Integer personYear = Integer.parseInt(pensonnelIdCard.substring(6, 10));
        Integer personMonth = Integer.parseInt(pensonnelIdCard.substring(10, 12));
        Integer personDay = Integer.parseInt(pensonnelIdCard.substring(12, 14));

        Calendar cal = Calendar.getInstance();
        // 得到当前时间的年、月、日
        Integer yearNow = cal.get(Calendar.YEAR);
        Integer monthNow = cal.get(Calendar.MONTH) + 1;
        Integer dayNow = cal.get(Calendar.DATE);

        // 用当前年月日减去生日年月日
        Integer yearMinus = yearNow - personYear;
        Integer monthMinus = monthNow - personMonth;
        Integer dayMinus = dayNow - personDay;

        Integer age = yearMinus; //先大致赋值

        if (yearMinus == 0) { //出生年份为当前年份
            age = 0;
        } else { //出生年份大于当前年份
            if (monthMinus < 0) {//出生月份小于当前月份时，还没满周岁
                age = age - 1;
            }
            if (monthMinus == 0) {//当前月份为出生月份时，判断日期
                if (dayMinus < 0) {//出生日期小于当前月份时，没满周岁
                    age = age - 1;
                }
            }
        }
        return age.toString();
    }


}
