package com.bonus.boot.manager.physical.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bonus.boot.manager.career.entity.CareerBean;
import com.bonus.boot.manager.manager.dao.UtilDao;
import com.bonus.boot.manager.manager.utils.*;
import com.bonus.boot.manager.physical.dao.EmployeeHealthCheckDao;
import com.bonus.boot.manager.physical.entity.EmployeeHealthCheckBean;
import com.bonus.boot.manager.physical.service.EmployeeHealthCheckService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;
import java.util.logging.SimpleFormatter;

@Service("employeeHealthCheckService")
public class EmployeeHealthCheckServiceImpl implements EmployeeHealthCheckService {

    @Resource
    private EmployeeHealthCheckDao dao;
    @Resource
    private UtilDao utilDao;

    @Override
    public List<EmployeeHealthCheckBean> getList(EmployeeHealthCheckBean o) {
        List<EmployeeHealthCheckBean> list = dao.getList(o);
        int rateNum = 0;
        double freeNum = 0.0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getPhysicalStatus().indexOf("已体检") != -1) {
                rateNum++;
            }
            freeNum += Float.parseFloat(list.get(i).getPhysicalFree());
        }
        String formattedNumber = "0.00";
        if (list.size() > 0) {
            DecimalFormat df = new DecimalFormat("0.00");
            formattedNumber = df.format((rateNum / (double) list.size()) * 100);
            if (".00".equals(formattedNumber)) {
                formattedNumber = "0.00";

            }
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setRate(formattedNumber + "%");
                list.get(i).setAllFree(freeNum + "");
            }
        } else {
            formattedNumber = "0.00";
        }
        return list;
    }


    @Override
    public String saveExcelInfo(HttpServletRequest request, MultipartFile file) {
        String res = "";
        try {
            if (StringHelper.isEmpty(UserUtil.getLoginUser().getHospitalId())) {
                return "当前操作人员不是医院人员,请更换医院人员账号!";
            }
            EmployeeHealthCheckBean entity = new EmployeeHealthCheckBean();
            entity.setPersonName(request.getParameter("personName"));
            entity.setIdNumber(request.getParameter("idNumber"));
            entity.setPersonName(request.getParameter("physicalTime"));

            List<JSONObject> lstObj = (List<JSONObject>) ImportNoPhotoExcelHelper.readExcel(file, EmployeeHealthCheckBean.class);
            List<EmployeeHealthCheckBean> list = new ArrayList<>();
            int i = 0;
            boolean active = false;
            String personName = "";
            String idNumber = "";
            String physicalTime = "";
            /**
             * 查询所有的体检库人员
             */
            List<CareerBean> allIdNumberList = dao.getAllIdNumber();
            if (lstObj != null && lstObj.size() > 0) {
                for (JSONObject obj : lstObj) {
                    i++;
                    EmployeeHealthCheckBean bean = new EmployeeHealthCheckBean();
                    personName = obj.getString("personName");
                    bean.setPersonName(personName);
                    if (StringHelper.isEmpty(personName)) {
                        res += "第" + i + "行姓名为空;";
                        active = true;
                    }
                    idNumber = obj.getString("idNumber");
                    bean.setIdNumber(idNumber);

                    System.out.println("===="+idNumber);
                    CareerBean compareBean = new CareerBean();
                    compareBean.setIdNumber(idNumber);
                    if (StringHelper.isEmpty(idNumber)) {
                        res += "第" + i + "行身份证号码为空;";
                        active = true;
                    } else if (!IdCardValidateUtil.checkIdCard(idNumber)) {
                        res += "第" + i + "行身份证号码有误;";
                        active = true;
                    } else if (!allIdNumberList.contains(compareBean)) {
                        res += "第" + i + "行该人员不在人员库;";
                        active = true;
                    }
//                    else if (utilDao.determineIfExists("pm_base_physical","idcard",idNumber,"") == 0){
//                        res += "第" + i + "行该人员不在人员库;";
//                        active = true;
//                    }
                    physicalTime = obj.getString("physicalTime");
                    bean.setPhysicalTime(physicalTime);
                    if (StringHelper.isEmpty(physicalTime)) {
                        res += "第" + i + "行体检时间为空;";
                        active = true;
                    }else if (physicalTime.indexOf("1900") != -1){
                        res += "第" + i + "行体检时间格式错误;";
                        active = true;
                    }
                    list.add(bean);
                }
            }
            if (active) {
                String[] arr = res.split(";");
                String code = "<pre>" +
                        "导入数据错误提示：<br/>";
                for (int j = 0; j < arr.length; j++) {
                    if (j == 0 || j % 2 == 0) {
                        if (arr[j].indexOf("姓名") != -1) {
                            code += arr[j] + ";\t\t\t";
                        } else {
                            code += arr[j] + ";\t\t";
                        }
                    } else {
                        code += arr[j] + "<br/>";
                    }
                }
                return code + "<pre>";
            }
            if (ListHelper.isNotEmpty(list)) {
                List<EmployeeHealthCheckBean> noAppointList = new ArrayList();
                for (int j = 0; j < list.size(); j++) {
                    /**
                     * 查询是否有预约
                     */
                        int code = dao.getIsExistAppoint(list.get(j).getIdNumber());
                    if (code > 0){
                        //有预约
                        list.get(j).setPhysicalStatus("已预约已体检");
                        dao.updateAppointStatus(list.get(j).getIdNumber(), "1");
                        dao.updateAppointCancel(list.get(j).getIdNumber(), "3");
                    }else {
                        //无预约
                        list.get(j).setPhysicalStatus("未预约已体检");
                        noAppointList.add(list.get(j));
                    }
                    dao.updateExcelData(list.get(j));
                }
                /**
                 * 查询本医院本周未体检人
                 */
                List<CareerBean> noCheckList = dao.getNoCheckLsit(getNowWeekBegin(),DateTimeHelper.getNowDate(),UserUtil.getLoginUser().getHospitalId());
                for (int k = 0; k < noCheckList.size(); k++) {
                    dao.updateNoCheckStatus(noCheckList.get(k).getId(), "2");
                }
                /**
                 * 对未预约已体检人员发送短信通知
                 */
                for (int z = 0; z < noAppointList.size(); z++) {
                    String idNumbers = noAppointList.get(z).getIdNumber();
                    String name = noAppointList.get(z).getPersonName();
                //    SendPhoneMessageUtil.SendPhoneMsg(dao.getPersonPhoneNumber(idNumbers),name+"您好,您的未预约已体检违规记录已记录在库，体检前请先登录平台预约，体检报告可在平台查看。");
                    System.out.println(idNumbers+"短信发送成功");
                }
            }
        } catch (Exception e) {
            res = "导入失败";
            e.printStackTrace();
        }
        return "导入成功";
    }


    public static String getNowWeekBegin() {
        Date dt = new Date();
        int this_day = dt.getDay () ;
        // 如果周日作为一周的最后一天
        int step_s2 = -this_day+1; // 上周日距离今天的天数（负数表示）
        if (this_day == 0) {
            step_s2 = -6; // 如果今天是周日
        }
        int step_m2 = 7 - this_day; // 周日距离今天的天数（负数表示）
        long thisTime = System.currentTimeMillis();
        Date monday = new Date(thisTime + (long) step_s2 * 24 *
                3600
                * 1000);
        Date sunday = new Date(thisTime + (long) step_m2 * 24 *
                3600
                * 1000);
        return getDateToString(monday,"yyyy-MM-dd");
    }
    /**
     * 日期转换为字符串格式
     * @param date Date类型
     * @param sFormate: "yyyy-MM-dd HH:mm:ss:SSSS"
     * @return 字符串
     */
    public static String getDateToString(Date date, String
            sFormate) {
        SimpleDateFormat dateFormat = new
                SimpleDateFormat(sFormate);
        return dateFormat.format(date);
    }

    private static Map<String, String> getNextWeek(String queryDate) throws
            ParseException {
        Map<String, String> dateMap = new HashMap<String, String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(sdf.parse(queryDate));
        cal2.setTime(sdf.parse(queryDate));
        int dayWeek = cal1.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (dayWeek == 1) {
            cal1.add(Calendar.DAY_OF_MONTH, 1);
            cal2.add(Calendar.DAY_OF_MONTH, 7);
        } else {
            cal1.add(Calendar.DAY_OF_MONTH, 1 - dayWeek + 8);
            cal2.add(Calendar.DAY_OF_MONTH, 1 - dayWeek + 14);
        }
        // 下周 周一日期
        String beginDateNext = sdf.format(cal1.getTime());
        // 下周 周日日期
        String endDateNext = sdf.format(cal2.getTime());
        dateMap.put("beginDateNext", beginDateNext);
        dateMap.put("endDateNext", endDateNext);
        return dateMap;
    }
}
