package cn.hnthyy.thmz.controller.mz;

import cn.hnthyy.thmz.Utils.ExcelUtil;
import cn.hnthyy.thmz.Utils.JsonUtil;
import cn.hnthyy.thmz.Utils.PyWbUtil;
import cn.hnthyy.thmz.Utils.TokenUtil;
import cn.hnthyy.thmz.comment.UserLoginToken;
import cn.hnthyy.thmz.entity.his.zd.ZdUnitCode;
import cn.hnthyy.thmz.entity.thmz.User;
import cn.hnthyy.thmz.enums.YesNoEnum;
import cn.hnthyy.thmz.pageDto.ZdUnitCodePageDto;
import cn.hnthyy.thmz.service.his.zd.ZdUnitCodeService;
import cn.hnthyy.thmz.vo.PageViewVo;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class UnitCodeController {
    @Autowired
    private ZdUnitCodeService zdUnitCodeService;

    /**
     * 查询科室字典列表
     * @param zdUnitCodePageDto
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/listUnitCode", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> listUnitCode(@RequestBody ZdUnitCodePageDto zdUnitCodePageDto) {
        Map<String, Object> resultMap = new HashMap<>();
        if(zdUnitCodePageDto==null){
            resultMap.put("code", -1);
            resultMap.put("message", "查询科室列表失败，参数为空");
            return resultMap;
        }
        ZdUnitCode zdUnitCode = zdUnitCodePageDto.getZdUnitCode();
        if(zdUnitCode==null){
            resultMap.put("code", -1);
            resultMap.put("message", "查询科室列表失败，参数为空");
            return resultMap;
        }
        if(StringUtils.isBlank(zdUnitCode.getName())){
            zdUnitCode.setName(null);
        }else {
            zdUnitCode.setName("%"+zdUnitCode.getName()+"%");
        }
        if(StringUtils.isBlank(zdUnitCode.getCode())){
            zdUnitCode.setCode(null);
        }
        if(StringUtils.isBlank(zdUnitCode.getPyCode())){
            zdUnitCode.setPyCode(null);
        }
        if(StringUtils.isBlank(zdUnitCode.getWbCode())){
            zdUnitCode.setWbCode(null);
        }
        log.info("查询科室字典，参数信息");
        PageViewVo pageViewVo = new PageViewVo(zdUnitCodePageDto.getPageIndex(), zdUnitCodePageDto.getPageSize(),zdUnitCodePageDto.getOrderByCase());
        int total = zdUnitCodeService.countZdUnitCode(zdUnitCode);
        pageViewVo.setTotal(total);
        pageViewVo.setData(zdUnitCodeService.queryZdUnitCodeWithPage(zdUnitCodePageDto));
        resultMap.put("code", 0);
        resultMap.put("message", "查询科室列表成功");
        resultMap.put("pageViewVO", pageViewVo);
        return resultMap;
    }



    /**
     * 查询科室字典列表 列表导出
     *
     * @return
     */
    @RequestMapping(value = "/excelUnitCode", method = {RequestMethod.GET})
    public Map<String, Object> excelUnitCode(@RequestParam("orderByCase") String orderByCase, @RequestParam("code") String code, @RequestParam("name") String name,
                                             @RequestParam("pyCode") String pyCode,@RequestParam("wbCode") String wbCode,@RequestParam("delFlag") Integer delFlag,
                                             @RequestParam("classCode") Integer classCode, HttpServletRequest request, HttpServletResponse response) {
        ZdUnitCode zdUnitCode=new ZdUnitCode();
        ZdUnitCodePageDto zdUnitCodePageDto = new ZdUnitCodePageDto();
        zdUnitCodePageDto.setOrderByCase(orderByCase);
        zdUnitCodePageDto.setZdUnitCode(zdUnitCode);
        zdUnitCode.setName(name);
        zdUnitCode.setCode(code);
        zdUnitCode.setPyCode(pyCode);
        zdUnitCode.setWbCode(wbCode);
        zdUnitCode.setDelFlag(delFlag);
        zdUnitCode.setClassCode(classCode);
        Map<String, Object> resultMap = new HashMap<>();
        if(zdUnitCode==null){
            resultMap.put("code", -1);
            resultMap.put("message", "查询科室列表失败，参数为空");
            return resultMap;
        }
        if(StringUtils.isBlank(zdUnitCode.getName())){
            zdUnitCode.setName(null);
        }else {
            zdUnitCode.setName("%"+zdUnitCode.getName()+"%");
        }
        if(StringUtils.isBlank(zdUnitCode.getCode())){
            zdUnitCode.setCode(null);
        }
        if(StringUtils.isBlank(zdUnitCode.getPyCode())){
            zdUnitCode.setPyCode(null);
        }
        if(StringUtils.isBlank(zdUnitCode.getWbCode())){
            zdUnitCode.setWbCode(null);
        }
        List<ZdUnitCode> zdUnitCodeList = zdUnitCodeService.queryZdUnitCode(zdUnitCodePageDto);
        if (zdUnitCodeList == null || zdUnitCodeList.size() == 0) {
            resultMap.put("code", -1);
            resultMap.put("message", "没有查询到符合条件的科室字典列表");
            return resultMap;
        }
        ExcelUtil.exportExcelForZdUnitCode(request, response, zdUnitCodeList);
        return null;
    }




    /**
     * 查询科室字典列表
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/allUnitCode", method = {RequestMethod.POST,RequestMethod.GET})
    public Map<String, Object> allUnitCode() {
        Map<String, Object> resultMap = new HashMap<>();
        log.info("查询科室字典，参数信息");
        resultMap.put("code", 0);
        resultMap.put("message", "查询科室列表成功");
        resultMap.put("data", zdUnitCodeService.queryAllDeptInCache());
        return resultMap;
    }



    /**
     * 查询所有门诊开放科室列表
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/allMzUnitCode", method = {RequestMethod.POST,RequestMethod.GET})
    public Map<String, Object> allMzUnitCode() {
        Map<String, Object> resultMap = new HashMap<>();
        log.info("查询门诊科室字典，参数信息");
        resultMap.put("code", 0);
        resultMap.put("message", "查询门诊科室列表成功");
        resultMap.put("data", zdUnitCodeService.queryAllMzDeptInCache());
        return resultMap;
    }



    /**
     * 查询所有未停用且需要挂号的门诊的科室
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/allMzGhUnitCode", method = {RequestMethod.POST,RequestMethod.GET})
    public Map<String, Object> allMzGhUnitCode() {
        Map<String, Object> resultMap = new HashMap<>();
        log.info("查询门诊科室字典，参数信息");
        resultMap.put("code", 0);
        resultMap.put("message", "查询所有未停用且需要挂号的门诊的科室成功");
        resultMap.put("data", zdUnitCodeService.queryAllMzGhDeptInCache());
        return resultMap;
    }


    /**
     * 查询所有的病区列表
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/allInpatientWard", method = {RequestMethod.GET})
    public Map<String, Object> allInpatientWard() {
        Map<String, Object> resultMap = new HashMap<>();
        log.info("查询所有的病区列表，参数信息");
        resultMap.put("code", 0);
        resultMap.put("message", "查询所有的病区列表成功");
        resultMap.put("data", zdUnitCodeService.queryAllInpatientWard());
        return resultMap;
    }


    /**
     * 获取小科室
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getSmallDeptByDept", method = {RequestMethod.GET})
    public Map<String, Object> getSmallDeptByDept(@RequestParam("code") String code) {
        Map<String, Object> resultMap = new HashMap<>();
        log.info("获取小科室，参数信息");
        resultMap.put("code", 0);
        resultMap.put("message", "获取小科室成功");
        resultMap.put("data", zdUnitCodeService.querySmallDeptByDept(code));
        return resultMap;
    }


    /**
     * 根据病区编码查询床号
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getBedNumByDept", method = {RequestMethod.GET})
    public Map<String, Object> getBedNumByDept(@RequestParam("code") String code) {
        Map<String, Object> resultMap = new HashMap<>();
        log.info("根据病区编码查询床号，参数信息");
        resultMap.put("code", 0);
        resultMap.put("message", "根据病区编码查询床号成功");
        resultMap.put("data", zdUnitCodeService.queryBedNumByDept(code));
        return resultMap;
    }






    /**
     * 保存科室字典
     * @param zdUnitCode
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/saveUnitCode", method = {RequestMethod.POST})
    public Map<String, Object> saveUnitCode(@RequestBody ZdUnitCode zdUnitCode,HttpServletRequest httpServletRequest) {
        log.info("保存科室字典，参数信息");
        Map<String, Object> resultMap = new HashMap<>();
        if(zdUnitCode==null){
            resultMap.put("code", -1);
            resultMap.put("message", "保存科室失败，参数为空");
            return resultMap;
        }
        if (checkZdUnitCode(zdUnitCode, resultMap)) {
            return resultMap;
        }
        String token = TokenUtil.getToken(httpServletRequest);
        if (StringUtils.isBlank(token)) {
            resultMap.put("code", -1);
            resultMap.put("message", "保存科室失败,用户Token不存在");
            return resultMap;
        }
        if("-1".equals(zdUnitCode.getMzClass())){
            zdUnitCode.setMzClass("");
        }
        DecodedJWT decodedJWT=TokenUtil.parseJWT(token);
        User tokenUser=(User)JsonUtil.jsontoObject(decodedJWT.getSubject(),User.class);
        zdUnitCode.setOpDate(new Date());
        zdUnitCode.setOpId(tokenUser.getUserIdCode());
        if(StringUtils.isNotBlank(zdUnitCode.getName())){
            zdUnitCode.setPyCode(PyWbUtil.toBigFirstChar(zdUnitCode.getName()));
            zdUnitCode.setWbCode(PyWbUtil.getWBCode(zdUnitCode.getName()));
        }
       try {
           if(StringUtils.isBlank(zdUnitCode.getOriginalCode())){
               //新增部门记录
               zdUnitCode.setDelFlag(YesNoEnum.NO.code);
               zdUnitCodeService.saveZdUnitCode(zdUnitCode);
               resultMap.put("code", 0);
               resultMap.put("message", "保存科室成功");
               return resultMap;
           }
           //修改部门记录
           zdUnitCodeService.modifyZdUnitCode(zdUnitCode);
           resultMap.put("code", 0);
           resultMap.put("message", "保存科室成功");
           return resultMap;
       }catch (Exception e){
           e.printStackTrace();
           resultMap.put("code", -1);
           resultMap.put("message", "保存科室失败,错误信息：【"+e.getMessage()+"】");
           log.error("保存科室失败,错误信息：[]",e.getMessage());
           return resultMap;
       }
    }

    /**
     * 检查是否有相同的科室编码或者科室名称
     * @param zdUnitCode
     * @param resultMap
     * @return
     */
    private boolean checkZdUnitCode(@RequestBody ZdUnitCode zdUnitCode, Map<String, Object> resultMap) {
        //停用操作不需要校验
        if(YesNoEnum.YES.code.equals(zdUnitCode.getDelFlag())){
            return false;
        }
        List<ZdUnitCode> zdUnitCodes=zdUnitCodeService.checkZdUnitCode(zdUnitCode);
        if(zdUnitCodes!=null && zdUnitCodes.size()>0){
            for (ZdUnitCode zu:zdUnitCodes){
                if(zu!=null){
                    if(StringUtils.isNotBlank(zdUnitCode.getCode()) && zdUnitCode.getCode().equals(zu.getCode())){
                        resultMap.put("code", -1);
                        resultMap.put("message", "保存科室失败，已经存在相同科室编号，请检查后重新输入");
                        return true;
                    }
                    if(StringUtils.isNotBlank(zdUnitCode.getName()) && zdUnitCode.getName().equals(zu.getName())){
                        resultMap.put("code", -1);
                        resultMap.put("message", "保存科室失败，已经存在相同科室名称，请检查后重新输入");
                        return true;
                    }
                    //新农合暂不校验
//                    if(StringUtils.isNotBlank(zdUnitCode.getXnhDeptCode()) && zdUnitCode.getXnhDeptCode().equals(zu.getXnhDeptCode())){
//                        resultMap.put("code", -1);
//                        resultMap.put("message", "保存科室失败，已经存在相同的新农合科室编号，请检查后重新输入");
//                        return true;
//                    }
//                    if(StringUtils.isNotBlank(zdUnitCode.getXnhDeptName()) && zdUnitCode.getXnhDeptName().equals(zu.getXnhDeptName())){
//                        resultMap.put("code", -1);
//                        resultMap.put("message", "保存科室失败，已经存在相同的新农合科室名称，请检查后重新输入");
//                        return true;
//                    }
                }
            }
        }
        return false;
    }


    /**
     * 按照科室编号查询科室字典
     * @param zdUnitCode
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getUnitCodeByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> getUnitCodeByCode(@RequestBody ZdUnitCode zdUnitCode) {
        Map<String, Object> resultMap = new HashMap<>();
        if(zdUnitCode==null || StringUtils.isBlank(zdUnitCode.getCode())){
            resultMap.put("code", -1);
            resultMap.put("message", "查询科室信息失败，参数为空");
            return resultMap;
        }
        log.info("查询科室字典，参数信息");
        ZdUnitCode reZdUnitCode = zdUnitCodeService.queryByCode(zdUnitCode.getCode());
        if(reZdUnitCode==null){
            resultMap.put("code", -1);
            resultMap.put("message", "查询科室信息失败，该编号的科室信息不存在");
            return resultMap;
        }
        resultMap.put("code", 0);
        resultMap.put("message", "查询科室信息成功");
        resultMap.put("data", reZdUnitCode);
        return resultMap;
    }


}
