package com.jpsoft.shinestar.modules.mobile.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.business.dto.MedicalPersonDTO;
import com.jpsoft.shinestar.modules.business.dto.MedicalRecordsAddDTO;
import com.jpsoft.shinestar.modules.business.dto.MedicalRecordsDTO;
import com.jpsoft.shinestar.modules.business.entity.MedicalPerson;
import com.jpsoft.shinestar.modules.business.entity.MedicalRecords;
import com.jpsoft.shinestar.modules.business.service.MedicalPersonService;
import com.jpsoft.shinestar.modules.business.service.MedicalRecordsService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/mobile/medicalRecordsApi")
public class MedicalRecordsApiController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private MedicalPersonService medicalPersonService;

    @Autowired
    private MedicalRecordsService medicalRecordsService;

    @ApiOperation(value="获取长者信息")
    @PostMapping("getElderInfo")
    public MessageResult<Map> getElderInfo(String token, @RequestAttribute String subject) {
        MessageResult<Map> msgResult = new MessageResult<>();

        try {

            Map<String,Object> map = new HashMap<>();

            PersonInfo personInfo = personInfoService.get(Long.parseLong(subject));

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());

            //是否有关联长者
            if (StringUtils.isNotEmpty(personPopedom.getRelationPopedom())) {
                personPopedom = personPopedomService.get(personPopedom.getRelationPopedom());
            }

            PersonInfo person = personInfoService.get(personPopedom.getPersonId());

            map.put("id",person.getId());
            map.put("popedomId",personPopedom.getId());
            map.put("name",person.getName());
            String gender;
            if(StringUtils.isNotEmpty(person.getSex())) {
                if ("1".equals(person.getSex())) {
                    gender = "男";
                } else {
                    gender = "女";
                }
            }
            else{
                gender = "未知";
            }

            String age = "未知";

            MedicalPerson medicalPerson = medicalPersonService.findByPersonId(person.getId());

            if(medicalPerson!=null){
                Date birthDate = medicalPerson.getBirthDate();
                int ageInt = getAge(birthDate);
                age = String.valueOf(ageInt) + "岁";

                if(medicalPerson.getGender()!=null) {
                    if (medicalPerson.getGender()) {
                        gender = "女";
                    } else {
                        gender = "男";
                    }
                }
                else{
                    gender = "未知";
                }
            }

            map.put("gender",gender);

            map.put("age",age);
            map.put("faceImageUrl",person.getFaceImageUrl());

            msgResult.setData(map);
            msgResult.setResult(true);
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }

        return msgResult;

    }


    @ApiOperation(value="就医档案保存")
    @PostMapping("medicalPersonSave")
    public MessageResult<MedicalPerson> medicalPersonSave(@RequestBody MedicalPersonDTO medicalPersonDto,String token,@RequestAttribute String subject){
        MessageResult<MedicalPerson> msgResult = new MessageResult<>();

        try {
            MedicalPerson medicalPerson;

            int affectCount;

            if(StringUtils.isEmpty(medicalPersonDto.getId())){
                medicalPerson = new MedicalPerson();
                medicalPerson.setId(UUID.randomUUID().toString());
                medicalPerson.setPersonId(medicalPersonDto.getPersonId().toString());

                boolean gender = false;

                if(medicalPersonDto.getGender().equals("女")){
                    gender = true;
                }
                medicalPerson.setGender(gender);
                medicalPerson.setBirthDate(medicalPersonDto.getBirthDate());
                medicalPerson.setAllergicDrugs(medicalPersonDto.getAllergicDrugs());
                medicalPerson.setMedicalHistory(medicalPersonDto.getMedicalHistory());
                medicalPerson.setDelFlag(false);
                medicalPerson.setCreateBy(subject);
                medicalPerson.setCreateTime(new Date());

                affectCount = medicalPersonService.insert(medicalPerson);
            }
            else{
                medicalPerson = medicalPersonService.get(medicalPersonDto.getId());

                if(StringUtils.isNotEmpty(medicalPersonDto.getGender())) {
                    boolean gender = false;
                    if (medicalPersonDto.getGender().equals("女")) {
                        gender = true;
                    }
                    medicalPerson.setGender(gender);
                }
                if(medicalPersonDto.getBirthDate()!=null) {
                    medicalPerson.setBirthDate(medicalPersonDto.getBirthDate());
                }

                medicalPerson.setAllergicDrugs(medicalPersonDto.getAllergicDrugs());
                medicalPerson.setMedicalHistory(medicalPersonDto.getMedicalHistory());
                medicalPerson.setUpdateBy(subject);
                medicalPerson.setUpdateTime(new Date());

                affectCount = medicalPersonService.update(medicalPerson);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(medicalPerson);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库保存失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取就医档案")
    @GetMapping("medicalPersonDetail/{id}")
    public MessageResult<MedicalPersonDTO> medicalPersonDetail(@PathVariable("id") String id,String token){
        MessageResult<MedicalPersonDTO> msgResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(Long.parseLong(id));

            MedicalPerson medicalPerson = medicalPersonService.findByPersonId(personInfo.getId());

            MedicalPersonDTO medicalPersonDTO = new MedicalPersonDTO();

            medicalPersonDTO.setPersonId(personInfo.getId());
            medicalPersonDTO.setFaceImageUrl(personInfo.getFaceImageUrl());
            medicalPersonDTO.setName(personInfo.getName());

            String gender;
            if(StringUtils.isNotEmpty(personInfo.getSex())) {
                if ("1".equals(personInfo.getSex())) {
                    gender = "男";
                } else {
                    gender = "女";
                }
            }
            else{
                gender = "未知";
            }
            medicalPersonDTO.setGender(gender);

            if(medicalPerson!=null){
                medicalPersonDTO.setId(medicalPerson.getId());
                medicalPersonDTO.setBirthDate(medicalPerson.getBirthDate());
                medicalPersonDTO.setAllergicDrugs(medicalPerson.getAllergicDrugs());
                medicalPersonDTO.setMedicalHistory(medicalPerson.getMedicalHistory());

                if(medicalPerson.getGender()!=null) {
                    if (medicalPerson.getGender()) {
                        gender = "女";
                    } else {
                        gender = "男";
                    }
                }
                else{
                    gender = "未知";
                }
                medicalPersonDTO.setGender(gender);
            }
            msgResult.setResult(true);
            msgResult.setData(medicalPersonDTO);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="就医记录列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String token,@RequestAttribute String subject,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            HttpServletRequest request){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        try {

            Map<String, Object> searchParams = new HashMap<>();

            PersonInfo person = personInfoService.get(Long.parseLong(subject));

            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            //是否有关联长者
            if (StringUtils.isNotEmpty(personPopedom.getRelationPopedom())) {
                personPopedom = personPopedomService.get(personPopedom.getRelationPopedom());
            }

            searchParams.put("popedomId",personPopedom.getId());

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));

            Page<MedicalRecords> page = medicalRecordsService.pageSearch(searchParams, pageIndex, pageSize, sortList);

            Page<MedicalRecordsDTO> pageDto = new Page<>();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            for (MedicalRecords medicalRecords : page) {
                MedicalRecordsDTO medicalRecordsDTO = new MedicalRecordsDTO();

                medicalRecordsDTO.setId(medicalRecords.getId());
                medicalRecordsDTO.setHospitalName(medicalRecords.getHospitalName());

                if(medicalRecords.getHospitalTime()!=null) {
                    medicalRecordsDTO.setHospitalTime(sdf.format(medicalRecords.getHospitalTime()));
                }
                medicalRecordsDTO.setPathogeny(medicalRecords.getPathogeny());
                medicalRecordsDTO.setPopedomId(medicalRecords.getPopedomId());

                pageDto.add(medicalRecordsDTO);
            }

            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());

            msgResult.setData(PojoUtils.pageWrapper(page));
            msgResult.setResult(true);
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }

        return msgResult;
    }


    @ApiOperation(value="就医记录详情")
    @GetMapping("medicalRecordDetail/{id}")
    public MessageResult<MedicalRecordsAddDTO> medicalRecordDetail(@PathVariable("id") String id,String token){
        MessageResult<MedicalRecordsAddDTO> msgResult = new MessageResult<>();

        try {
            MedicalRecords medicalRecords = medicalRecordsService.get(id);

            if (medicalRecords != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                MedicalRecordsAddDTO medicalRecordsDTO = new MedicalRecordsAddDTO();

                medicalRecordsDTO.setId(medicalRecords.getId());
                medicalRecordsDTO.setHospitalName(medicalRecords.getHospitalName());

                if(medicalRecords.getHospitalTime()!=null) {
                    medicalRecordsDTO.setHospitalTime(sdf.format(medicalRecords.getHospitalTime()));
                }
                medicalRecordsDTO.setPathogeny(medicalRecords.getPathogeny());
                medicalRecordsDTO.setPopedomId(medicalRecords.getPopedomId());

                medicalRecordsDTO.setHospitalName(medicalRecords.getHospitalName());
                medicalRecordsDTO.setResult(medicalRecords.getResult());
                medicalRecordsDTO.setResultImg(medicalRecords.getResultImg());
                medicalRecordsDTO.setDrugs(medicalRecords.getDrugs());
                medicalRecordsDTO.setDrugsImg(medicalRecords.getDrugsImg());
                medicalRecordsDTO.setCost(medicalRecords.getCost());
                medicalRecordsDTO.setCostImg(medicalRecords.getCostImg());


                msgResult.setResult(true);
                msgResult.setData(medicalRecordsDTO);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="添加就医记录")
    @PostMapping("medicalRecordAdd")
    public MessageResult<MedicalRecords> medicalRecordAdd(@RequestBody MedicalRecordsAddDTO medicalRecordsAddDTO,String token,@RequestAttribute String subject){
        MessageResult<MedicalRecords> msgResult = new MessageResult<>();

        try {
            MedicalRecords medicalRecords = new MedicalRecords();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            medicalRecords.setId(UUID.randomUUID().toString());
            medicalRecords.setDelFlag(false);
            medicalRecords.setCreateBy(subject);
            medicalRecords.setCreateTime(new Date());
            medicalRecords.setHospitalName(medicalRecordsAddDTO.getHospitalName());

            if(medicalRecordsAddDTO.getHospitalTime()!=null) {
                medicalRecords.setHospitalTime(sdf.parse(medicalRecordsAddDTO.getHospitalTime()));
            }
            medicalRecords.setPopedomId(medicalRecordsAddDTO.getPopedomId());
            medicalRecords.setPathogeny(medicalRecordsAddDTO.getPathogeny());
            medicalRecords.setResult(medicalRecordsAddDTO.getResult());
            medicalRecords.setResultImg(medicalRecordsAddDTO.getResultImg());
            medicalRecords.setDrugs(medicalRecordsAddDTO.getDrugs());
            medicalRecords.setDrugsImg(medicalRecordsAddDTO.getDrugsImg());
            medicalRecords.setCost(medicalRecordsAddDTO.getCost());
            medicalRecords.setCostImg(medicalRecordsAddDTO.getCostImg());

            int affectCount = medicalRecordsService.insert(medicalRecords);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(medicalRecords);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="更新就医记录")
    @PostMapping("medicalRecordUpdate")
    public MessageResult<MedicalRecords> medicalRecordUpdate(@RequestBody MedicalRecordsAddDTO medicalRecordsAddDTO,String token,@RequestAttribute String subject){
        MessageResult<MedicalRecords> msgResult = new MessageResult<>();

        try {
            MedicalRecords medicalRecords = medicalRecordsService.get(medicalRecordsAddDTO.getId());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            medicalRecords.setHospitalName(medicalRecordsAddDTO.getHospitalName());
            if(medicalRecordsAddDTO.getHospitalTime()!=null) {
                medicalRecords.setHospitalTime(sdf.parse(medicalRecordsAddDTO.getHospitalTime()));
            }
            medicalRecords.setPathogeny(medicalRecordsAddDTO.getPathogeny());
            medicalRecords.setResult(medicalRecordsAddDTO.getResult());
            medicalRecords.setResultImg(medicalRecordsAddDTO.getResultImg());
            medicalRecords.setDrugs(medicalRecordsAddDTO.getDrugs());
            medicalRecords.setDrugsImg(medicalRecordsAddDTO.getDrugsImg());
            medicalRecords.setCost(medicalRecordsAddDTO.getCost());
            medicalRecords.setCostImg(medicalRecordsAddDTO.getCostImg());
            medicalRecords.setUpdateBy(subject);
            medicalRecords.setUpdateTime(new Date());

            int affectCount = medicalRecordsService.update(medicalRecords);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(medicalRecords);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    public int getAge(Date birthDay) throws Exception {
        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;
    }

}
