package com.emr.service.ImportExcel;

import com.emr.dao.CommomMapper;
import com.emr.dao.ExportTaskMapper;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.entity.ExportTask;
import com.emr.entity.ExportTaskDetails;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
import com.emr.entity.approve.Emr_Apply_Approve;
import com.emr.vo.commomSearch.CommomVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ProjectName:importExcelJudgeMethod
 * @Description:导入excel的需要判断字段的集中类
 * @Param
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/10/12 9:16
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/10/12 9:16
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Component
@Transactional
public class ImportExcelJudgeMethod {
    //公共批量插入方法
    private static final String SIMPLEINSERT = "SimpleInsert";
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private Emr_Apply_ApproveMapper applyApproveMapper;

    @Autowired
    private ExportTaskMapper exportTaskMapper;

    /****************************************导入公共判断******************************************************/
    /**
     * 批量插入
     * */
    public int SimpleInsert(List<Object> list,String mapperName)throws Exception{
        //注入判断方法集中类
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        //获取类实例
        Object bean = wac.getBean(mapperName);
        Class<?>  cls = bean.getClass();
        //获取执行方法
        Method method = cls.getDeclaredMethod(SIMPLEINSERT,List.class);
        return (int)method.invoke(bean,list);
    }

    /**
     * 批量插入
     */
    public int SimpleInsert1(List<Object> list, String mapperName, String value) throws Exception {

        int t = 0;
        String taskName = value.replaceAll(".xls", "").replaceAll(".xlsx", "");
        ExportTask task = null;
        task = exportTaskMapper.getExportTaskByName(taskName);


        if (list != null && list.size() > 0) {
            ExportTask exportTask = new ExportTask();
            exportTask.setTaskName(taskName);
            exportTask.setState(0);
            exportTask.setCreateDate(new Date());

            if (ObjectUtils.isEmpty(task)) {
                //任务清单主表插入
                exportTaskMapper.insertSelective(exportTask);
                //根据任务名称查找任务清单id
                task = exportTaskMapper.getExportTaskByName(taskName);
            }else{
                exportTask.setTaskId(task.getTaskId());
                exportTaskMapper.updateByPrimaryKeySelective(exportTask);

            }

            for (int i = 0; i < list.size(); i++) {
                ExportTaskDetails exportTaskDetails = (ExportTaskDetails) list.get(i);
                exportTaskDetails.setTaskid(task.getTaskId());
            }
            //注入判断方法集中类
            WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
            //获取类实例
            Object bean = wac.getBean(mapperName);
            Class<?> cls = bean.getClass();
            //获取执行方法
            Method method = cls.getDeclaredMethod(SIMPLEINSERT, List.class);
            t = (int) method.invoke(bean, list);

        }
        return t;
    }

    /****************************************自定义验证记录合法******************************************************/
    public  String judgeRecord(String fieldName, String value, Field f, Object object, String head)throws Exception{
        Emr_Apply_Approve applyApprove = (Emr_Apply_Approve)object;
        List<String> patientIdList = commomMapper.selectPatientIdByAdmissTimesAndInpatientNoAndName(applyApprove.getAdmissTimes(), applyApprove.getInpatientNo(), applyApprove.getName(),null,null);
        if(null != patientIdList && !patientIdList.isEmpty()){
            if(patientIdList.size() == 1){
                HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
                Power_User powerUser = (Power_User)request.getSession().getAttribute("CURRENT_USER");
                applyApprove.setPatientId(patientIdList.get(0));
                String patientId = "'" + applyApprove.getPatientId() + "'";
                List<Emr_Apply_Approve> approves = applyApproveMapper.selectPatientIdsByUserAndApplyStatus(powerUser.getUserName(),patientId,applyApprove.getApplyType());
                if(null != approves && !approves.isEmpty()){
                    return "该病案另一个申请还处于有效期，无须重复申请!";
                }
                List<CommomVo> commomVos = commomMapper.selectAllByPatients("'"+applyApprove.getPatientId()+"'");
                BeanUtils.copyProperties(commomVos.get(0),applyApprove);

                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                applyApprove.setDisDate(fmt.parse(commomVos.get(0).getDisDate()));
                ImportExcelUtil.newInstance("emr_Apply_ApproveMapper",applyApprove, Emr_Apply_Approve.class);
            }else{
                return "查询结果不唯一,符合条件共计"+patientIdList.size()+"条";
            }
        }else{
            return "查询无该病案!";
        }
        return "";
    }
    /****************************************单元格自定义验证******************************************************/
    /***
     * 验证批量申请的病案号
     * */
    public  String judgeInpatientNo(String fieldName, String value, Field f, Object object, String head)throws Exception{
        if("inpatientNo".equals(fieldName)){
            //判断长度
            if(value.length() > 30){
                return  "\""+head+"\"输入内容太长,长度为30";
            }
            if(StringUtils.isNotBlank(value)){
                List<CommomVo> commomVos = commomMapper.selectCommomByInpatientNo(value);
                if(null != commomVos && !commomVos.isEmpty()){
                    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
                    Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                    Field applyTypeField = object.getClass().getDeclaredField("applyType");
                    applyTypeField.setAccessible(true);
                    String applyType = (String)applyTypeField.get(object);
                    Integer applyTypeInt = null;
                    if(StringUtils.isNotBlank(applyType)){
                        applyTypeInt = Integer.valueOf(applyType);
                    }
                    //查询审核通过且未过期
                    List<Emr_Apply_Approve> approves = applyApproveMapper.selectPatientIdsByUser(user.getUserName(), null, applyTypeInt);
                    //定义是否存在审核通过且未过期的inpatientId
                    boolean flag = false;
                    if(null != approves && !approves.isEmpty()){
                        for (Emr_Apply_Approve approve : approves) {
                            String inpatientNo = approve.getInpatientNo();
                            if (StringUtils.isNotBlank(inpatientNo) && inpatientNo.equals(value)) {
                                flag = true;
                                break;
                            }
                        }
                    }
                    if(!flag){
                        f.set(object,value);
                        CommomVo commomVo = commomVos.get(0);
                        Field patientIdField = object.getClass().getDeclaredField("patientId");
                        patientIdField.setAccessible(true);
                        patientIdField.set(object,commomVo.getPatientId());
                        Field admissIdField = object.getClass().getDeclaredField("admissId");
                        admissIdField.setAccessible(true);
                        admissIdField.set(object,commomVo.getAdmissId());
                    }else{
                        return "\""+head+"\"审核通过且未过期,";
                    }
                }else{
                    return "\""+head+"\"不存在,";
                }
            }else{
                return "\""+head+"\"不能为空,";
            }
        }
        return "";
    }

