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

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.TemperatureConfig;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
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.outapi.dto.GreenCodeDTO;
import com.jpsoft.shinestar.modules.outapi.service.OutApiService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/mobile/IndividualLogApi")
public class IndividualLogApiController {
    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private PersonDeviceFilterLogService personDeviceFilterLogService;

    @Autowired
    private TemperatureConfig temperatureConfig;

    @Autowired
    private HolidayInfoService holidayInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private AlarmConfigService alarmConfigService;

    @Autowired
    private OutApiService outApiService;

    @Autowired
    private ValueOperations<String, Object> valueOperations;

    @PostMapping("healthyPersonList")
    @ApiOperation(value = "健康公示列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "sortType", value = "排序(1-序号,2-拼音)", paramType = "form")
    })

    public MessageResult<Map> healthyPersonList(
            String token,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestParam(value = "sortType", defaultValue = "1") String sortType,
            @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo admin = personInfoService.get(Long.valueOf(subject));

           /* Map<String, Object> companyMap = (Map<String, Object>) valueOperations.get(RedisConfig.PERSON_SELECT_COMPANY + admin.getId());
            String companyId = companyMap.get("id").toString();*/

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

            List<Sort> sortList = new ArrayList<>();
            if(sortType.equals("1")){
         //       sortList.add(new Sort("t2.student_number", "asc"));
                sortList.add(new Sort("a.create_time", "asc"));
            }
            else{
                sortList.add(new Sort("convert(a.name_ USING gbk) COLLATE gbk_chinese_ci", "asc"));
            }
        //    sortList.add(new Sort("a.create_time", "desc"));

            CompanyInfo companyInfo = companyInfoService.get(admin.getCompanyId());

            searchParams.put("companyCode", companyInfo.getCode()+"%");

            Page<PersonInfo> page = personInfoService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

            for (PersonInfo personInfo : page) {
                PersonDeviceFilterLog personDeviceFilterLog = personDeviceFilterLogService.lastPersonLog(personInfo.getId());

                if (personDeviceFilterLog != null) {
                    personInfo.setLastTemperatureLog(personDeviceFilterLog.getTemperature());
                    BigDecimal temperature = personDeviceFilterLog.getTemperature();
                    if (temperature.compareTo(temperatureConfig.getMax())<=0) {
                        personInfo.setIsNormal(false);
                    } else {
                        personInfo.setIsNormal(true);
                    }
                }
            }

            messageResult.setResult(true);
            messageResult.setData(PojoUtils.pageWrapper(page));
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("temperaturePersonDetail")
    @ApiOperation(value = "人员体温详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "人员ID", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> temperaturePersonDetail(
            String personId, String token,
            @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();
        Map<String, Object> map = new HashMap<>();

        try {
            PersonInfo person = personInfoService.get(Long.valueOf(personId));

           /* if (StringUtils.isBlank(person.getIdCard())) {
                throw new Exception("身份证为空");
            }*/


           /* GreenCodeDTO greenCodeDTO = outApiService.getGreenCode(person.getName(), person.getIdCard());
            String date = "";
            String healthyCode = "";
            String sjly = "";
            if (greenCodeDTO != null) {
                date = greenCodeDTO.getDate();
                healthyCode = greenCodeDTO.getHealthyCode();
                sjly = greenCodeDTO.getSjly();
            }*/

            String companyName = "";
            String parkName = "";
            CompanyInfo companyInfo = companyInfoService.get(person.getCompanyId());

            if (companyInfo != null){
                companyName = companyInfo.getName();
                if (StringUtils.isNotBlank(companyInfo.getParentId())){
                    parkName = companyInfo.getParentName();
                }
            }



            map.put("idCard", person.getIdCard());
            map.put("name", person.getName());
            map.put("parking",parkName);
            map.put("companyName",companyName);
            map.put("temperatureMax", temperatureConfig.getMax());
            map.put("faceImageUrl", person.getFaceImageUrl());
         //   map.put("date",date);
       //     map.put("healthyCode", healthyCode);
         //   map.put("sjly", sjly);


            PersonDeviceFilterLog lastPersonLog = personDeviceFilterLogService.lastPersonLog(person.getId());
            BigDecimal lastTemperature = null;
            if (lastPersonLog != null){
                 lastTemperature = lastPersonLog.getTemperature();
            }



            DecimalFormat df = new DecimalFormat("##.#");

            if (lastTemperature != null) {
                map.put("lastTemperature", df.format(lastTemperature));


                if (lastTemperature.compareTo(temperatureConfig.getMax())<=0) {
                    map.put("isNormal", false);
                } else {
                    map.put("isNormal", true);
                }
            } else {
                map.put("lastTemperature", "无记录");
            }



            messageResult.setResult(true);
            messageResult.setData(map);
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("temperaturePersonCurve")
    @ApiOperation(value = "人员温度曲线接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "人员ID", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<List<Map<String, Object>>> temperaturePersonCurve(
            String personId, String token,
            @RequestAttribute String subject) {

        MessageResult<List<Map<String, Object>>> messageResult = new MessageResult<>();

        try {
            List<Map<String, Object>> totalList = new ArrayList<>();

            PersonInfo person = personInfoService.get(Long.valueOf(personId));

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

            //最近14天
            DateTime startTime = now.minusDays(13);
            DateTime endTime = now;

            map.put("startDate", startTime.toString("yyyy-MM-dd"));
            map.put("endDate", endTime.toString("yyyy-MM-dd"));

            List<Map<String, Object>> list1 = new ArrayList<>();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            PersonDeviceFilterLog lastPersonLog = personDeviceFilterLogService.lastPersonLog(person.getId());

            String lastDateStr = DateTime.now().toString("yyyy-MM-dd");

            if (lastPersonLog != null) {
                sdf.format(lastPersonLog.getRecordTime());
            }

            DateTime today = DateTime.now().withTimeAtStartOfDay();
            int undetectedCount = 0; //未测温天数
            int totalDays = 0;       //连续测温天数

            CompanyInfo companyInfo = companyInfoService.get(person.getCompanyId());

            //最近一年的节假日
            Set<String> holidaySet = holidayInfoService.getHolidaySetByDate(companyInfo.getCode(), startTime.toDate(), today.plusDays(1).toDate(), false);

            //查询当前用户的考勤设置
            Set<Integer> weekdaySet = alarmConfigService.getWeekdaySetByCompanyId(person.getCompanyId());

            for (int i = 0; i < 14; i++) {
                Map<String, Object> map1 = new HashMap<>();
                DateTime curDay = startTime.plusDays(i);

                String startDate = curDay.toString("yyyy-MM-dd");
                String endDate = curDay.plusDays(1).toString("yyyy-MM-dd");

                PersonDeviceFilterLog personDeviceFilterLog = null;

                if (lastDateStr.equals(startDate) && lastPersonLog != null) {
                    //当天最后一条记录
                    DateTime recordTime = new DateTime(lastPersonLog.getRecordTime());

                    if (recordTime.toString("yyyy-MM-dd").equals(startDate)) {
                        personDeviceFilterLog = lastPersonLog;
                    }
                }

                if (personDeviceFilterLog == null) {
                    personDeviceFilterLog = personDeviceFilterLogService.findByPersonOrderTemperature(person.getId(), startDate, endDate);
                }

                if (personDeviceFilterLog != null) {
                    boolean isDanger = false;
                    map1.put("name", curDay.toString("MM-dd"));
                    map1.put("value", personDeviceFilterLog.getTemperature());

                    if (personDeviceFilterLog.getTemperature().compareTo(temperatureConfig.getMax())>0) {
                        isDanger = true;
                    }

                    map1.put("danger", isDanger);
                    totalDays++;
                } else {
                    //如果没有记录，先判断是否非工作日
                    if (!weekdaySet.contains(curDay.getDayOfWeek())) {
                        //先排除一周非工作日
                        continue;
                    } else if (holidaySet.contains(curDay.toString("yyyy-MM-dd"))) {
                        //再排除节假日
                        continue;
                    }

                    //工作日没有记录，则显示为0
                    map1.put("name", curDay.toString("MM-dd"));
                    map1.put("value", 0);
                    map1.put("danger", false);

                    totalDays = 0; //连续正常数清零
                    undetectedCount++; //未检测数增加
                }

                list1.add(map1);
            }

            map.put("list", list1);
            map.put("temperatureMax", temperatureConfig.getMax());
            map.put("undetectedCount", undetectedCount);
            map.put("totalDays", totalDays);

            totalList.add(map);

            messageResult.setData(totalList);
            messageResult.setResult(true);
        } catch (Exception ex) {
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);
        }

        return messageResult;

    }

    @PostMapping("getGreenCode")
    @ApiOperation(value="获取绿码")
    @ApiImplicitParams({
            @ApiImplicitParam(name="personId",value = "人员ID",required = true,paramType = "form"),
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<GreenCodeDTO> getGreenCode(
            String personId, String token,
            @RequestAttribute String subject){
        MessageResult<GreenCodeDTO> messageResult = new MessageResult<>();

        try{
            PersonInfo person = personInfoService.get(Long.valueOf(personId));
            if (StringUtils.isBlank(person.getIdCard())){

                GreenCodeDTO greenCodeDTO = new GreenCodeDTO();
                greenCodeDTO.setHasIdCard(false);
                greenCodeDTO.setName(person.getName());
                messageResult.setResult(true);
                messageResult.setCode(200);
                messageResult.setData(greenCodeDTO);
                return messageResult;

            }



            GreenCodeDTO greenCodeDTO = outApiService.getGreenCode(person.getName(),person.getIdCard());

            if (greenCodeDTO!=null && StringUtils.isNotBlank(greenCodeDTO.getHealthyCode())){
                String date = greenCodeDTO.getDate();
                String sjly = greenCodeDTO.getSjly();
                StringBuilder sb = new StringBuilder(date);
                sb.insert(4,"-");
                sb.insert(7,"-");
                greenCodeDTO.setDate(sb.toString());
                if (sjly.equals("1")){
                    greenCodeDTO.setSjly("湖北省健康码平台");
                }
                if (sjly.equals("2")){
                    greenCodeDTO.setSjly("武汉市健康码平台");
                }

                greenCodeDTO.setName(person.getName());
                greenCodeDTO.setIdCard(person.getIdCard());
                greenCodeDTO.setHasIdCard(true);

                // map.put("greenCode",greenCodeDTO);
                messageResult.setResult(true);
                messageResult.setData(greenCodeDTO);
                messageResult.setMessage("success");
            }
            else{
                messageResult.setResult(false);
                messageResult.setMessage("未查询到健康码信息");
            }
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setCode(400);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("getGreenCodeByName")
    @ApiOperation(value="获取绿码")
    @ApiImplicitParams({
            @ApiImplicitParam(name="name",value = "姓名",required = true,paramType = "form"),
            @ApiImplicitParam(name="idCard",value = "身份证",required = true,paramType = "form"),
    })
    public MessageResult<GreenCodeDTO> getGreenCodeByName(
            String name, String idCard){
        MessageResult<GreenCodeDTO> messageResult = new MessageResult<>();

        try{
            GreenCodeDTO greenCodeDTO = outApiService.getGreenCode(name,idCard);

            if (greenCodeDTO!=null && StringUtils.isNotBlank(greenCodeDTO.getHealthyCode())){
                String date = greenCodeDTO.getDate();
                String sjly = greenCodeDTO.getSjly();
                StringBuilder sb = new StringBuilder(date);
                sb.insert(4,"-");
                sb.insert(7,"-");
                greenCodeDTO.setDate(sb.toString());
                if (sjly.equals("1")){
                    greenCodeDTO.setSjly("湖北省健康码平台");
                }
                if (sjly.equals("2")){
                    greenCodeDTO.setSjly("武汉市健康码平台");
                }

                greenCodeDTO.setName(name);
                greenCodeDTO.setIdCard(idCard);
                greenCodeDTO.setHasIdCard(true);

                // map.put("greenCode",greenCodeDTO);
                messageResult.setResult(true);
                messageResult.setData(greenCodeDTO);
                messageResult.setMessage("success");
            }
            else{
                messageResult.setResult(false);
                messageResult.setMessage("未查询到健康码信息");
            }
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setCode(400);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

}
