package com.dcsoft.system.uniubi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.CacheConstants;
import com.dcsoft.common.core.constant.HttpStatus;
import com.dcsoft.common.core.constant.SecurityConstants;
import com.dcsoft.common.core.domain.R;
import com.dcsoft.common.core.utils.JwtUtils;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.core.utils.uuid.IdUtils;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.web.page.TableDataInfo;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.redis.service.RedisService;
import com.dcsoft.system.api.RemoteFileService;
import com.dcsoft.system.api.domain.SysFile;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.consume.domain.ConsumePeopleDay;
import com.dcsoft.system.consume.domain.ConsumeRecord;
import com.dcsoft.system.consume.service.IConsumePeopleDayService;
import com.dcsoft.system.consume.service.IConsumeRecordService;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.domain.HkBack;
import com.dcsoft.system.uniubi.domain.HkBackRecord;
import com.dcsoft.system.uniubi.domain.Hknfo;
import com.dcsoft.system.uniubi.service.ISysApiService;
import com.dcsoft.system.utils.HttpUtil;
import com.dcsoft.system.utils.PictureUtils;
import com.dcsoft.system.utils.WeChatUtil;
import com.dcsoft.system.visitor.domain.Visitor;
import com.dcsoft.system.visitor.service.IVisitorService;
import com.github.pagehelper.PageInfo;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

import static com.dcsoft.common.core.utils.PageUtils.startPage;
import static com.dcsoft.common.core.web.domain.AjaxResult.error;
import static com.dcsoft.common.core.web.domain.AjaxResult.success;