    /***
     * 验证批量申请的姓名
     * */
    public  String judgeName(String fieldName, String value, Field f, Object object, String head)throws Exception{
        if("name".equals(fieldName)){
            //判断长度
            if(value.length() > 30){
                return  "\""+head+"\"输入内容太长,长度为30";
            }
            if(StringUtils.isBlank(value)){
                return "\""+head+"\"不能为空,";
            }
            f.set(object,value);
        }
        return "";
    }
    /***
     * 验证批量申请的病案号
     * */
    public  String judgeInpatientNo1(String fieldName, String value, Field f, Object object, String head)throws Exception{
        if("inpatientNo".equals(fieldName)){
            //判断长度
            if(value.length() > 30){
                return  "\""+head+"\"输入内容太长,长度为30";
            }
            if(StringUtils.isBlank(value)){
                return "\""+head+"\"不能为空,";
            }
            f.set(object,value);
        }
        return "";
    }
    /***
     * 验证批量申请的住院次数
     * */
    public  String judgeAdmissTimes(String fieldName, String value, Field f, Object object, String head)throws Exception{
        if("admissTimes".equals(fieldName)){
            //判断长度
            if(value.length() > 3){
                return  "\""+head+"\"输入内容太长,长度为3";
            }
            if(StringUtils.isBlank(value)){
                return "\""+head+"\"不能为空,";
            }
            if(StringUtils.isNotBlank(value)){
                Class<?> filedType = f.getType();
                String typeName = filedType.getName();
                if("java.lang.Short".equals(typeName)){
                    f.set(object,Short.valueOf(value));
                }else{
                    f.set(object,value);
                }
            }
        }
        return "";
    }

    /**
     * 验证taskId
     *
     * @param fieldName
     * @param value
     * @param f
     * @param object
     * @param head
     * @return
     */
    public String judgeTaskId(String fieldName, String value, Field f, Object object, String head) throws Exception {

        if ("taskid".equals(fieldName)) {
            if (StringUtils.isBlank(value)) {
                return "\"" + head + "\"不能为空,";
            }
            f.set(object, Integer.valueOf(value));
        }

        return "";

    }

    /**
     * 验证病案号
     *
     * @param fieldName
     * @param value
     * @param f
     * @param object
     * @param head
     * @return
     */
    public String judgeInpNo(String fieldName, String value, Field f, Object object, String head) throws Exception {

        if ("inpno".equals(fieldName)) {
            if (StringUtils.isBlank(value)) {
                return "\"" + head + "\"不能为空,";
            }
            //判断长度
            if (value.length() > 30) {
                return "\"" + head + "\"输入内容太长,长度为30,";
            }
            //判断当前行病案号是否已经存在
            /*ExportTaskDetails exportTaskDetails = exportTaskDetailsMapper.selectExportTaskDetailsByInpNo(value);
            if (exportTaskDetails != null) {
                return "\"" + head + "\"已存在,";
            }*/

            f.set(object, value);
        }
        return "";
    }

    /**
     * 验证出院日期
     *
     * @param fieldName
     * @param value
     * @param f
     * @param object
     * @param head
     * @return
     */
    public String judgeDischargeDateTime(String fieldName, String value, Field f, Object object, String head) throws Exception {

        if ("dischargedatetime".equals(fieldName)) {
            if (StringUtils.isBlank(value)) {
                return "\"" + head + "\"不能为空,";
            }

            f.set(object, DateUtil.parseYYYYMMDDDate(value));
        }
        return "";
    }
}
