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

import cn.hutool.json.JSONObject;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.exception.CustomException;
import com.jpsoft.shinestar.modules.base.dto.PersonHealthLedgerDTO;
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.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

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

    @Autowired
    private PersonHealthLedgerService personHealthLedgerService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;
    @Autowired
    private CompanyStructureInfoService  companyStructureInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private DataDictionaryService dictionaryService;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private PersonDeviceFilterLogService personDeviceFilterLogService;

    @Autowired
    private ValueOperations<String,Object> valueOperations;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private  CompanySuperviseService companySuperviseService;

    @ApiOperation(value="保存信息")
    @PostMapping("save")
    public MessageResult<PersonHealthLedger> save(@RequestBody PersonHealthLedger personHealthLedger, @RequestAttribute String subject){
        MessageResult<PersonHealthLedger> msgResult = new MessageResult<>();
        String key = "personHealthLedger_" + personHealthLedger.getPersonId() + "_" + DateTime.now().toString("yyyy-MM-dd");
        try {
            //每天只能打一次
//            List<PersonHealthLedger> list = personHealthLedgerService.findByTimeAndPersonId(DateTime.now().toString("yyyy-MM-dd"),personHealthLedger.getPersonId());
//
//            if (list.size()>0){
//                throw new Exception("今日已健康打卡！");
//            }

            Date date = new Date();
            if(personHealthLedger.getCreateTime()!=null){
                date=personHealthLedger.getCreateTime();
            }

            //todo
            //判断今日是否打开用
            personHealthLedger.setCountNum(1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //开始计算
            // 查询昨天 是否有数据
            Date  endTime = sdf.parse(sdf.format( date ));
            Date startTime = new DateTime(endTime).minusDays(1).toDate();
            PersonHealthLedger minusLedger = personHealthLedgerService.existByCreateTimeAndPersonId(personHealthLedger.getPersonId(), startTime, endTime);
            if(minusLedger!=null){

                if(minusLedger.getCountNum()==null){
                    minusLedger.setCountNum(1);
                }
                personHealthLedger.setCountNum(minusLedger.getCountNum()+1);

            }
            //todo

            personHealthLedger.setId(UUID.randomUUID().toString());
            personHealthLedger.setDelFlag(false);
            personHealthLedger.setCreateBy(subject);
            personHealthLedger.setCreateTime(new Date());

            //判断今日是否打开用
           // String key = "personHealthLedger_" + personHealthLedger.getPersonId() + "_" + DateTime.now().toString("yyyy-MM-dd");
            boolean writeSuccess =  valueOperations.setIfAbsent(key,personHealthLedger.getId(),1,TimeUnit.DAYS);

            //每天只能打一次
            if (!writeSuccess){
                throw new CustomException("今日已健康打卡！");
            }

            int affectCount = personHealthLedgerService.insert(personHealthLedger);
            Long personId = Long.valueOf(subject);

            //戴口罩状态（0：未开启口罩验证，1：未戴口罩，2：戴口罩）
            Integer maskFlag = 0;
            PersonInfo personInfo = personInfoService.get(personId);
           // Date date = new Date();
            //体温上报对应测温设备
            String deviceNo = "0";

            JSONObject faceImageJson = new JSONObject(); //暂未使用
            JSONObject libMatInfoListJson = new JSONObject();
            JSONObject matchPersonInfo = new JSONObject();

            libMatInfoListJson.put("MatchStatus","1");
            libMatInfoListJson.put("MatchPersonID",personInfo.getId());
            matchPersonInfo.put("PersonName",personInfo.getName());

            //记录人员记录
            personDeviceLogService.deviceInsertLog(deviceNo,personHealthLedger.getTemperature(),faceImageJson,libMatInfoListJson,matchPersonInfo,date,maskFlag,personInfo.getFaceImageUrl());


            personHealthLedger.setPersonInfo(personInfo);
            //记录人员过滤记录
            personDeviceFilterLogService.deviceInsertFilterLog(deviceNo,personHealthLedger.getTemperature(),faceImageJson,libMatInfoListJson,matchPersonInfo,date,maskFlag,personInfo.getFaceImageUrl(),personHealthLedger.getAddress(),personHealthLedger);

           /* try {
                personHealthLedger.setPersonInfo(personInfo);
                //保存省内省外在荆州过年人数+1
                companySuperviseService.updateAtProvinceNum(personHealthLedger);
            }
            catch(Exception ex){
                logger.error(ex.getMessage(),ex);
                msgResult.setResult(false);
                msgResult.setMessage(ex.getMessage());
            }*/

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

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

        return msgResult;
    }

    @PostMapping("workerPageList")
    @ApiOperation(value="健康台账列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="queryDate",value = "选择日期（格式:yyyy-MM-dd）",required = true,paramType = "form"),
            @ApiImplicitParam(name="setinput",value = "前端输入", paramType = "form"),
            @ApiImplicitParam(name="companyId",value = "班级ID",paramType = "form"),
            @ApiImplicitParam(name="status",value = "是否上报（空：全部，1：已上报，2：未上报）",paramType = "form"),
            @ApiImplicitParam(name = "sortType", value = "排序(1-序号,2-拼音)", paramType = "form")
    })
    public MessageResult<Map> workerPageList(
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryDate,
            @RequestParam(value="setinput",defaultValue="") String setinput,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="status",defaultValue="") String status,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value="address",defaultValue="") String address,
            @RequestParam(value = "sortType", defaultValue = "1") String sortType,
            @RequestAttribute String subject){
        //当前用户ID
        System.out.println(subject);

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

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

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //searchParams.put("queryDate",sdf.format(queryDate));

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

            Date startTime = sdf.parse(sdf.format( queryDate ));
            Date endTime = new DateTime(startTime).plusDays(1).toDate();

            searchParams.put("startTime",startTime);
            searchParams.put("endTime",endTime);

            if(StringUtils.isNotEmpty(setinput)) {
                searchParams.put("name", "%" + setinput + "%");
            }



            List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode("%"+companyId+"%");
            List<String> idList = new ArrayList<>();
            if (companyInfoList.size()>0){
                for (CompanyInfo companyInfo : companyInfoList){
                    idList.add(companyInfo.getId());
                }
            }

            searchParams.put("InCompanyId",idList);

       //     searchParams.put("companyId", companyId);


            if (StringUtils.isNotEmpty(status)){
                searchParams.put("status",status); //1：已上报，2：未上报
            }
            String addressOut = null;
            String addressIn = null;
            if(StringUtils.isNotEmpty(address)){

                if("0".equals(address)){
                    addressIn = "湖北省荆州市%";
                    searchParams.put("addressIn",addressIn);
                }
                if("1".equals(address)){
                    addressOut = "湖北省荆州市%";
                    addressIn = "湖北省%";
                    searchParams.put("addressOut",addressOut);
                    searchParams.put("addressIn",addressIn);
                }
                if("2".equals(address)){
                    addressOut = "湖北省%";
                    searchParams.put("addressOut",addressOut);
                }
            }
            List<Sort> sortList = new ArrayList<>();

            if(sortType.equals("1")){
                sortList.add(new Sort("a.id_", "asc"));
            }
            else{
                sortList.add(new Sort("a.pinyin_", "asc"));
            }

            Page<PersonHealthLedgerDTO> page = personHealthLedgerService.workerPageList(searchParams,pageIndex,pageSize,true,sortList);

            for (PersonHealthLedgerDTO person:page) {
                if(StringUtils.isNotEmpty(person.getPersonHealthLedgerId())){
                    person.setUpLoad(true);
                }
                else{
                    person.setUpLoad(false);
                }
            }

            msgResult.setResult(true);
            msgResult.setData(PojoUtils.pageWrapper(page));

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

        return msgResult;
    }


    @ApiOperation(value="获取学生信息")
    @RequestMapping(value = "getPersonInfo",method = RequestMethod.POST)
    public MessageResult<PersonHealthLedgerDTO> getPersonInfo(String popedom,String token, @RequestAttribute String subject){
        MessageResult<PersonHealthLedgerDTO> msgResult = new MessageResult<>();

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

            PersonHealthLedgerDTO  studentPersonInfoDTO = new PersonHealthLedgerDTO();

            if(personInfo!=null){

                studentPersonInfoDTO.setId(personInfo.getId());
                studentPersonInfoDTO.setName(personInfo.getName());
                studentPersonInfoDTO.setPhone(personInfo.getPhone());


                PersonHealthLedger personHealthLedger = personHealthLedgerService.lastByPersonId(personInfo.getId());
                if (personHealthLedger != null) {
                    List<DataDictionary> dictionaryList = dictionaryService.findByCatalogName("健康情况");
                    for (DataDictionary dictionary : dictionaryList) {
                        if (dictionary.getValue().equals(personHealthLedger.getFamilyStatus())) {
                            personHealthLedger.setFamilyStatusN(dictionary.getName());
                        }
                        if (dictionary.getValue().equals(personHealthLedger.getHealthStatus())) {
                            personHealthLedger.setHealthStatusN(dictionary.getName());
                        }
                    }
                }
                studentPersonInfoDTO.setIdCard(personInfo.getIdCard());
                studentPersonInfoDTO.setPersonHealthLedger(personHealthLedger);


                studentPersonInfoDTO.setPosition1(personInfo.getCompanyName());

                PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
                CompanyStructureInfo  structure =companyStructureInfoService.get(personPopedom.getCompanyStructureId());

                studentPersonInfoDTO.setPosition2(structure!=null?structure.getStructureName():"");
                studentPersonInfoDTO.setPosition3(personPopedom.getRemark());
            }
            //健康打卡-引流
            DataDictionary detail = dictionaryService.get("2659053f-1b24-4cc5-a2fa-2113028ff464");
            if(detail!=null&&StringUtils.isNotEmpty(detail.getValue())){
                studentPersonInfoDTO.setUrl(detail.getValue());
            }
            msgResult.setResult(true);
            msgResult.setData(studentPersonInfoDTO);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }


    @ApiOperation(value="获取健康状况列表")
    @RequestMapping(value = "getHealthStatusList",method = RequestMethod.POST)
    public MessageResult<List<Map<String,String>>> getHealthStatusList(String token){
        MessageResult<List<Map<String,String>>> msgResult = new MessageResult<>();

        try{
            List<DataDictionary> dictionaryList = dictionaryService.findByCatalogName("健康情况");

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

            for (DataDictionary dictionary:dictionaryList) {
                Map<String,String> map = new HashMap<>();
                map.put("name",dictionary.getName());
                map.put("value",dictionary.getValue());
                list.add(map);
            }

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

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

        return msgResult;
    }



    @PostMapping("upload")
    @ApiOperation(value="家庭成员健康码上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "photoFile",value = "健康码图片", required = true,paramType="form", dataType = "__file"),
            @ApiImplicitParam(name="token",value = "令牌",required = false,paramType = "query"),
            @ApiImplicitParam(name="subject",value = "令牌",required = false,paramType = "query")
    })
    public MessageResult<String> upload(
             MultipartFile[] photoFile, String token, @RequestAttribute  String subject){
        MessageResult<String> messageResult = new MessageResult<>();

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

            if (personInfo==null){
                throw new Exception("人员信息不存在!");
            }

            String retFileUrl = "";

            int i = 1;
            for (MultipartFile file:photoFile) {
                String photoName = personInfo.getId() + "-" + String.valueOf(i);
                retFileUrl += OSSUtil.upload(ossConfig,"/personHealthLedger",photoName,file.getInputStream())+",";
                i++;
            }

            if(StringUtils.isNotEmpty(retFileUrl)){
                retFileUrl = retFileUrl.substring(0,retFileUrl.lastIndexOf(","));
            }

            messageResult.setResult(true);
            messageResult.setData(retFileUrl);
            messageResult.setCode(200);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);

            messageResult.setResult(false);
            messageResult.setMessage(e.getMessage());
        }

        return messageResult;
    }



    @ApiOperation(value="获取详细信息")
    @GetMapping("detail")
    public MessageResult<PersonHealthLedgerDTO> detail(String id,String popedom,String token, @RequestAttribute  String subject){
        MessageResult<PersonHealthLedgerDTO> msgResult = new MessageResult<>();

        try {
            PersonHealthLedgerDTO  studentPersonInfoDTO = new PersonHealthLedgerDTO();
            PersonHealthLedger personHealthLedger=null;
            PersonInfo personInfo=null;
            //无id , 自己进入， 有id ,老师点击
            if(id==null||"undefined".equals(id)){
                personInfo = personInfoService.get(Long.parseLong(subject));
                String key = "personHealthLedger_" + personInfo.getId() + "_" + DateTime.now().toString("yyyy-MM-dd");

                String personHealthLedgerId = (String)valueOperations.get(key);

                if (StringUtils.isNotEmpty(personHealthLedgerId)){
                    personHealthLedger = personHealthLedgerService.get(personHealthLedgerId);
                }

                if (personHealthLedger==null){
                    throw new Exception("打卡记录不存在!");
                }
//                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//                List<PersonHealthLedger>list=personHealthLedgerService.findByTimeAndPersonId(sdf.format(new Date()),personInfo.getId());
//               if(list.size()==0){
//                   msgResult.setResult(false);
//                   msgResult.setMessage("数据库不存在该记录!");
//               }
//                personHealthLedger = list.get(0);
            }else{
                personHealthLedger = personHealthLedgerService.get(id);
                personInfo = personInfoService.get(personHealthLedger.getPersonId());
            }

            List<DataDictionary> dictionaryList = dictionaryService.findByCatalogName("健康情况");
            for (DataDictionary dictionary:dictionaryList) {
              if(dictionary.getValue().equals(personHealthLedger.getFamilyStatus())){
                  personHealthLedger.setFamilyStatusN(dictionary.getName());
              }
                if(dictionary.getValue().equals(personHealthLedger.getHealthStatus())){
                    personHealthLedger.setHealthStatusN(dictionary.getName());
                }
            }
            studentPersonInfoDTO.setId(personInfo.getId());
            studentPersonInfoDTO.setName(personInfo.getName());
            studentPersonInfoDTO.setPhone(personInfo.getPhone());


            studentPersonInfoDTO.setPosition1(personInfo.getCompanyName());

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            CompanyStructureInfo  structure =companyStructureInfoService.get(personPopedom.getCompanyStructureId());

            studentPersonInfoDTO.setPosition2(structure!=null?structure.getStructureName():"");
            studentPersonInfoDTO.setPosition3(personPopedom.getRemark());

            personHealthLedger.setPersonInfo(personInfo);
            studentPersonInfoDTO.setIdCard(personInfo.getIdCard());
            studentPersonInfoDTO.setPersonHealthLedger(personHealthLedger);
            if (personHealthLedger != null) {
                msgResult.setResult(true);
                msgResult.setData(studentPersonInfoDTO);
            } 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("curDateIsUpload")
    public MessageResult<Boolean> curDateIsUpload(String token, @RequestAttribute  String subject){
        MessageResult<Boolean> msgResult = new MessageResult<>();

        try{
            SimpleDateFormat dateFormat = new SimpleDateFormat(" yyyy-MM-dd ");

            String currentDate =   dateFormat.format( new Date() );

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

            Date startTime = dateFormat.parse(currentDate);

            Date endTime = new DateTime(startTime).plusDays(1).toDate();

          //  PersonHealthLedger personHealthLedger = personHealthLedgerService.existByCreateTimeAndPersonId(personInfo.getId(),startTime,endTime);
            String key = "personHealthLedger_" + personInfo.getId() + "_" + DateTime.now().toString("yyyy-MM-dd");
            String personHealthLedgerId = null;

            if(valueOperations.get(key)!=null){
                personHealthLedgerId = valueOperations.get(key).toString();
            }

            PersonHealthLedger personHealthLedger = null;

            if(StringUtils.isNotEmpty(personHealthLedgerId)) {
                personHealthLedger = personHealthLedgerService.get(personHealthLedgerId);

                if (personHealthLedger==null){
                    //redis保存值不是id
                    personHealthLedger = personHealthLedgerService.existByCreateTimeAndPersonId(personInfo.getId(),startTime,endTime);
                }

                if (personHealthLedger!=null){
                    //更新redis
                    valueOperations.set(key, personHealthLedger.getId(),1,TimeUnit.DAYS);
                }
            }
            boolean isUpload = false;

            if(personHealthLedger!=null){
                isUpload = true;
            }
            msgResult.setData(isUpload);
            msgResult.setResult(true);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @PostMapping("query")
    @ApiOperation(value="query")
    public MessageResult<Map> query(            @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryDate,
                                                @RequestParam(value="companyId",defaultValue="") String companyId,

                                                String token, @RequestAttribute  String subject){
        MessageResult<Map> msgResult = new MessageResult<>();
        Map<String,Object> searchParams = new HashMap<>();

        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //searchParams.put("queryDate",sdf.format(queryDate));

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

            Date startTime = sdf.parse(sdf.format( queryDate ));
            Date endTime = new DateTime(startTime).plusDays(1).toDate();

            searchParams.put("startTime",startTime);
            searchParams.put("endTime",endTime);






            List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode("%"+companyId+"%");
            List<String> idList = new ArrayList<>();
            if (companyInfoList.size()>0){
                for (CompanyInfo companyInfo : companyInfoList){
                    idList.add(companyInfo.getId());
                }
            }
            searchParams.put("InCompanyId",idList);
            List<Map> maps=personHealthLedgerService.query(searchParams);
            if(maps.size()>0){
                msgResult.setData(maps.get(0));
            }

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

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

        return msgResult;
    }
}
