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

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
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.JwtUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import io.swagger.annotations.Api;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/base/punchRecord")
@Api(description = "punchRecord")
@Slf4j
public class PunchRecordController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    private PunchRecordService punchRecordService;

    @Autowired
    private PunchLocationService punchLocationService;

    @Autowired
    private PersonInfoService personInfoService;



    @Autowired
    private CompanyInfoService companyInfoService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<PunchRecord> create(){
        MessageResult<PunchRecord> msgResult = new MessageResult<>();

        PunchRecord punchRecord = new PunchRecord();

        msgResult.setData(punchRecord);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<PunchRecord> add(@RequestBody PunchRecord punchRecord,@RequestAttribute String subject){
        MessageResult<PunchRecord> msgResult = new MessageResult<>();

        try {
            punchRecord.setId(UUID.randomUUID().toString());
            punchRecord.setDelFlag(false);
            punchRecord.setCreateBy(subject);
            punchRecord.setCreateTime(new Date());

            int affectCount = punchRecordService.insert(punchRecord);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(punchRecord);
            } 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("edit/{id}")
    public MessageResult<PunchRecord> edit(@PathVariable("id") String id){
        MessageResult<PunchRecord> msgResult = new MessageResult<>();

        try {
            PunchRecord punchRecord = punchRecordService.get(id);

            if (punchRecord != null) {
                msgResult.setResult(true);
                msgResult.setData(punchRecord);
            } 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("update")
    public MessageResult<PunchRecord> update(@RequestBody PunchRecord punchRecord,@RequestAttribute String subject){
        MessageResult<PunchRecord> msgResult = new MessageResult<>();

        try {
            punchRecord.setUpdateBy(subject);
            punchRecord.setUpdateTime(new Date());

            int affectCount = punchRecordService.update(punchRecord);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(punchRecord);
            } 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("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            PunchRecord punchRecord = punchRecordService.get(id);
            punchRecord.setDelFlag(true);
            punchRecord.setUpdateBy(subject);
            punchRecord.setUpdateTime(new Date());

            int affectCount = punchRecordService.update(punchRecord);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } 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("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                PunchRecord punchRecord = punchRecordService.get(id);
                punchRecord.setDelFlag(true);
                punchRecord.setUpdateBy(subject);
                punchRecord.setUpdateTime(new Date());

                affectCount += punchRecordService.update(punchRecord);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } 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="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String id,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

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

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

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("id_","asc"));

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

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

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

        return msgResult;
    }

    @PostMapping("savePersonRecord")
    @ResponseBody
    @ApiOperation(value = "记录学生打卡信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "打卡点id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "openId", value = "openId", required = true, paramType = "form"),
            @ApiImplicitParam(name = "longtitude", value = "经度", required = false, paramType = "form"),
            @ApiImplicitParam(name = "latitude", value = "纬度", required = false, paramType = "form"),
            @ApiImplicitParam(name = "temperature", value = "打卡温度", required = false, paramType = "form"),
    })
    public MessageResult<Map> savePersonRecord(String id, String openId,String longtitude,String latitude,String temperature) {
        MessageResult<Map> messageResult = new MessageResult<>();
        String msg = "打卡成功";

        try {
                if (StringUtils.isBlank(id)){
                    throw new Exception("打卡点空");
                }
                if (StringUtils.isBlank(openId)) {
                    throw new Exception("openId为空");
                }
               /* if (StringUtils.isBlank(longtitude) || StringUtils.isBlank(latitude)){
                    throw new Exception("学生获取位置失败");
                }*/
                PunchLocation punchLocation = punchLocationService.get(id);
                if (punchLocation == null){
                    throw new Exception("打卡点不存在");
                }
                if (!punchLocation.getIsEnable()){
                    throw new Exception("打卡点未启用。请联系管理员");
                }

                String schoolId = "";
                String popedom = "";

                PersonInfo personInfo =null;

                if (!punchLocation.getCompanyId().equals(schoolId)){
                    throw new Exception("学生所在学校和打卡点所属不一致");
                }
                HashMap<String,Object> searchMap = new HashMap<>();
                searchMap.put("personId",personInfo.getId());
                searchMap.put("punchId",punchLocation.getId());
                cn.hutool.core.date.DateTime dateTime = DateUtil.offsetSecond(new Date(),-10);
                searchMap.put("qtCreateTime", DateUtil.formatDateTime(dateTime));
                List<Sort> sortList = new ArrayList<>();
                sortList.add(new Sort("create_time","asc"));
                Page<PunchRecord> page = punchRecordService.pageSearch(searchMap,1,10,false,sortList);
                if (page.getResult().size()>0){
                    throw new Exception("请勿重复打卡");
                }


                PunchRecord punchRecord = new PunchRecord();
                punchRecord.setId(UUID.randomUUID().toString());
                punchRecord.setPersonId(personInfo.getId());
                punchRecord.setPunchId(punchLocation.getId());
                punchRecord.setLongtitude(longtitude);
                punchRecord.setLatitude(latitude);
                punchRecord.setDelFlag(false);
                punchRecord.setCreateBy(personInfo.getName());
                punchRecord.setCreateTime(new Date());
               if(temperature!=null &&temperature!=""){
                 //  punchRecord.setTemperature(new BigDecimal(temperature));
               }
                punchRecordService.insert(punchRecord);


                String token = JwtUtil.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(6).toDate());

                HashMap<String,Object> map = new HashMap<>();
                map.put("popedom",popedom);
                map.put("personId",personInfo.getId());
                map.put("token",token);
                messageResult.setData(map);
                messageResult.setMessage("打卡成功");
                messageResult.setResult(true);
                messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("healthCertAuth")
    @ResponseBody
    @ApiOperation(value = "健康证权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "打卡点id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "openId", value = "openId", required = true, paramType = "form")
    })
    public MessageResult<Map> healthCertAuth(String id, String openId) {
        MessageResult<Map> messageResult = new MessageResult<>();

        String schoolName = "";
        try {
            if (StringUtils.isBlank(id)){
                throw new Exception("打卡点空");
            }
            if (StringUtils.isBlank(openId)) {
                throw new Exception("openId为空");
            }
            PunchLocation punchLocation = punchLocationService.get(id);
            if (punchLocation == null){
                throw new Exception("打卡点不存在");
            }
            if (!punchLocation.getIsEnable()){
                throw new Exception("打卡点未启用。请联系管理员");
            }
            CompanyInfo school = companyInfoService.get(punchLocation.getCompanyId());
            if (school == null){
                throw new Exception("学校信息不存在");
            }
            schoolName = school.getName();

            PersonInfo personInfo = null;
            if (personInfo == null){
                throw new Exception("您不是"+school.getName()+"的人员，无通行权限");
            }
            if (personInfo.getPopedom().equals("2")){
                throw new Exception("学生家长不可用");
            }
            String schoolId = "";
            String popedom = "";



            if (!punchLocation.getCompanyId().equals(schoolId)){
                throw new Exception("您不是"+school.getName()+"的人员，无通行权限");
            }

            HashMap<String,Object> map = new HashMap<>();
            map.put("companyName",schoolName);
            map.put("result",true);
            map.put("popedom",popedom);
            map.put("personId",personInfo.getId());
            String token = JwtUtil.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(6).toDate());
            map.put("token",token);
            messageResult.setData(map);
            messageResult.setMessage("成功");
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            HashMap<String,Object> map = new HashMap<>();
            map.put("companyName",schoolName);
            map.put("result",false);
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

}