/**
 * 用户管理 业务处理
 *
 * @author xueyi
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class SysApiController {

    @Autowired
    protected ISysApiService apiService;

    @Autowired
    protected ISysPeopleService peopleService;


    @Autowired
    protected IVisitorService visitorService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisService redisService;



    @Value("${weixin.appid}")
    public String appid;
    @Value("${weixin.appSecret}")
    public String appSecret;

    @Autowired
    private ISysBranchService sysBranchService;

    @Autowired
    private IConsumeRecordService consumeRecordService;

    @Autowired
    private IHkPeopleRecordService hkPeopleRecordService;

    private final static long expireTime = CacheConstants.EXPIRATION;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private IConsumePeopleDayService consumePeopleDayService;

    @Autowired
    private ISysEquipmentService sysEquipmentService;

    @Value("${artemis.enabled}")
    private String enabled;

    @Value("${artemis.url}")
    public String url;
    @Value("${artemis.appKey}")
    public String appKey;
    @Value("${artemis.appSecret}")
    public String appSecrets;

    private static final String ARTEMIS_PATH = "/artemis";

    @Value("${weCom.corpid}")
    public String corpid;
    @Value("${weCom.corpsecret}")
    public String corpsecret;

    @Value("${weCom.token}")
    public String qywxToken;




    @RequestMapping(value = "peopleInfo",method = RequestMethod.POST)
    @ApiOperation("获取peopleInfo")
    @Log(title = "hr人员信息接口", businessType = BusinessType.UPDATE)
    public JSONObject peopleInfo(HttpServletRequest request){
        JSONObject result=new JSONObject();
        String name=request.getParameter("name");
        String deptId=request.getParameter("deptId");
        String gh=request.getParameter("gh");
        String phone=request.getParameter("phone");
        String type=request.getParameter("type");
        String doorNo=request.getParameter("cardNo");
        String isConsume=request.getParameter("isConsume");
        String qwid=request.getParameter("qwid");

        String username=request.getHeader("username");
        String password=request.getHeader("password");


        if(StringUtils.isEmpty(username)){
            result.put("code",500);
            result.put("data","username is null");
            return result;
        }
        if(StringUtils.isEmpty(password)){
            result.put("code",500);
            result.put("data","password is null");
            return result;
        }
        if(!"hr".equals(username)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }
        if(!"admin@123".equals(password)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }

        if(StringUtils.isEmpty(gh)){
            result.put("code",500);
            result.put("data","gh is null");
            return result;
        }

        if(StringUtils.isEmpty(name)){
            result.put("code",500);
            result.put("data","name is null");
            return result;
        }
        if(StringUtils.isEmpty(deptId)){
            result.put("code",500);
            result.put("data","deptId is null");
            return result;
        }
        if(StringUtils.isEmpty(type)){
            result.put("code",500);
            result.put("data","type is null");
            return result;
        }
        if(StringUtils.isEmpty(isConsume)){
            result.put("code",500);
            result.put("data","isConsume is null");
            return result;
        }
        SysPeople sysPeople=new SysPeople();
        sysPeople.setGh(gh);
        sysPeople.setName(name);
        sysPeople.setDoorNo(doorNo);
        sysPeople.setBranchId(deptId);
        sysPeople.setPhone(phone);
        sysPeople.setType(type);
        sysPeople.setQwid(qwid);
        SysPeople people = peopleService.selectSysPeopleByGh(gh);
        if(people==null){
            peopleService.insertSysPeople(sysPeople);
        }else{
            sysPeople.setId(people.getId());
            sysPeople.setGuid(people.getGuid());
            peopleService.updateSysPeople(sysPeople);
        }
        result.put("code",200);
        result.put("data",sysPeople);

        return result;
    }

    @RequestMapping(value = "delPeopleInfo",method = RequestMethod.POST)
    @ApiOperation("获取peopleInfo")
    @Log(title = "hr人员信息接口删除", businessType = BusinessType.DELETE)
    public JSONObject delPeopleInfo(HttpServletRequest request){
        JSONObject result=new JSONObject();
        String gh=request.getParameter("gh");

        String username=request.getHeader("username");
        String password=request.getHeader("password");


        if(StringUtils.isEmpty(username)){
            result.put("code",500);
            result.put("data","username is null");
            return result;
        }
        if(StringUtils.isEmpty(password)){
            result.put("code",500);
            result.put("data","password is null");
            return result;
        }
        if(!"hr".equals(username)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }
        if(!"admin@123".equals(password)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }

        if(StringUtils.isEmpty(gh)){
            result.put("code",500);
            result.put("data","gh is null");
            return result;
        }


        SysPeople people = peopleService.selectSysPeopleByGh(gh);
        if(people==null){
            result.put("code",500);
            result.put("data","people is null");
            return result;
        }else{
            peopleService.deleteSysPeopleById(people.getId());
        }
        result.put("code",200);
        result.put("data","ok");

        return result;
    }

    @RequestMapping(value = "deptInfo",method = RequestMethod.POST)
    @ApiOperation("获取deptInfo")
    @Log(title = "hr部门信息接口", businessType = BusinessType.UPDATE)
    public JSONObject deptInfo(HttpServletRequest request){
        JSONObject result=new JSONObject();
        String id=request.getParameter("id");
        String parentId=request.getParameter("parentId");
        String name=request.getParameter("name");
        String username=request.getHeader("username");
        String password=request.getHeader("password");


        if(StringUtils.isEmpty(username)){
            result.put("code",500);
            result.put("data","username is null");
            return result;
        }
        if(StringUtils.isEmpty(password)){
            result.put("code",500);
            result.put("data","password is null");
            return result;
        }
        if(!"hr".equals(username)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }
        if(!"admin@123".equals(password)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }
        if("null".equals(id)&&StringUtils.isEmpty(id)){
            result.put("code",500);
            result.put("data","id is null");
        }
        if("name".equals(id)&&StringUtils.isEmpty(name)){
            result.put("code",500);
            result.put("data","name is null");
        }
        if("name".equals(parentId)&&StringUtils.isEmpty(parentId)){
            result.put("code",500);
            result.put("data","parentId is null");
        }
        SysBranch sysBranch=new SysBranch();
        sysBranch.setId(id);
        sysBranch.setName(name);
        sysBranch.setParentId(parentId);

        SysBranch branch = sysBranchService.selectSysBranchById(id);
        if(branch==null){
            sysBranchService.insertSysBranch(sysBranch);
        }else{
            hkCreateBrach(sysBranch);
            sysBranchService.updateSysBranch(sysBranch);
        }
        result.put("code",200);
        result.put("data",sysBranch);

        return result;
    }

    @RequestMapping(value = "delDeptInfo",method = RequestMethod.POST)
    @ApiOperation("删除delDeptInfo")
    @Log(title = "hr部门信息接口删除", businessType = BusinessType.DELETE)
    public JSONObject delDeptInfo(HttpServletRequest request){
        JSONObject result=new JSONObject();
        String id=request.getParameter("id");

        String username=request.getHeader("username");
        String password=request.getHeader("password");


        if(StringUtils.isEmpty(username)){
            result.put("code",500);
            result.put("data","username is null");
            return result;
        }
        if(StringUtils.isEmpty(password)){
            result.put("code",500);
            result.put("data","password is null");
            return result;
        }
        if(!"hr".equals(username)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }
        if(!"admin@123".equals(password)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }

        if(StringUtils.isEmpty(id)){
            result.put("code",500);
            result.put("data","id is null");
            return result;
        }


        SysBranch branch = sysBranchService.selectSysBranchById(id);
        if(branch==null){
            hkDelBrach(id);
            result.put("code",500);
            result.put("data","branch is null");
            return result;
        }else{
            sysBranchService.deleteSysBranchById(branch.getId());
        }
        result.put("code",200);
        result.put("data","ok");

        return result;
    }

    private String hkDelBrach(String id) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecrets);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/org/batch/delete";
        JSONArray list=new JSONArray();
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        String[] indexCode=new String[]{id};
        paramMaps.put("indexCodes",indexCode);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);


        return id;

    }

    private SysBranch hkCreateBrach(SysBranch sysBranch) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecrets);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/org/batch/add";
        JSONArray list=new JSONArray();
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("clientId",123456789);
        paramMaps.put("orgIndexCode", sysBranch.getId());
        paramMaps.put("orgName", sysBranch.getName() );
        paramMaps.put("parentIndexCode", sysBranch.getParentId() );
        list.add(paramMaps);
        String body = JSON.toJSON(list).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        JSONArray list1= (JSONArray) jsons1.get("successes");
        if(list1.size()>0){
            JSONObject objs= (JSONObject)list1.get(0);
            sysBranch.setId(objs.get("orgIndexCode")+"");
        }
        return sysBranch;

    }


    @RequestMapping(value = "consumePeopleDay",method = RequestMethod.POST)
    @ApiOperation("获取consumePeopleDay")
    public JSONObject consumePeopleDay(HttpServletRequest request){
        JSONObject result=new JSONObject();
        String gh=request.getParameter("gh");
        String consumeInterval=request.getParameter("consumeInterval");
        String consumeTime=request.getParameter("consumeTime");
        String type=request.getParameter("type");
        String canteen=request.getParameter("canteen");
        String overtime=request.getParameter("overtime");
        String recordId=request.getParameter("recordId");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String username=request.getHeader("username");
        String password=request.getHeader("password");


        if(StringUtils.isEmpty(username)){
            result.put("code",500);
            result.put("data","username is null");
            return result;
        }
        if(StringUtils.isEmpty(password)){
            result.put("code",500);
            result.put("data","password is null");
            return result;
        }
        if(!"hr".equals(username)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }
        if(!"admin@123".equals(password)){
            result.put("code",500);
            result.put("data","username or password is error");
            return result;
        }
        if("null".equals(gh)&&StringUtils.isEmpty(gh)){
            result.put("code",500);
            result.put("data","gh is null");
        }
        if("null".equals(consumeInterval)&&StringUtils.isEmpty(consumeInterval)){
            result.put("code",500);
            result.put("data","consumeInterval is null");
        }
        if("null".equals(consumeTime)&&StringUtils.isEmpty(consumeTime)){
            result.put("code",500);
            result.put("data","consumeTime is null");
        }
        if("null".equals(type)&&StringUtils.isEmpty(type)){
            result.put("code",500);
            result.put("data","type is null");
        }
       /* if("null".equals(recordId)&&StringUtils.isEmpty(recordId)){
            result.put("code",500);
            result.put("data","recordId is null");
        }*/
        SysPeople sysPeople=new SysPeople();
        sysPeople.setGh(gh);
        SysPeople people = peopleService.selectSysPeopleByGh(gh);
        if(people==null){
            result.put("code",500);
            result.put("data","people is null");
        }else{
            //保存吃饭信息
            ConsumePeopleDay consumePeopleDay=new ConsumePeopleDay();
            try {
                consumePeopleDay.setConsumeTime(dateFormat.parse(consumeTime));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            consumePeopleDay.setEmpId(gh);
            consumePeopleDay.setConsumeInterval(consumeInterval);
            consumePeopleDay.setType(type);
            consumePeopleDay.setAccountId(people.getId()+"");
            consumePeopleDay.setCanteen(canteen);
            consumePeopleDay.setRecordId(recordId);
            consumePeopleDay.setOvertime(overtime);
            if("null".equals(recordId)&&StringUtils.isEmpty(recordId)){
                consumePeopleDayService.insertConsumePeopleDay(consumePeopleDay);
            }else{
                ConsumePeopleDay consumePeopleDays =consumePeopleDayService.selectConsumePeopleDayByRecordId(recordId);
                if(consumePeopleDays!=null){
                    consumePeopleDay.setId(consumePeopleDays.getId());
                    consumePeopleDayService.updateConsumePeopleDay(consumePeopleDay);
                }else{
                    consumePeopleDayService.insertConsumePeopleDay(consumePeopleDay);
                }

            }

        }
        result.put("code",200);
        result.put("data","OK");
        return result;
    }

    @RequestMapping(value = "hkPeopleRecord",method = RequestMethod.POST)
    @ApiOperation("获取海康通行刷卡数据")
    @Log(title = "获取海康通行刷卡数据", businessType = BusinessType.EXPORT)
    public TableDataInfo hkPeopleRecord(Hknfo hknfo,HttpServletRequest request) throws ParseException {
        String username=request.getHeader("username");
        String password=request.getHeader("password");


        if(StringUtils.isEmpty(username)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
        if(StringUtils.isEmpty(password)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
        if(!"hr".equals(username)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
        if(!"admin@123".equals(password)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
        HkPeopleRecord record=new HkPeopleRecord();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(StringUtils.isNotEmpty(hknfo.getStartDate())){
            record.setStartTime(sdf.parse(hknfo.getStartDate()));
        }
        if(StringUtils.isNotEmpty(hknfo.getEndDate())){
            record.setEndTime(sdf.parse(hknfo.getEndDate()));
        }

        record.setGh(hknfo.getGh());
        record.setPeopleName(hknfo.getPeopleName());
        startPage();
        List<HkPeopleRecord> list=hkPeopleRecordService.selectHkPeopleRecordList(record);
        return getDataTable(list);
    }

    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    @RequestMapping(value = "consumeRecord",method = RequestMethod.POST)
    @ApiOperation("获取消费就餐数据")
    @Log(title = "获取消费就餐数据", businessType = BusinessType.EXPORT)
    public TableDataInfo consumeRecord(Hknfo hknfo,HttpServletRequest request) throws ParseException {
        String username=request.getHeader("username");
        String password=request.getHeader("password");


        if(StringUtils.isEmpty(username)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
        if(StringUtils.isEmpty(password)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
        if(!"hr".equals(username)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
        if(!"admin@123".equals(password)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ConsumeRecord consumeRecord=new ConsumeRecord();
        if(StringUtils.isNotEmpty(hknfo.getStartDate())){
            consumeRecord.setStartDate(sdf.parse(hknfo.getStartDate()));
        }
        if(StringUtils.isNotEmpty(hknfo.getEndDate())){
            consumeRecord.setEndDate(sdf.parse(hknfo.getEndDate()));
        }
           consumeRecord.setOutTradeId(hknfo.getOutTradeId());
           consumeRecord.setEmpId(hknfo.getGh());
        startPage();
        List<ConsumeRecord> list=consumeRecordService.selectConsumeRecordList(consumeRecord);
        return getDataTable(list);
    }


    @RequestMapping(value = "app",method = RequestMethod.POST)
    @ApiOperation("获取openid")
    public JSONObject app(@RequestBody JSONObject json){
        String phone=json.get("phone")+"";
        String name=json.get("name")+"";
        String openid=json.get("openid")+"";
        log.info("openid:" + openid);
        JSONObject result=new JSONObject();
        SysPeople people = peopleService.selectSysPeopleByOpenId(openid);
        if(people!=null){//已绑定人员
            result.put("code",200);
            result.put("data",people);
        }else{//未绑定人员
            SysPeople peoples =peopleService.selectSysPeopleByGh(phone,name);
            log.info("人员信信息:" + peoples);
            if(peoples!=null){//已绑定人员
                result.put("data",peoples);
                result.put("code",200);
                peoples.setOpenid(openid);
                peopleService.updateSysPeople(peoples);
            }else{
                result.put("code",200);
            }
        }
        return result;
    }


    @GetMapping(value = "/peopleEwm")
    public AjaxResult getInfo(@RequestParam("id") Long id,@RequestParam("time") Long timeLong)
    {

        SysPeople people =peopleService.selectSysPeopleById(id);

        return success(people);
    }

    @GetMapping(value = "/visEwm")
    public AjaxResult visEwm(@RequestParam("id") Long id,@RequestParam("time") Long timeLong)
    {

        Visitor visitor =visitorService.selectVisitorById(id);

        return success(visitor);
    }

    //根据code获取openid
    @GetMapping(value = "/getOpenIdUser")
    public AjaxResult getInfo(@RequestParam("code") String code)
    {
       //防止统一code重复提交
        String verifyKey = CacheConstants.WX_KEY + code;
        String openid = redisService.getCacheObject(verifyKey);
        SysUser sysUser=new SysUser();
        System.out.println("获取openid==============================" + openid);
        if(StringUtils.isEmpty(openid)) {//重新获取openid
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?&appid=" + appid + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code";
            String response = HttpUtil.getData(url);
            JSONObject json = JSONObject.parseObject(response);
            System.out.println("微信获取openid==============================" + json);
            sysUser = userService.selectUserByOpenId(json.get("openid").toString());
            redisService.setCacheObject(verifyKey,json.get("openid").toString());
            redisService.expire(verifyKey,60*60);
            if (StringUtils.isNull(sysUser)) {
                sysUser=new SysUser();
                sysUser.setOpenid(json.get("openid").toString());
                return success(sysUser);
            }
        }else{
            sysUser= userService.selectUserByOpenId(openid);
            if (StringUtils.isNull(sysUser)) {
                sysUser=new SysUser();
                sysUser.setOpenid(openid);
                return success(sysUser);
            }
        }
        return success(sysUser);
    }

    /**
     * 获取微信公众号token
     *
     * @return
     */
    private String getQyWxToken() {
        String cacheObject = redisService.getCacheObject(CacheConstants.QYWEIXIN_TOKEN);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(cacheObject)) {
            return cacheObject;
        }
        String body = cn.hutool.http.HttpUtil.createGet(qywxToken).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        String string = object.get("access_token").toString();
        redisService.setCacheObject(CacheConstants.QY_LOGIN_TOKEN, string, Long.valueOf(object.get("expires_in").toString()), TimeUnit.SECONDS);
        return string;
    }


    //根据code获取openid
    @GetMapping(value = "/getQyWxUser")
    public AjaxResult getQyWxUser(@RequestParam("code") String code)
    {
        //防止统一code重复提交
        String verifyKey = CacheConstants.WX_KEY + code;
        String openid = redisService.getCacheObject(verifyKey);
        SysUser sysUser=new SysUser();
        System.out.println("获取openid==============================" + openid);
        if(StringUtils.isEmpty(openid)) {//重新获取openid
            //String url = "https://api.weixin.qq.com/sns/oauth2/access_token?&appid=" + appid + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code";
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret ;
            String response = HttpUtil.getData(url);
            JSONObject json = JSONObject.parseObject(response);
            System.out.println("企业微信获取access_token==============================" + json);
            String url1 = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" + getQyWxToken() + "&code=" + code ;
            String response1 = HttpUtil.getData(url1);
            JSONObject json1 = JSONObject.parseObject(response1);
            System.out.println("企业微信获取访问用户身份\n==============================" + json1);
            sysUser = userService.selectUserByOpenId(json1.get("userid").toString());
            redisService.setCacheObject(verifyKey,json1.get("userid").toString());
            redisService.expire(verifyKey,60*60);
            if (StringUtils.isNull(sysUser)) {
                sysUser=new SysUser();
                sysUser.setOpenid(json1.get("userid").toString());
                return success(sysUser);
            }
        }else{
            sysUser= userService.selectUserByOpenId(openid);
            if (StringUtils.isNull(sysUser)) {
                sysUser=new SysUser();
                sysUser.setOpenid(openid);
                return success(sysUser);
            }
        }
        return success(sysUser);
    }







    //根据code获取openid
    @GetMapping(value = "/getWxUser")
    public JSONObject getWxUser(@RequestParam("code") String code)
    {
        JSONObject result=new JSONObject();
        //防止统一code重复提交
        String verifyKey = CacheConstants.WX_KEY + code;
        String openid = redisService.getCacheObject(verifyKey);
        //String openid ="oQvJy6PpmGoEw9TthhcuB1Nnb39E";
        SysPeople people=new SysPeople();
        System.out.println("获取openid==============================" + openid);
        if("null".equals(openid) || StringUtils.isEmpty(openid)) {//重新获取openid
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?&appid=" + appid + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code";
            String response = HttpUtil.getData(url);
            JSONObject json = JSONObject.parseObject(response);
            System.out.println("微信获取openid==============================" + json);
            people = peopleService.selectSysPeopleByOpenId(json.get("openid").toString());
            redisService.setCacheObject(verifyKey,json.get("openid").toString());
            redisService.expire(verifyKey,60*60);
            if (people==null) {
                people=new SysPeople();
                people.setOpenid(json.get("openid").toString());
            }
            result.put("code",200);
            result.put("data",people);
            return result;
        }else{
            people= peopleService.selectSysPeopleByOpenId(openid);
            if (people==null) {
                people=new SysPeople();
                people.setOpenid(openid);
            }
            result.put("code",200);
            result.put("data",people);
            return result;
        }
    }

    /**
     * getSign,初始化config信息
     * @return
     */
    @RequestMapping("/getSign")
    @ResponseBody
    public AjaxResult getSign(HttpServletRequest request, String url) throws Exception {
        String jsapi_ticket  = WeChatUtil.getJsapiTicket(WeChatUtil.getAccessToken());
        Map<String, String> ret = WeChatUtil.sign(jsapi_ticket, url);
        System.out.println("======getSign============="+ret);
        return AjaxResult.success("请求成功",ret);
    }





    @PostMapping("/getPeople")
    public Map<String, Object> getPeople(@RequestBody SysPeople sysPeople)
    {
        Map<String, Object> rspMap = new HashMap<String, Object>();
        SysPeople faceStudents = peopleService.selectSysPeopleByPhoneUser(sysPeople);
        if(faceStudents!=null){
            String token = IdUtils.fastUUID();
            // Jwt存储信息
            Map<String, Object> claimsMap = new HashMap<String, Object>();
            claimsMap.put(SecurityConstants.USER_KEY, token);
            claimsMap.put(SecurityConstants.DETAILS_USER_ID, faceStudents.getId());
            claimsMap.put(SecurityConstants.DETAILS_USERNAME, faceStudents.getName());
            // 接口返回信息
            String access_token= JwtUtils.createToken(claimsMap);
            rspMap.put("access_token", access_token);
            rspMap.put("expires_in", expireTime);
            rspMap.put("sysPeople",faceStudents);
            Claims claims = JwtUtils.parseToken(access_token);
            String userKey = JwtUtils.getUserKey(claims);
            // 根据uuid将loginUser缓存
            redisService.setCacheObject(getTokenKey(userKey), faceStudents, expireTime, TimeUnit.MINUTES);
            log.info("用户登录信息：" + sysPeople);
            peopleService.updatePeopleInfo(sysPeople);
        }
        return  rspMap;
    }

    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }





    /*private AjaxResult sendWeixinJspay(String tradeId, int amounts,String openid) throws Exception {
        WeixinPayConfig wxPayConfig = new WeixinPayConfig();// 支付宝配置

        Map<String,String> params = new HashMap<>();
        params.put("appid",wxPayConfig.getAppid());
        params.put("mch_id",wxPayConfig.getMerchantId());
        params.put("description","测试消费");
        params.put("out_trade_no",tradeId);
        params.put("notify_url",wxPayConfig.getNotify_url());
        Map<String,Object> amount = new HashMap<>();
        amount.put("total",amounts); //订单总金额，单位为分。
        amount.put("currency","CNY");
        params.put("amount",amount.toString());
        params.put("nonce_str", generateNonceStr());
        Map<String,Object> payer = new HashMap<>();
        payer.put("openid",openid);
        params.put("payer",payer.toString());
        //创建Httpclient对象
        HttpClient client = new HttpClient(wxPayConfig.getJspayUrl());
        //支持https协议sorry
        client.setHttps(true);
        //设置请求的参数
        String xml= WXPayUtil.mapToXml(params);
        client.setXmlParam(xml);
        //发送post请求
        client.post();
        //获取请求的响应结果
        String content = client.getContent();
        Map<String, String> map = WXPayUtil.xmlToMap(content);
        if (map.get("result_code").equals("SUCCESS")){//扣款成功
            System.out.println("调用成功");
        }else{
            System.out.println("调用失败");
        }
        // 构造支付参数
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000); // 时间戳
        String nonceStr = WXPayUtil.generateNonceStr(); // 随机字符串
        String packageStr = map.get("prepay_id"); // 预支付订单ID
        String signType = "MD5"; // 签名类型
        //构造签名串
        Map<String,String> param = new HashMap<>();
        param.put("appId",wxPayConfig.getAppid());
        param.put("timeStamp",timestamp);
        param.put("nonceStr",nonceStr);
        param.put("packageStr",packageStr);
        String sign =WXPayUtil.generateSignature(param, wxPayConfig.getApiV3Key());

        Map<String, String> payParams = new HashMap<>();
        payParams.put("appId", wxPayConfig.getAppid());
        payParams.put("timeStamp", timestamp);
        payParams.put("nonceStr", nonceStr);
        payParams.put("package", packageStr);
        payParams.put("signType", signType);
        payParams.put("paySign", sign);
        return AjaxResult.success("调用成功",payParams);
    }


    private AjaxResult sendZfb(String tradeId, Double amounts) throws AlipayApiException {
        AlipayConfig alipayConfig = new AlipayConfig();// 支付宝配置
        String appid=alipayConfig.getAppid();
        String private_key=alipayConfig.getRsa_private_key();
        String public_key=alipayConfig.getAlipay_public_key();
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appid,private_key,"json","GBK",public_key,"RSA2");
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(alipayConfig.getNotify_url());
        *//******必传参数******//*
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", tradeId);
        //支付金额，最小值0.01元 单位为元，精确到小数点后两位
        bizContent.put("total_amount",amounts);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "测试消费");
        //1.条码场景：bar_code；2.刷脸场景：security_code
        bizContent.put("product_code", "QUICK_WAP_WAY");
        request.setBizContent(bizContent.toString());
        AlipayTradePayResponse response = alipayClient.execute(request);
        String pageRedirectionData = response.getBody();
        System.out.println("调用数据"+pageRedirectionData);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
       return AjaxResult.success("调用成功",pageRedirectionData);
    }

    @PostMapping("/alipay_callback")
    public AjaxResult alipay_callback(HttpServletRequest request) {
        try{
            Map<String,String> params = new HashMap<String,String>();
            Map requestParams =request.getParameterMap();
            for(Iterator iter = requestParams.keySet().iterator();iter.hasNext();){
                String name =(String)iter.next();
                String[] values =(String[])requestParams.get(name);
                String valuestr ="";
                for(int i =0 ; i<values.length;i++) {
                    valuestr = (i == values.length - 1) ? valuestr + values[i] : valuestr + values[i] + ",";
                }
                    params.put(name,valuestr);
            }
            System.out.println("支付宝回调,sign: {},trade status: },&数:{)"+params.get("sign")+";"+params.get("trade_status")+";"+params.toString());

            try {
                boolean flag = AlipaySignature.rsaCheckV1
                (params, new AlipayConfig().getAlipay_public_key(), "UTF-8", "RSA2");
                if(flag){
                    if("TRADE_SUCCESS".equals(params.get("trade_status"))){
                        String outTradeNo = params.get("out_trade_no");
                        String tradeNo = params.get("trade no");
                        String tradeStatus = params.get("trade_status");

                    }

                }
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            params.remove("sign_type");


        }catch(Exception e){

        }

        return success();
    }

    @GetMapping("/branchTree")
    public AjaxResult branchTree(SysBranch space)
    {
        return success(sysBranchService.selectSysBranchList(space));
    }

    *//**
     * 新增人员管理
     *//*
    @Log(title = "第三方人员管理", businessType = BusinessType.INSERT)
    @PostMapping("/addOther")
    public AjaxResult addOther(@RequestBody SysPeople sysPeople) throws ExecutionException, InterruptedException {
            //注册设备进行注册
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(sysPeople.getAvatar())) {//是否上传头像，检测照片是否合格
                SysEquipment equipment=new SysEquipment();
                equipment.setIsCj("1");
                equipment.setFlag("0");
                List<SysEquipment> list=equipmentService.selectSysEquipmentList(equipment);
                if(list.size()>0){
                    //人员是否注册
                    String ip=list.get(0).getIp();
                    String pass=list.get(0).getPassword();
                    if(org.apache.commons.lang3.StringUtils.isEmpty(sysPeople.getGuid())){
                        Person person=new Person();
                        person.setName(sysPeople.getName());
                        person.setiDNumber(sysPeople.getIdcard());
                        person.setPhone(sysPeople.getPhone());
                        String data=sdkService.personCreate(person,ip,pass);
                        JSONObject json= JSONObject.parseObject(data);
                        if("1".equals(json.get("result")+"")) {
                            JSONObject obj= (JSONObject) json.get("data");
                            String admitGuid=obj.get("id")+"";
                            sysPeople.setGuid(admitGuid);
                        }else{
                            return error(json.get("msg")+"");
                        }
                    }
                    //人像是否注册
                    String datas = sdkService.imageCreateUrl(sysPeople.getGuid(), sysPeople.getAvatar(), ip, pass);
                    JSONObject jsons = JSONObject.parseObject(datas);
                    if ("1".equals(jsons.get("result")+"")) {
                        if(jsons.get("data")!=null){
                            String faceGuid = jsons.get("data")+"";
                            sysPeople.setFaceGuid(faceGuid);
                        }
                    }else{
                        return error(jsons.get("msg")+"");
                    }
                    //照片检测后删除注册设备人员
                    sdkService.personDelete(sysPeople.getGuid(),ip,pass);
                }
            }else{
                sysPeople.setGuid(IdUtils.simpleUUID());
            }
            sysPeople.setIsSf("1");
           return toAjax(peopleService.insertSysPeople(sysPeople));
    }

    *//**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     *//*
    protected AjaxResult toAjax(int rows)
    {
        return rows > 0 ? AjaxResult.success() : error();
    }*/


    @PostMapping("/uploadMinioCar")
    public R<SysFile> uploadMinioCar(@RequestBody JSONObject data) {
        String url=data.get("url")+"";
        if(StringUtils.isEmpty(url)){
            return R.fail("图片地址不能为空");
        }
        MultipartFile files= PictureUtils.base64ToMultipartFiles(url);
        R<SysFile>  file=remoteFileService.uploadMinioCar(files);
        return file;
    }

    @RequestMapping(value = "remoteCheck",method = RequestMethod.POST)
    public JSONObject remoteCheck(@RequestBody String AccessControllerEvent) throws Exception {
        JSONObject jsonObject = new JSONObject();
        //远控开门
        if(StringUtils.isEmpty(AccessControllerEvent)){
            return jsonObject;
        }
        HkBack obj= JSONObject.parseObject(AccessControllerEvent,HkBack.class);
        if("AccessControllerEvent".equals(obj.getEventType())){//远程核验
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            Date dateTime=sdf.parse(obj.getDateTime());
            HkBackRecord hkBackRecord=obj.getAccessControllerEvent();
            if(hkBackRecord.getRemoteCheck()){
                String checkResult="success";
                String info="核验通过";
                String jobNo="";
                String timeId="";
                //接口校验
                String guid=obj.getAccessControllerEvent().getEmployeeNoString();
                SysPeople peoples=new SysPeople();
                peoples.setGuid(guid);
                SysPeople people=peopleService.selectByGuid(peoples);
                Integer serialNo=obj.getAccessControllerEvent().getSerialNo();
                if(people!=null){
                    //如果是部门卡就不限制次数
                    Date date1=sdf1.parse(sdf2.format(dateTime)+" 14:00:00");
                    Date date2=sdf1.parse(sdf2.format(dateTime)+" 16:00:00");
                    String timeType="";
                    if(date1.getTime()>dateTime.getTime()){
                        timeType="2";
                        timeId="187";
                    }else if(date2.getTime()<dateTime.getTime()){
                        timeType="3";
                        timeId="188";
                    }else{
                        timeType="4";
                        timeId="189";
                    }
                    if("3".equals(people.getType())){
                        checkResult="success";
                    }else {
                        jobNo=people.getGh();
                        Map<String, Object> paramMap =new HashMap<>();
                        paramMap.put("recordDateTime",sdf1.format(dateTime));
                        paramMap.put("code",jobNo);//认证人员员工号
                        paramMap.put("consumeInterval",timeType);
                        //请求当天的消费信息
                        JSONObject json=peopleDay(paramMap);
                        if("0".equals(json.get("code"))){
                            checkResult="success";
                            info=json.get("msg")+"";
                        }else{
                            checkResult="failed";
                            info=json.get("msg")+"";
                        }
                    }
                }else{
                    checkResult="failed";
                    info="人员未注册";
                }
                JSONObject obj1=new JSONObject();
                JSONObject obj2=new JSONObject();
                obj2.put("serialNo",serialNo);
                obj2.put("checkResult",checkResult);
                obj1.put("RemoteCheck",obj2);
                String xml=obj1.toJSONString() ;

                SysEquipment sysEquipment=sysEquipmentService.selectSysEquipmentByIp(obj.getIpAddress());
                String jsonObject2= HttpUtil.putISAPIJson(sysEquipment.getIp(), sysEquipment.getRemark(), sysEquipment.getPassword(), "/ISAPI/AccessControl/remoteCheck?format=json",xml);
                System.out.println("返回信息+++++++++++++++"+jsonObject2);

                /*JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("serialNo",obj.getAccessControllerEvent().getSerialNo());
                jsonObject1.put("checkResult",checkResult);
                jsonObject1.put("info",info);
                jsonObject1.put("audioPrompt",audioPrompt);
                jsonObject.put("RemoteCheck",jsonObject1);*/
                //保存识别记录
                hkBackRecord.setDateTime(dateTime);
                hkBackRecord.setRemark(info);
                hkBackRecord.setSerialNumber(sysEquipment.getSequence());
                hkPeopleRecordService.insertHkPeopleBackRecord(hkBackRecord);
                //hkBackRecordService.insertHkBackRecord(hkBackRecord);
                if("success".equals(checkResult)){
                    ConsumeRecord consumeRecord=new ConsumeRecord();
                    consumeRecord.setConsumeResult("0");
                    consumeRecord.setConsumeMode("3");
                    consumeRecord.setEmpId(jobNo);
                    consumeRecord.setStartDate(dateTime);
                    consumeRecord.setEndDate(new Date());
                    consumeRecord.setAccountId(people.getId()+"");
                    consumeRecord.setResultCode("0");
                    consumeRecord.setPayMode("2");
                    consumeRecord.setOrderType("0");
                    consumeRecord.setCardSn(people.getDoorNo());
                    consumeRecord.setDevId(sysEquipment.getSequence()+"");
                    consumeRecord.setRemark(info);
                    consumeRecord.setTimeId(timeId);
                    consumeRecordService.insertConsumeRecord(consumeRecord);
                }

            }

        }
        if("videoloss".equals(obj.getEventType())){//心跳
            //保存设备离在线状态
            String serialNumber=obj.getSerialNumber();
            /*HkCamera camera =hkCameraService.selectHkCameraByserialNumber(serialNumber);
            if(camera!=null){
                camera.setFlag("1");
                camera.setUpdateTime(new Date());
                hkCameraService.updateHkCamera(camera);
            }*/

        }


        return jsonObject;
    }

    private JSONObject peopleDay(Map<String, Object> paramMap) {
        return consumePeopleDayService.queryPeopleDay(paramMap);
    }

    @RequestMapping(value = "eventRcv",method = RequestMethod.POST)
    public JSONObject eventRcv(String Obj) throws Exception {
        JSONObject jsonObject = new JSONObject();
        System.out.println("事件接受===="+Obj);

        return jsonObject;
    }

    @RequestMapping(value = "personList1",method = RequestMethod.GET)
    public JSONObject personList1() throws Exception {
        JSONObject jsonObject = new JSONObject();

        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecrets);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v2/person/personList";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("pageNo", "1");
        paramMaps.put("pageSize", 1000 );
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        JSONArray list= (JSONArray) jsons1.get("list");
        for(Object obj:list){
            JSONObject objs= (JSONObject)obj;
            SysPeople people=new SysPeople();
            people.setName(objs.get("personName")+"");
            people.setGuid(objs.get("personId")+"");
            people.setBranchId(objs.get("orgIndexCode")+"");
            people.setGh(objs.get("jobNo")+"");
            people.setIsConsume("1");
            SysPeople peoples=peopleService.selectByGuid(people);
            if(peoples==null){
                peopleService.insertSysPeoples(people);
            }

        }

        return jsonObject;
    }

    @RequestMapping(value = "personList2",method = RequestMethod.GET)
    public JSONObject personList2() throws Exception {
        JSONObject jsonObject = new JSONObject();

        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecrets);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v2/person/personList";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("pageNo", "2");
        paramMaps.put("pageSize", 1000 );
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        JSONArray list= (JSONArray) jsons1.get("list");
        for(Object obj:list){
            JSONObject objs= (JSONObject)obj;
            SysPeople people=new SysPeople();
            people.setName(objs.get("personName")+"");
            people.setGuid(objs.get("personId")+"");
            people.setBranchId(objs.get("orgIndexCode")+"");
            people.setGh(objs.get("jobNo")+"");
            people.setSex(objs.get("gender")+"");
            people.setIsConsume("1");
            SysPeople peoples=peopleService.selectByGuid(people);
            if(peoples==null){
                peopleService.insertSysPeoples(people);
            }
        }

        return jsonObject;
    }

    @RequestMapping(value = "vehicleList",method = RequestMethod.GET)
    public JSONObject vehicleList() throws Exception {
        JSONObject jsonObject = new JSONObject();

        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecrets);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/vehicle/advance/vehicleList";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("pageNo", "1");
        paramMaps.put("pageSize", 1000 );
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        JSONArray list= (JSONArray) jsons1.get("list");
        for(Object obj:list){
            JSONObject objs= (JSONObject)obj;
            SysPeople people=new SysPeople();
            people.setGuid(objs.get("personId")+"");
            people.setCarNo(objs.get("plateNo")+"");
            SysPeople peoples=peopleService.selectByGuid(people);
            if(peoples!=null){
                people.setId(peoples.getId());
                peopleService.updateSysPeoples(people);
            }
        }

        return jsonObject;
    }
}
