package io.renren.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.google.gson.Gson;
import io.renren.common.redis.RedisUtils;
import io.renren.config.AlipayConfig;
import io.renren.config.WxPayConfig;
import io.renren.entity.*;
import io.renren.service.*;
import io.renren.util.HttpClient;
import io.renren.util.HttpUtil;
import io.renren.util.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/request")
@Api(tags="消费机接口")
public class CardController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ISysPeopleService peopleService;

    @Autowired
    private ISysEquipmentService equipmentService;

    @Autowired
    private IConsumeRecordService consumeRecordService;

    @Autowired
    private ISysPeopleEquipmentService peopleEquipmentService;

    @Autowired
    private IConsumeTenantService consumeTenantService;

    @Autowired
    private IConsumeTimeIntervalService consumeTimeIntervalService;


    @Autowired
    private IConsumePeopleDayService peopleDayService;
    @Value("${consume.url}")
    private String url;

    @Value("${consume.port}")
    private String port;

    @RequestMapping(value = "heartbeat",method = RequestMethod.POST)
    @ApiOperation("设备上传心跳")
    public JSONObject heartbeat(@RequestBody JSONObject json){
        JSONObject api=new JSONObject();
        Gson gson = new Gson();
        //如果有记录时则要处理记录后再应答，保存后的id回传给设备，方便设备对记录作标志 cardpwd FFFFFFFFFFFF
        //判断设备在线情况
        //获取设备缓存的设备时间

        redisUtils.set(json.get("dev_id")+"",json.get("time"),2*60);
        SysEquipment equipment=equipmentService.selectEquipmentBySequence(json.get("dev_id")+"");

        SysEquipment sysEquipment=new SysEquipment();
        sysEquipment.setBigtype("4");
        List<SysEquipment> list=equipmentService.selectSysEquipmentList(sysEquipment);
        for(SysEquipment e:list){
            String time = redisUtils.get(e.getSequence()+"")+"";
            if(StringUtils.isNotEmpty(time)&&!"null".equals(time)){
                e.setFlag("0");//在线
                equipmentService.updateSysEquipment(e);
            }else{
                e.setFlag("1");
                equipmentService.updateSysEquipment(e);
            }
        }
        //获取设备的参数，只获取一次，当设备更新时再获取一次
        if ("0".equals(equipment.getConsumeFlag())){
            CardEntity  card=new CardEntity();
            card.setApi("parameters");
            Long time=new Date().getTime()/1000;
            card.setTime(time);
            String noncestr= UUID.randomUUID().toString();
            card.setNoncestr(noncestr);
            String sign= EncodeByMD5(time+noncestr+"FFFFFFFFFFFF");
            card.setSign(sign);
            card.setTransaction_id(json.get("transaction_id")+"");
            //设备参数
            JSONArray devSet=new JSONArray();
            JSONObject devSet1=new JSONObject();
            devSet1.put("key","admin_pwd");
            devSet1.put("value",equipment.getPassword());
            devSet1.put("param_id","000000");
            JSONObject devSet2=new JSONObject();
            devSet2.put("key","consume_type");
            devSet2.put("value",equipment.getConsumeType());//消费方式
            devSet2.put("param_id","000000");
            JSONObject devSet3=new JSONObject();
            devSet3.put("key","admin_mend_password1");
            devSet3.put("value",equipment.getPassword());//消费方式
            devSet3.put("param_id","000000");
            JSONObject devSet4=new JSONObject();
            devSet4.put("key","title");
            devSet4.put("value",equipment.getName());
            devSet4.put("param_id","000000");
            devSet.add(devSet1);
            devSet.add(devSet2);
            devSet.add(devSet3);
            devSet.add(devSet4);
            card.setDev_set(devSet);
            //支付宝参数 查询绑定商户支付宝信息
            if(StringUtils.isNotEmpty(equipment.getTenantId()+"")){
                ConsumeTenant consumeTenant=consumeTenantService.selectConsumeTenantById(equipment.getTenantId());
                if(StringUtils.isNotEmpty(consumeTenant.getZfbAppId())){
                    JSONObject zfb=new JSONObject();
                    zfb.put("zfb_app_id",consumeTenant.getZfbAppId());
                    zfb.put("zfb_sys_service_provider_id",consumeTenant.getZfbSysServiceProviderId());
                    zfb.put("zfb_rsa_private_key",consumeTenant.getZfbRsaPrivateKey());
                    zfb.put("zfb_stop",consumeTenant.getZfbStop());
                    zfb.put("zfb_mode",consumeTenant.getZfbMode());
                    zfb.put("param_id","000000");
                    card.setZfb(zfb);
                }
                if(StringUtils.isNotEmpty(consumeTenant.getWxAppid())) {
                    //微信参数 查询绑定商户支付宝信息
                    JSONObject wx = new JSONObject();
                    wx.put("wx_appid",consumeTenant.getWxAppid());
                    wx.put("wx_mch_id",consumeTenant.getWxMchId());
                    wx.put("wx_sub_mch_id",consumeTenant.getWxSubMchId());
                    wx.put("wx_key",consumeTenant.getWxKey());
                    wx.put("wx_stop",consumeTenant.getWxStop());
                    wx.put("wx_mode",consumeTenant.getWxMode());
                    wx.put("param_id","000000");
                    card.setWeixin(wx);
                }
            }
            //时间段 消费方式时间段模式
            if("2".equals(equipment.getConsumeType())){
                //查询时间段信息
                JSONArray timePeriod=new JSONArray();
                List<ConsumeTimeInterval> consumeTimeIntervals=consumeTimeIntervalService.selectConsumeTimeIntervalList(new ConsumeTimeInterval());
                for(ConsumeTimeInterval cti:consumeTimeIntervals ){
                    JSONObject obj=new JSONObject();
                    obj.put("id",cti.getId());
                    obj.put("start_time",cti.getStartTime());
                    obj.put("end_time",cti.getEndTime());
                    obj.put("use_mode",cti.getUseMode());
                    obj.put("tmrtype",cti.getTmrtype());
                    obj.put("level",cti.getLevel());
                    obj.put("maxcount",cti.getMaxcount());
                    if(StringUtils.isNotEmpty(cti.getFixmoney())){
                        obj.put("fixmoney",Double.parseDouble(cti.getFixmoney())*100);
                    }
                    obj.put("consume_type",cti.getConsumeType());
                    obj.put("param_id","000000");
                    timePeriod.add(obj);
                }
                card.setTime_period(timePeriod);
            }
            String cards=gson.toJson(card);
            api=JSONObject.parseObject(cards);
            System.out.println("设备主动请求获取参数==="+api);
            return api;
        }
        //设备版本升级后进行软件推送
        if ("2".equals(equipment.getConsumeFlag())){
            CardEntity  card=new CardEntity();
            card.setApi("upgrade");
            Long time=new Date().getTime()/1000;
            card.setTime(time);
            String noncestr= UUID.randomUUID().toString();
            card.setNoncestr(noncestr);
            String sign= EncodeByMD5(time+noncestr+"FFFFFFFFFFFF");
            card.setSign(sign);
            card.setTransaction_id(json.get("transaction_id")+"");
            card.setInterval(10000L);
            //设备参数
            card.setUrl("http://192.168.19.3:9300/uploadPath/thxf.apk?devid="+json.get("dev_id"));//服务器上地址，注意升级更换
            //card.setUrl("http://192.168.1.92:9300/uploadPath/ynxf.apk?devid="+json.get("dev_id"));//服务器上地址，注意升级更换
            card.setResult_code("0");
            card.setResult_msg("OK");
            String cards=gson.toJson(card);
            api=JSONObject.parseObject(cards);
            equipment.setConsumeFlag("0");
            equipmentService.updateSysEquipment(equipment);
            return api;
        }
        //消费记录
        JSONArray records= JSONArray.parseArray(JSONArray.toJSONString(json.get("records")));
        if(records!=null&&records.size()!=0){
            JSONArray records1=new JSONArray();
            if (records.size()>10){
                for(int i=0;i<10;i++){
                    JSONObject objs= (JSONObject) records.get(i);
                    JSONObject obj=new JSONObject();
                    obj.put("id",objs.get("id"));
                    records1.add(obj);
                    ConsumeRecord consumeRecord = JSONObject.parseObject(String.valueOf(objs), ConsumeRecord.class);
                  /*  //判断是否是同一订单，若是同一订单就不扣钱
                    ConsumeRecord consumeRecords=consumeRecordService.selectConsumeRecordByOutTradeId(consumeRecord.getOutTradeId());
                    if(consumeRecords!=null){
                        break;
                    }*/
                    if(!"null".equals(consumeRecord.getConsumeMoney())){
                        consumeRecord.setConsumeMoney(Double.parseDouble(consumeRecord.getConsumeMoney()+"")/100+"");
                    }else{
                        consumeRecord.setConsumeMoney("");
                    }
                    consumeRecord.setEndDate(new Date(Long.parseLong(consumeRecord.getEndTime())));
                    consumeRecord.setStartDate(new Date(Long.parseLong(consumeRecord.getStartTime())));
                    consumeRecord.setDevId(json.get("dev_id")+"");
                    //判断消费处于什么消费时段
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    List<ConsumeTimeInterval> consumeTimeIntervals=consumeTimeIntervalService.selectConsumeTimeIntervalList(new ConsumeTimeInterval());
                    for(ConsumeTimeInterval cti:consumeTimeIntervals ){
                        try {
                            Date start=sdf1.parse(sdf.format(new Date())+" "+cti.getStartTime());
                            Date end=sdf1.parse(sdf.format(new Date())+" "+cti.getEndTime());
                            //夜餐判断
                            if("3".equals(cti.getTmrtype())){
                                Calendar calendar = new GregorianCalendar();
                                calendar.setTime(end);
                                calendar.add(Calendar.DATE, 1);
                                end = calendar.getTime();
                                if(start.getTime()<new Date().getTime()&&end.getTime()>new Date().getTime()){
                                    consumeRecord.setTimeId(cti.getId());
                                    break;
                                }
                            }else {
                                if(start.getTime()<new Date().getTime()&&end.getTime()>new Date().getTime()){
                                    consumeRecord.setTimeId(cti.getId());
                                    break;
                                }
                            }
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }

                    }
                    try {
                        Long id= Long.parseLong(objs.get("account_id")+"");
                        SysPeople people=peopleService.selectSysPeopleById(id);
                        DecimalFormat df = new DecimalFormat("0.00");
                        /*String je=df.format(people.getBtje()-Double.parseDouble(consumeRecord.getConsumeMoney()));
                        people.setBtje(Double.parseDouble(je));*/
                        if(people.getBtje()>=Double.parseDouble(consumeRecord.getConsumeMoney())){
                            String je=df.format(people.getBtje()-Double.parseDouble(consumeRecord.getConsumeMoney()));
                            people.setBtje(Double.parseDouble(je));
                            consumeRecord.setDiscountMoney(je);
                        }else{
                            Double czje = (people.getBtje()+people.getCzje()-Double.parseDouble(consumeRecord.getConsumeMoney()));
                            people.setBtje((double) 0);
                            consumeRecord.setWalletConsumeMode(df.format(people.getCzje()-czje));
                            people.setCzje(Double.valueOf(df.format(czje)));
                            consumeRecord.setDiscountMoney(df.format(czje));
                        }
                        peopleService.updateSysPeople(people);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    if(!"2".equals(consumeRecord.getOrderType())){//排除更正
                        consumeRecordService.insertConsumeRecord(consumeRecord);
                    }
                }
            }else{
                for(int i=0;i<records.size();i++){
                    JSONObject objs= (JSONObject) records.get(i);
                    JSONObject obj=new JSONObject();
                    obj.put("id",objs.get("id"));
                    records1.add(obj);
                    ConsumeRecord consumeRecord = JSONObject.parseObject(String.valueOf(objs), ConsumeRecord.class);
                   /* //判断是否是同一订单，若是同一订单就不扣钱
                    ConsumeRecord consumeRecords=consumeRecordService.selectConsumeRecordByOutTradeId(consumeRecord.getOutTradeId());
                    if(consumeRecords!=null){
                        break;
                    }*/
                    System.out.println("获取信息===="+consumeRecord.getOutTradeId());
                    if(StringUtils.isEmpty(consumeRecord.getOutTradeId())){

                    }else{
                        if(!"null".equals(consumeRecord.getConsumeMoney())&&StringUtils.isNotEmpty(consumeRecord.getConsumeMoney())){
                            consumeRecord.setConsumeMoney(Double.parseDouble(consumeRecord.getConsumeMoney()+"")/100+"");
                        }else{
                            consumeRecord.setConsumeMoney("");
                        }
                        consumeRecord.setEndDate(new Date(Long.parseLong(consumeRecord.getEndTime())));
                        consumeRecord.setStartDate(new Date(Long.parseLong(consumeRecord.getStartTime())));
                        consumeRecord.setDevId(json.get("dev_id")+"");
                        //判断设备是否是消费时段
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        List<ConsumeTimeInterval> consumeTimeIntervals=consumeTimeIntervalService.selectConsumeTimeIntervalList(new ConsumeTimeInterval());
                        for(ConsumeTimeInterval cti:consumeTimeIntervals ){
                            try {
                                Date start=sdf1.parse(sdf.format(new Date())+" "+cti.getStartTime());
                                Date end=sdf1.parse(sdf.format(new Date())+" "+cti.getEndTime());
                                //夜餐判断
                                if("3".equals(cti.getTmrtype())){
                                    Calendar calendar = new GregorianCalendar();
                                    calendar.setTime(end);
                                    calendar.add(Calendar.DATE, 1);
                                    end = calendar.getTime();
                                    if(start.getTime()<new Date().getTime()&&end.getTime()>new Date().getTime()){
                                        consumeRecord.setTimeId(cti.getId());
                                        break;
                                    }
                                }else {
                                    if(start.getTime()<new Date().getTime()&&end.getTime()>new Date().getTime()){
                                        consumeRecord.setTimeId(cti.getId());
                                        break;
                                    }
                                }
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }

                        }
                        try {
                            Long id= Long.parseLong(objs.get("account_id")+"");
                            SysPeople people=peopleService.selectSysPeopleById(id);
                            DecimalFormat df = new DecimalFormat("0.00");
                          /*  String je=df.format(people.getBtje()-Double.parseDouble(consumeRecord.getConsumeMoney()));
                            people.setBtje(Double.parseDouble(je));*/
                            if(people.getBtje()>=Double.parseDouble(consumeRecord.getConsumeMoney())){
                                String je=df.format(people.getBtje()-Double.parseDouble(consumeRecord.getConsumeMoney()));
                                people.setBtje(Double.parseDouble(je));
                                consumeRecord.setDiscountMoney(je);
                            }else{
                                Double czje = (people.getBtje()+people.getCzje()-Double.parseDouble(consumeRecord.getConsumeMoney()));
                                people.setBtje((double) 0);
                                consumeRecord.setWalletConsumeMode(df.format(people.getCzje()-czje));
                                people.setCzje(Double.valueOf(df.format(czje)));
                                consumeRecord.setDiscountMoney(df.format(czje));
                            }
                            peopleService.updateSysPeople(people);
                           // consumeRecord.setDiscountMoney(je);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        if(!"2".equals(consumeRecord.getOrderType())) {//排除更正
                            consumeRecordService.insertConsumeRecord(consumeRecord);
                        }
                    }
                }
            }
            CardEntity  card=new CardEntity();
            card.setApi("heartbeat");
            Long time=new Date().getTime()/1000;
            card.setTime(time);
            String noncestr= UUID.randomUUID().toString();
            card.setNoncestr(noncestr);
            String sign= EncodeByMD5(time+noncestr+"FFFFFFFFFFFF");
            card.setSign(sign);
            card.setTransaction_id(json.get("transaction_id")+"");
            card.setRecords(records1);
            String cards=gson.toJson(card);
            api=JSONObject.parseObject(cards);
            return api;
        }
        //菜品列表
        JSONArray dishlist= JSONArray.parseArray(JSONArray.toJSONString(json.get("dishlist")));
        if (dishlist!=null){
            //菜品信息
            JSONObject dish= (JSONObject) dishlist.get(0);
            //充值记录
            JSONObject consume= (JSONObject) dishlist.get(1);
        }
        //服务器应答心跳
        CardEntity  card=new CardEntity();
        card.setApi("heartbeat");
        Long time=new Date().getTime()/1000;
        card.setTime(time);
        String noncestr= UUID.randomUUID().toString();
        card.setNoncestr(noncestr);
        String sign= EncodeByMD5(time+noncestr+"FFFFFFFFFFFF");
        card.setSign(sign);
        card.setTransaction_id(json.get("transaction_id")+"");
        //增加名单
        //查询未进入消费人员名单
        SysPeople people=new SysPeople();
        people.setDelFlag(0L);
        people.setEquipmentId(equipment.getId()+"");
        people.setPageNo(20);
        List<SysPeople> sysPeopleList=peopleService.selectSysPeopleList(people);
        if(sysPeopleList!=null&&sysPeopleList.size()>0){
            card.setApi("addperson");
            JSONArray whitelist=new JSONArray();
            for(SysPeople p:sysPeopleList){
                if (StringUtils.isEmpty(p.getEquipmentId())){
                    JSONObject obj=new JSONObject();
                    obj.put("rec_id",p.getId());
                    obj.put("account_id",p.getId());
                    obj.put("emp_id",p.getGh());
                    obj.put("emp_fname",p.getName());
                    obj.put("depart_name",p.getBranch().getName());
                    obj.put("tel",p.getPhone());
                    obj.put("valid_date","2099-01-01");
                    obj.put("level_id","0");
                    obj.put("card_sn",p.getDoorNo());
                    obj.put("url",p.getAvatar());
                    obj.put("groups",0);
                    obj.put("access_pwd",p.getLoginPwd());
                    obj.put("twins","");
                    obj.put("retain_photo","0");
                    whitelist.add(obj);
                    //保存记录
                    SysPeopleEquipment spe=new SysPeopleEquipment();
                    spe.setPeopleId(p.getId());
                    spe.setEquipmentId(equipment.getId());
                    peopleEquipmentService.insertSysPeopleEquipment(spe);
                }
            }
            card.setWhitelist(whitelist);
            String cards=gson.toJson(card);
            api=JSONObject.parseObject(cards);
            return api;
        }
        //删除名单
        SysPeople delpeople=new SysPeople();
        delpeople.setDelFlag(2L);
        delpeople.setEquipmentId(equipment.getId()+"");
        List<SysPeople> delPeopleList=peopleService.selectSysPeopleList(delpeople);
        if(delPeopleList!=null&&delPeopleList.size()>0){
            card.setApi("delperson");
            JSONArray whitelist=new JSONArray();
            for(SysPeople ps:delPeopleList){
                if (StringUtils.isNotEmpty(ps.getEquipmentId())){
                    JSONObject objs=new JSONObject();
                    objs.put("rec_id",ps.getId());
                    objs.put("account_id",ps.getId());
                    objs.put("emp_id",ps.getGh());
                    objs.put("only_del_photo","0");
                    whitelist.add(objs);
                    SysPeopleEquipment spe=new SysPeopleEquipment();
                    spe.setPeopleId(ps.getId());
                    spe.setEquipmentId(equipment.getId());
                    peopleEquipmentService.deleteSysPeopleEquipment(spe);
                }
            }
            card.setWhitelist(whitelist);
            String cards=gson.toJson(card);
            api=JSONObject.parseObject(cards);
            return api;
        }
        //发布菜品
        card.setApi("adddish");


        return api;
    }

    @RequestMapping(value = "addperson",method = RequestMethod.POST)
    @ApiOperation("设备收到增加名单处理结果接口")
    public void addperson(@RequestBody JSONObject json){
        //如果有记录时则要处理记录后再应答，保存后的id回传给设备，方便设备对记录作标志 cardpwd FFFFFFFFFFFF
        JSONArray whitelist= JSONArray.parseArray(JSONArray.toJSONString(json.get("whitelist")));
        for(Object o:whitelist){
            JSONObject objs= (JSONObject) o;
            Long id= Long.parseLong(objs.get("account_id")+"");
            SysPeople people=peopleService.selectSysPeopleById(id);
            String code=objs.get("result_code")+"";
            people.setXfFlag(code);
            String remark="";
            switch(code){
                case "400" :
                    break; //可选
                case "401" :
                    remark="没有个人相片";
                    break; //可选
                case "402" :
                    remark="没有检测到人脸";
                    break; //可选
                case "403" :
                    remark="人脸姿势不正确";
                    break;
                case "404" :
                    remark="检测图片异常";
                    break;
                case "405" :
                    remark="图片超过4M错误";
                    break;
                case "406" :
                    remark="名单超出数量";
                    break;
                case "407" :
                    remark="图片url下载失败";
                    break;
                case "408" :
                    remark="文件写入失败";
                    break;
                case "409" :
                    remark="bitmap转byte数组出错";
                    break;
                case "410" :
                    remark="人脸已存在";
                    break;
                case "411" :
                    remark="人脸模糊";
                    break;
                case "413" :
                    remark="脸部特征被遮挡";
                    break;
                case "414" :
                    remark="人脸图片拍照环境偏暗";
                    break;
                case "415" :
                    remark="人脸图片存在多张人脸";
                    break;
                case "416" :
                    remark="人脸尺寸过小";
                    break;
                case "417" :
                    remark="人脸在边缘位置";
                    break;
                case "418" :
                    remark="人脸相似大于3个";
                    break;
                case "419" :
                    remark="右脸过亮";
                    break;
                case "420" :
                    remark="右脸过暗";
                    break;
                case "421" :
                    remark="左脸过亮";
                    break;
                case "422" :
                    remark="未定义";
                    break;
                case "423" :
                    remark="左脸过暗";
                    break;
                case "424" :
                    remark="下巴和嘴巴过亮";
                    break;
                case "425" :
                    remark="下巴和嘴巴过暗";
                    break;
                case "426" :
                    remark="左眼遮挡";
                    break;
                case "427" :
                    remark="右眼遮挡";
                    break;
                case "428" :
                    remark="鼻子遮挡";
                    break;
                case "429" :
                    remark="嘴巴遮挡";
                    break;
                case "430" :
                    remark="左脸遮挡";
                    break;
                case "431" :
                    remark="右脸遮挡";
                    break;
                case "432" :
                    remark="下巴遮挡";
                    break;
                case "433" :
                    remark="脸部偏暗";
                    break;
                default :
            }
            people.setRemark(remark);
            peopleService.updateSysPeople(people);
        }

    }

    @RequestMapping(value = "delperson",method = RequestMethod.POST)
    @ApiOperation("设备收到删除名单处理结果接口")
    public void delperson(@RequestBody JSONObject json){
        //如果有记录时则要处理记录后再应答，保存后的id回传给设备，方便设备对记录作标志 cardpwd FFFFFFFFFFFF
        json.get("dev_id");



        return;
    }

    @RequestMapping(value = "adddish",method = RequestMethod.POST)
    @ApiOperation("设备上传发布菜品结果")
    public void adddish(@RequestBody JSONObject json){
        System.out.println("设备上传发布菜品结果========="+json);
        //如果有记录时则要处理记录后再应答，保存后的id回传给设备，方便设备对记录作标志 cardpwd FFFFFFFFFFFF




        return;
    }

    @RequestMapping(value = "real", method = RequestMethod.POST)
    @ApiOperation("实时接口")
    public JSONObject real(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        System.out.println("实时接口=========" + json);
        //如果有记录时则要处理记录后再应答，保存后的id回传给设备，方便设备对记录作标志 cardpwd FFFFFFFFFFFF
        String api = json.getString("api");
        //判断是否是人员查询接口
        if ("infoquery".equals(api)) {
            //判断人员查询是否成功
            JSONObject params = JSONObject.parseObject(JSONObject.toJSONString(json.get("params")));
            String code = "0";
            String accountId = "";
            String name = "";
            String gh = "";
            String deptName = "";
            String isLock = "";
            double money = 0;
            if (params != null) {
                Long id = Long.parseLong(params.get("pay_code") + "");
                SysPeople people = peopleService.selectSysPeopleById(id);
                if (people != null) {
                    accountId = people.getId() + "";
                    code = "0";
                    money = (people.getCzje() + people.getBtje());
                    name = people.getName();
                    gh = people.getGh();
                    deptName = people.getBranch().getName();
                    isLock = people.getIsLock();
                } else {
                    code = "1";
                }
            } else {
                code = "1";
            }
            String transactionId = json.get("transaction_id") + "";
            result.put("api", "infoquery");
            result.put("query_code", "0");
            result.put("interval", "10000");
            result.put("result_code", code);
            Long time = new Date().getTime() / 1000;
            String noncestr = UUID.randomUUID().toString();
            result.put("time", time);
            String sign = EncodeByMD5(time + noncestr + "FFFFFFFFFFFF");
            result.put("sign", sign);
            result.put("transaction_id", transactionId);
            result.put("result_msg", "");
            result.put("noncestr", noncestr);
            JSONArray results = new JSONArray();
            JSONObject results1 = new JSONObject();
            results1.put("account_id", accountId);
            results1.put("consume", "");
            results1.put("balance", money);
            results1.put("emp_id", gh);
            results1.put("depart_name", deptName);
            results1.put("sign", EncodeByMD5(accountId + "100000" + time + noncestr + "FFFFFFFFFFFF"));
            results.add(results1);
            result.put("result", results);
            result.put("tts", name + "当前余额" + money + "元");
            JSONArray msg = new JSONArray();
            if ("0".equals(code)) {
                if ("1".equals(isLock)) {
                    JSONObject obj = new JSONObject();
                    obj.put("line", "查询成功");
                    JSONObject obj1 = new JSONObject();
                    obj1.put("line", "账号挂失，请解挂");
                    msg.add(obj);
                    msg.add(obj1);
                    result.put("tts", "账号挂失，请解挂");
                    result.put("result_code", "1");
                } else {
                    JSONObject obj = new JSONObject();
                    obj.put("line", "查询成功");
                    JSONObject obj1 = new JSONObject();
                    obj1.put("line", "当前余额:" + money);
                    msg.add(obj);
                    msg.add(obj1);
                }
            } else {
                JSONObject obj = new JSONObject();
                obj.put("line", "查询失败");
                JSONObject obj1 = new JSONObject();
                obj1.put("line", "人事资料未找到");
                msg.add(obj);
                msg.add(obj1);
                result.put("tts", "查询失败");
            }
            result.put("msg", msg);
            return result;
        }
        //判断是否是无点餐接口
        if ("posonline".equals(api)) {
            //无点餐时上传
            JSONObject params = JSONObject.parseObject(JSONObject.toJSONString(json.get("params")));
            String devId = json.getString("dev_id");
            SysPeople people = new SysPeople();
            //总金额
            Long amount = Long.parseLong(params.get("amount") + "");//交易金额
            String code = "0";
            double money = 0;
            if (StringUtils.isNotEmpty(params.get("pay_code") + "")) {
                Long id = Long.parseLong(params.get("pay_code") + "");
                people = peopleService.selectSysPeopleById(id);
                if ("2".equals(people.getType())) {
                    amount = 100L;
                }
                money = (people.getCzje() + people.getBtje()) * 100;
                if (money >= amount) {
                    code = "0";
                } else {
                    code = "1";
                }
            } else {
                code = "2";
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = sdf1.parse(sdf2.format(new Date()) + " 10:00:00");
                    if (date.getTime() > new Date().getTime()) {
                        amount = 500L;
                    } else {
                        amount = 1500L;
                    }
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            String accountId = people.getId() + "";
            String transactionId = json.get("transaction_id") + "";
            //服务器应答
            result.put("api", "posonline");
            result.put("interval", "10000");
            String noncestr = UUID.randomUUID().toString();
            result.put("noncestr", noncestr);
            Long time = new Date().getTime() / 1000;
            result.put("time", time);
            String sign = EncodeByMD5(time + noncestr + "FFFFFFFFFFFF");
            result.put("sign", sign);
            result.put("transaction_id", transactionId);
            result.put("result_code", code);
            result.put("result_msg", "");
            JSONArray results = new JSONArray();
            JSONObject results1 = new JSONObject();
            results1.put("account_id", accountId);
            results1.put("emp_id", people.getGh());
            results1.put("emp_fname", people.getName());
            results1.put("consume_money", params.get("amount"));
            results1.put("discount_money", "0");
            results1.put("balance", money);
            result.put("trade_id", params.get("trade_id"));
            results1.put("sign", EncodeByMD5(accountId + money + time + noncestr + "FFFFFFFFFFFF"));
            results.add(results1);
            result.put("result", results);
            DecimalFormat df = new DecimalFormat("0.00");
            JSONArray msg = new JSONArray();
          /*  //判断是否是同一订单，若是同一订单就不扣钱
            ConsumeRecord consumeRecords=consumeRecordService.selectConsumeRecordByOutTradeId(params.get("trade_id")+"");
            if(consumeRecords!=null){
                result.put("tts","已有该订单");
                JSONObject obj=new JSONObject();
                obj.put("line","已有该订单" );
                msg.add(obj);
                result.put("msg",msg);
                return  result;
            }*/

            //判断是否二次消费
            if ("0".equals(code)) {
                //判断内部人员是否报餐
                /*if (UpConsume(people)) {
                    result.put("tts", "未报餐");
                    JSONObject obj = new JSONObject();
                    obj.put("line", "未报餐");
                    msg.add(obj);
                    result.put("msg", msg);
                    result.put("result_code", "1");
                    System.out.println("请求当天的消费信息1==="+result);
                    return result;
                }
                if (twoConsume(people)) {
                    result.put("tts", "重复消费");
                    JSONObject obj = new JSONObject();
                    obj.put("line", "重复消费");
                    msg.add(obj);
                    result.put("msg", msg);
                    result.put("result_code", "1");
                    return result;
                }*/
                if ("3".equals(people.getType())) {

                } else if ("2".equals(people.getType())) {

                } else {
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                    Date startDate = new Date(Long.parseLong(params.get("sign_time") + ""));
                    String timeType = "";
                    try {
                        Date date1 = sdf1.parse(sdf2.format(startDate) + " 14:00:00");
                        Date date2 = sdf1.parse(sdf2.format(startDate) + " 16:00:00");
                        if (date1.getTime() > startDate.getTime()) {
                            timeType = "2";
                        } else if (date2.getTime() < startDate.getTime()) {
                            timeType = "3";
                        } else {
                            timeType = "4";
                        }
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("recordDateTime", sdf1.format(startDate));
                    paramMap.put("code", people.getId());//认证人员员工号
                    paramMap.put("consumeInterval", timeType);
                    //请求当天的消费信息
                    JSONObject jsons1 = queryPeopleDay(paramMap);
                    if (!"0".equals(jsons1.get("code") + "")) {
                        result.put("tts", jsons1.get("msg") + "");
                        JSONObject obj = new JSONObject();
                        obj.put("line", jsons1.get("msg") + "");
                        msg.add(obj);
                        result.put("msg", msg);
                        result.put("result_code", "1");
                        return result;
                    }
                }
            }
            System.out.println("result1===" + result);
            //保存消费记录
            ConsumeRecord consumeRecord = new ConsumeRecord();
            consumeRecord.setEmpId(people.getGh());
            if ("null".equals(accountId)) {
                consumeRecord.setAccountId(null);
            } else {
                consumeRecord.setAccountId(accountId);
            }
            consumeRecord.setConsumeMode(params.get("consume_mode") + "");
            consumeRecord.setConsumeMoney(Double.parseDouble(amount + "") / 100 + "");
            consumeRecord.setOutTradeId(params.get("trade_id") + "");
            consumeRecord.setStartTime(params.get("sign_time") + "");
            consumeRecord.setEndTime(new Date().getTime() + "");
            consumeRecord.setResultCode("0");
            consumeRecord.setPayMode(params.get("pay_mode") + "");
            consumeRecord.setOrderType("0");
            consumeRecord.setWalletConsumeMode("0");
            consumeRecord.setDevId(devId);
            Date startDate = new Date(Long.parseLong(params.get("sign_time") + ""));
            consumeRecord.setStartDate(startDate);
            consumeRecord.setEndDate(new Date());
            if ("0".equals(code)) {
                double amounts = Double.parseDouble(amount + "") / 100;
                //result.put("tts","消费"+df.format(amounts)+"元");
                result.put("tts", "谢谢");
                JSONObject obj = new JSONObject();
                obj.put("line", "姓名:" + people.getName());
                msg.add(obj);
                JSONObject obj1 = new JSONObject();
                obj1.put("line", "消费:" + df.format(amounts) + "元");
                msg.add(obj1);
                JSONObject obj2 = new JSONObject();
                obj2.put("line", "余:" + df.format((money - amount) / 100) + "元");
                msg.add(obj2);
                consumeRecord.setDiscountMoney(df.format((money - amount) / 100));
                if (people.getBtje() * 100 >= amount) {
                    Double btje = (people.getBtje() * 100 - amount) / 100;
                    people.setBtje(Double.valueOf(df.format(btje)));
                } else {
                    people.setBtje((double) 0);
                    Double czje = (money - amount) / 100;
                    consumeRecord.setWalletConsumeMode(df.format(people.getCzje() - czje));
                    people.setCzje(Double.valueOf(df.format(czje)));
                }
                peopleService.updateSysPeople(people);
            } else if ("2".equals(code)) {
                //支付宝(暂时接入支付宝支付)/微信支付
                String qrCode = params.get("qr_code") + "";
                if (this.codevale(qrCode)) {
                    consumeRecord.setConsumeResult("0");
                    consumeRecord.setPayMode("3");
                    consumeRecord.setRemark("支付宝支付");
                    try {
                        AlipayConfig alipayConfig = new AlipayConfig();// 支付宝配置
                        if (alipayConfig.isIsable()) {
                            double amounts = Double.parseDouble(amount + "") / 100;
                            result.put("tts", "消费" + df.format(amounts) + "元");
                            result.put("result_code", "0");
                            //result.put("tts","谢谢");
                            JSONObject obj = new JSONObject();
                            obj.put("line", "消费" + df.format(amounts) + "元");
                            JSONObject obj1 = new JSONObject();
                            obj1.put("line", "支付宝支付");
                            msg.add(obj);
                            msg.add(obj1);
                            sendZfb(params.get("trade_id") + "", qrCode, amounts);
                        } else {
                            double amounts = Double.parseDouble(amount + "") / 100;
                            result.put("tts", "消费" + df.format(amounts) + "元失败,请联系管理员");
                            result.put("result_code", "1");
                            JSONObject obj = new JSONObject();
                            obj.put("line", "消费" + df.format(amounts) + "元失败,请联系管理员");
                            JSONObject obj1 = new JSONObject();
                            obj1.put("line", "支付宝支付");
                            msg.add(obj);
                            msg.add(obj1);
                            consumeRecord.setConsumeResult("1");
                        }
                    } catch (AlipayApiException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    consumeRecord.setConsumeResult("0");
                    consumeRecord.setPayMode("4");
                    consumeRecord.setRemark("微信支付");
                    try {
                        WxPayConfig wxPayConfig = new WxPayConfig();//微信配置
                        if (wxPayConfig.isIsable()) {
                            double amounts = Double.parseDouble(amount + "") / 100;
                            result.put("tts", "消费" + df.format(amounts) + "元");
                            result.put("result_code", "0");
                            // result.put("tts","谢谢");
                            JSONObject obj = new JSONObject();
                            obj.put("line", "消费" + df.format(amounts) + "元");
                            JSONObject obj1 = new JSONObject();
                            obj1.put("line", "微信支付");
                            msg.add(obj);
                            msg.add(obj1);
                            sendWeixin(params.get("trade_id") + "", qrCode, Integer.parseInt(amount + ""), consumeRecord);
                        } else {
                            double amounts = Double.parseDouble(amount + "") / 100;
                            result.put("tts", "消费" + df.format(amounts) + "元失败,请联系管理员");
                            JSONObject obj = new JSONObject();
                            obj.put("line", "消费" + df.format(amounts) + "元失败,请联系管理员");
                            JSONObject obj1 = new JSONObject();
                            obj1.put("line", "微信支付");
                            msg.add(obj);
                            msg.add(obj1);
                            consumeRecord.setConsumeResult("1");
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } else {
                result.put("tts", "余次不足");
                JSONObject obj = new JSONObject();
                obj.put("line", "余次不足");
                JSONObject obj1 = new JSONObject();
                obj1.put("line", "当前余次：" + df.format(money / 100));
                msg.add(obj);
                msg.add(obj1);
                consumeRecord.setConsumeResult("1");
                consumeRecord.setRemark("余额不足");
            }
            consumeRecord.setDevId(json.get("dev_id") + "");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<ConsumeTimeInterval> consumeTimeIntervals = consumeTimeIntervalService.selectConsumeTimeIntervalList(new ConsumeTimeInterval());
            for (ConsumeTimeInterval cti : consumeTimeIntervals) {
                try {
                    Date start = sdf1.parse(sdf.format(new Date()) + " " + cti.getStartTime());
                    Date end = sdf1.parse(sdf.format(new Date()) + " " + cti.getEndTime());
                    if ("3".equals(cti.getTmrtype())) {
                        Calendar calendar = new GregorianCalendar();
                        calendar.setTime(end);
                        calendar.add(Calendar.DATE, 1);
                        end = calendar.getTime();
                        if (start.getTime() < new Date().getTime() && end.getTime() > new Date().getTime()) {
                            consumeRecord.setTimeId(cti.getId());
                            break;
                        }
                    } else {
                        if (start.getTime() < new Date().getTime() && end.getTime() > new Date().getTime()) {
                            consumeRecord.setTimeId(cti.getId());
                            break;
                        }
                    }
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

            }
            if (!"2".equals(consumeRecord.getOrderType())) {//排除更正
                consumeRecordService.insertConsumeRecord(consumeRecord);
            }
            result.put("msg", msg);
            System.out.println("系统发送数据====" + result);
            return result;
        }
        if ("recordquery".equals(api)) {//查询记录recordquery应答
            String transactionId = json.get("transaction_id") + "";
            String devId = json.get("dev_id") + "";
            //服务器应答
            result.put("api", "recordquery");
            result.put("interval", "10000");
            String noncestr = UUID.randomUUID().toString();
            result.put("noncestr", noncestr);
            Long time = new Date().getTime() / 1000;
            result.put("time", time);
            String sign = EncodeByMD5(time + noncestr + "FFFFFFFFFFFF");
            result.put("sign", sign);
            result.put("transaction_id", transactionId);
            ConsumeRecord consumeRecord = new ConsumeRecord();
            consumeRecord.setDevId(devId);
            List<ConsumeRecord> list = consumeRecordService.selectConsumeRecordAllList(consumeRecord);
            String code = "0";
            if (list.size() > 0) {
                code = "0";
            } else {
                code = "1";
            }
            result.put("result_code", code);
            result.put("result_msg", "");
            result.put("tts", "查询成功");
            JSONArray msg = new JSONArray();
            for (ConsumeRecord cr : list) {
                JSONObject obj = new JSONObject();
                if ("1".equals(cr.getConsumeResult())) {
                    obj.put("line", "姓名：" + cr.getAccountName() + "，消费失败：" + cr.getConsumeMoney() + "元 " + cr.getRemark());
                } else {
                    obj.put("line", "姓名：" + cr.getAccountName() + "，消费成功：" + cr.getConsumeMoney() + "元");
                }
                msg.add(obj);
            }
            result.put("msg", msg);

            return result;
        }
        if ("correctonline".equals(api)) {//查询记录recordquery应答
            String transactionId = json.get("transaction_id") + "";
            String devId = json.get("dev_id") + "";
            //服务器应答
            result.put("api", "correctonline");
            result.put("interval", "10000");
            String noncestr = UUID.randomUUID().toString();
            result.put("noncestr", noncestr);
            Long time = new Date().getTime() / 1000;
            result.put("time", time);
            String sign = EncodeByMD5(time + noncestr + "FFFFFFFFFFFF");
            result.put("sign", sign);
            result.put("transaction_id", transactionId);
            JSONArray results = new JSONArray();
            JSONObject results1 = new JSONObject();
            String accountId = "";
            JSONObject params = JSONObject.parseObject(JSONObject.toJSONString(json.get("params")));
            String code = "0";
            if (params != null) {
                Long id = Long.parseLong(params.get("pay_code") + "");
                SysPeople people = peopleService.selectSysPeopleById(id);
                if (people != null) {
                    accountId = people.getId() + "";
                    code = "0";
                } else {
                    code = "1";
                }
                ConsumeRecord consumeRecord = new ConsumeRecord();
                consumeRecord.setDevId(devId);
                consumeRecord.setAccountId(params.get("pay_code") + "");
                List<ConsumeRecord> list = consumeRecordService.selectConsumeRecordList(consumeRecord);
                Double amount = Double.valueOf(0);
                if (list.size() > 0) {
                    ConsumeRecord consumeRecords = list.get(0);
                    if ("1".equals(consumeRecords.getConsumeResult()) && "更正消费".equals(consumeRecords.getRemark())) {
                        code = "2";
                    } else {
                        amount = Double.parseDouble(consumeRecords.getConsumeMoney());
                        consumeRecords.setConsumeResult("1");
                        consumeRecords.setRemark("更正消费");
                        consumeRecordService.updateConsumeRecord(consumeRecords);
                        DecimalFormat df = new DecimalFormat("0.00");
                        if ("0".equals(consumeRecords.getWalletConsumeMode())) {
                            people.setBtje(Double.valueOf(df.format(amount + people.getBtje())));
                        } else {
                            people.setCzje(Double.parseDouble(consumeRecords.getWalletConsumeMode()) + people.getCzje());
                            if (amount > Double.parseDouble(consumeRecords.getWalletConsumeMode())) {
                                people.setBtje(Double.valueOf(amount - Double.parseDouble(consumeRecords.getWalletConsumeMode())));
                            }
                        }
                        peopleService.updateSysPeople(people);
                        code = "0";
                    }
                } else {
                    code = "1";
                }
                result.put("result_msg", "");
                result.put("tts", "退款" + amount + "元");
                double money = (people.getCzje() + people.getBtje()) * 100;
                results1.put("account_id", accountId);
                results1.put("emp_id", people.getGh());
                results1.put("emp_fname", people.getName());
                results1.put("consume_money", amount * 100 + "");
                results1.put("balance", money + amount * 100 + "");
                results1.put("trade_id", params.get("trade_id"));
                results1.put("sign", EncodeByMD5(accountId + people.getGh() + people.getName() + amount * 100 + time + noncestr + "FFFFFFFFFFFF"));
                results.add(results1);
                result.put("result", results);
            } else {
                code = "1";
            }
            result.put("result_code", code);
            JSONArray msg = new JSONArray();
            if ("0".equals(code)) {
                JSONObject obj = new JSONObject();
                obj.put("line", "更正成功");
                msg.add(obj);
            } else if ("2".equals(code)) {
                JSONObject obj = new JSONObject();
                obj.put("line", "最近消费记录已更正");
                msg.add(obj);
            } else {
                JSONObject obj = new JSONObject();
                obj.put("line", "更正失败");
                msg.add(obj);
            }
            result.put("msg", msg);
            System.out.println("发送的json====" + result);
            return result;
        }
        if ("sumonline".equals(api)) {//汇总sumonline应答
            String transactionId = json.get("transaction_id") + "";
            String devId = json.get("dev_id") + "";
            //服务器应答
            result.put("api", "sumonline");
            result.put("interval", "10000");
            String noncestr = UUID.randomUUID().toString();
            result.put("noncestr", noncestr);
            Long time = new Date().getTime() / 1000;
            result.put("time", time);
            String sign = EncodeByMD5(time + noncestr + "FFFFFFFFFFFF");
            result.put("sign", sign);
            result.put("transaction_id", transactionId);
            result.put("result_msg", "");
            String code = "0";
            result.put("result_code", code);
            result.put("tts", "消费汇总");
            JSONArray msg = new JSONArray();
            if ("0".equals(code)) {
                JSONObject obj1 = new JSONObject();
                obj1.put("line", "当日汇总");
                msg.add(obj1);
                List<Map<String, Object>> list = consumeRecordService.selectConsumeRecordSumonline(devId);
                for (Map<String, Object> cr : list) {
                    JSONObject obj = new JSONObject();
                    obj.put("line", cr.get("name") + "：次数：" + cr.get("num") + "次，消费：" + cr.get("money") + "元");
                    msg.add(obj);
                }
                JSONObject obj2 = new JSONObject();
                obj2.put("line", "当月汇总");
                msg.add(obj2);
                List<Map<String, Object>> lists = consumeRecordService.selectConsumeRecordSumonlineMonth(devId);
                for (Map<String, Object> cr : lists) {
                    JSONObject obj = new JSONObject();
                    obj.put("line", cr.get("name") + "：次数：" + cr.get("num") + "次，消费：" + cr.get("money") + "元");
                    msg.add(obj);
                }
            } else {
                JSONObject obj = new JSONObject();
                obj.put("line", "查询失败");
                msg.add(obj);
            }
            result.put("msg", msg);
            return result;
        }
        if ("rechargeonline".equals(api)) {//汇总sumonline应答
            JSONObject params = JSONObject.parseObject(JSONObject.toJSONString(json.get("params")));
            Long amount = Long.parseLong(params.get("amount") + "");//交易金额
            String account_id = params.get("pay_code") + "";
            String trade_id = params.get("trade_id") + "";

            SysPeople people = peopleService.selectSysPeopleById(Long.parseLong(account_id));
            String transactionId = json.get("transaction_id") + "";
            //服务器应答
            result.put("api", "rechargeonline");
            result.put("interval", "10000");
            String noncestr = UUID.randomUUID().toString();
            result.put("noncestr", noncestr);
            Long time = new Date().getTime() / 1000;
            result.put("time", time);
            String sign = EncodeByMD5(time + noncestr + "FFFFFFFFFFFF");
            result.put("sign", sign);
            result.put("transaction_id", transactionId);
            result.put("result_msg", "");
            String code = "0";
            result.put("result_code", code);
            double amounts = Double.parseDouble(amount + "") / 100;
            result.put("tts", "充值" + amounts + "元");
            JSONArray msg = new JSONArray();
            if ("0".equals(code)) {
                JSONObject obj1 = new JSONObject();
                obj1.put("line", "姓名:" + people.getName());
                msg.add(obj1);
                JSONObject obj2 = new JSONObject();
                obj2.put("line", "充值:" + amounts);
                msg.add(obj2);
                JSONObject obj3 = new JSONObject();
                obj3.put("line", "余:");
                msg.add(obj3);
                DecimalFormat df = new DecimalFormat("0.00");
                Double czje = people.getCzje() + amounts;
                people.setCzje(Double.valueOf(df.format(czje)));
                peopleService.updateSysPeople(people);
            } else {
                JSONObject obj = new JSONObject();
                obj.put("line", "充值失败");
                msg.add(obj);
            }
            result.put("msg", msg);
            JSONArray result1 = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("account_id", account_id);
            obj.put("emp_id", people.getGh());
            obj.put("emp_fname", people.getName());
            obj.put("consume_money", amount);
            obj.put("trade_id", params.get("trade_id") + "");
            String sign1 = EncodeByMD5(account_id + people.getGh() + people.getName() + amount + trade_id + time + noncestr + "FFFFFFFFFFFF");
            obj.put("sign", sign1);
            result1.add(obj);
            result.put("result", result1);
            return result;
        }
        return result;
    }

    public JSONObject queryPeopleDay(Map<String, Object> paramMap) {
        JSONObject obj=new JSONObject();
        ConsumePeopleDay consumePeopleDay=new ConsumePeopleDay();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf1.parse(paramMap.get("recordDateTime")+"");
            consumePeopleDay.setConsumeTime(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        consumePeopleDay.setAccountId(paramMap.get("code")+"");
        consumePeopleDay.setConsumeInterval(paramMap.get("consumeInterval")+"");
        List<ConsumePeopleDay> list=peopleDayService.selectConsumePeopleDayList(consumePeopleDay);
        if(list.size()>0){
            ConsumePeopleDay consumePeople=list.get(0);
            if("1".equals(consumePeople.getIsConsume())){
                obj.put("code","2");
                obj.put("msg",consumePeople.getAccountName()+"重复就餐");
                return obj;
            }else{
                obj.put("code","0");
                obj.put("msg",consumePeople.getAccountName()+"核验通过");
                consumePeople.setIsConsume("1");
                consumePeople.setUpdateTime(new Date());
                peopleDayService.updateConsumePeopleDay(consumePeople);
                return obj;
            }
        }else{
            obj.put("code","1");
            obj.put("msg","未报餐");
        }
        return obj;
    }

    private boolean UpConsume(SysPeople people) {
        if("3".equals(people.getType())){
            return false;
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime=new  Date();
        String timeType="4";
        try {
            Date date=sdf1.parse(sdf2.format(new Date())+" 10:00:00");
            Date date1=sdf1.parse(sdf2.format(new Date())+" 14:00:00");
            Date date2=sdf1.parse(sdf2.format(new Date())+" 16:00:00");
            if(date.getTime()>dateTime.getTime()){
                timeType="1";
            }else if(date.getTime()<dateTime.getTime()&&date1.getTime()>dateTime.getTime()){
                timeType="2";
            }else if(date2.getTime()<dateTime.getTime()){
                timeType="3";
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        boolean flag=true;
        ConsumePeopleDay consumePeopleDay=new ConsumePeopleDay();
        consumePeopleDay.setAccountId(people.getId()+"");
        consumePeopleDay.setConsumeTime(dateTime);
        consumePeopleDay.setConsumeInterval(timeType);
        List<ConsumePeopleDay> list=peopleDayService.selectConsumePeopleDayList(consumePeopleDay);
        if(list.size()>0){
            flag=false;
        }else{
            flag=true;
        }
        return flag;
    }

    private boolean twoConsume(SysPeople people) {
        boolean flag=true;
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime=new  Date();
        Long timeType=null;
        try {
            Date date=sdf1.parse(sdf2.format(new Date())+" 10:00:00");
            Date date1=sdf1.parse(sdf2.format(new Date())+" 14:00:00");
            Date date2=sdf1.parse(sdf2.format(new Date())+" 16:00:00");
            if(date.getTime()>dateTime.getTime()){
                timeType=186L;
            }else if(date.getTime()<dateTime.getTime()&&date1.getTime()>dateTime.getTime()){
                timeType=187L;
            }else if(date2.getTime()<dateTime.getTime()){
                timeType=188L;
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        ConsumeRecord consumeRecord=new ConsumeRecord();
        consumeRecord.setAccountId(people.getId()+"");
        consumeRecord.setTimeId(timeType);
        List<ConsumeRecord> list = consumeRecordService.selectConsumeRecordAllList(consumeRecord);
        if("3".equals(people.getType())){
            flag=false;
            if(StringUtils.isNotEmpty(people.getXfcs())){
                if(Integer.parseInt(people.getXfcs())>list.size()){
                    flag=false;
                }else{
                    flag=true;
                }
            }
            return flag;
        }
        if(list.size()>0){
            flag=true;
        }else{
            flag=false;
        }
        return flag;
    }

    @RequestMapping(value = "selfserver/queryRecord",method = RequestMethod.POST)
    @ApiOperation("自助机自助查询界面")
    public JSONObject queryRecord(@RequestBody JSONObject json){
        System.out.println("查询人员的消费充值记录========="+json);
        JSONObject result=new JSONObject();
        String id=json.get("account_id")+"";
        result.put("state","0");
        result.put("msg","成功");
        result.put("result",url+"pages/consume/consumeRecord/index?id="+id);

        return result;
    }

    @RequestMapping(value = "selfserver/queryRechargeRecord",method = RequestMethod.POST)
    @ApiOperation("自助机查询待退款订单记录")
    public JSONObject queryRechargeRecord(@RequestBody JSONObject json){
        System.out.println("查询待退款订单记录, 只能查询微信或支付宝的充值记录========="+json);
        //{"transaction_id":"100","fireware":"XF108-Y-SV1.020240822","ip":"192.168.124.52","build_time":"2024-09-20 15-19-58","sign":"feddcdb6fcb522110ff748930160a550","version":"V1.0.3","mac":"E8519E98F18D","noncestr":"359ff14bd3ad4f78be564dee92a3d622","dev_id":"1","serialno":"99032CFCBDFFEF1A","account_id":"578173","total_amount":0,"refund_amount":0,"return_money":0,"model":"17","pay_type":0,"time":"1727166839717","customer":"385946"}
        String id=json.get("account_id")+"";
        SysPeople people=peopleService.selectSysPeopleById(Long.parseLong(id));
        JSONObject result=new JSONObject();
        JSONObject obj=new JSONObject();
        JSONArray array=new JSONArray();
        obj.put("balance",people.getBtje()+people.getCzje());
        obj.put("rechargeRecord",array);
        result.put("state","1");
        result.put("msg","退款失败，请联系财务退款！");
        result.put("result",obj);
        return result;
    }

    @RequestMapping(value = "selfserver/rechargeRefund",method = RequestMethod.POST)
    @ApiOperation("自助机退款")
    public void rechargeRefund(@RequestBody JSONObject json){
        System.out.println("退款========="+json);




        return;
    }

    @RequestMapping(value = "realpass", method = RequestMethod.POST)
    @ApiOperation("人脸设备实时控制")
    public JSONObject realpass(@RequestBody JSONObject json) {
        System.out.println("人脸设备实时控制=========" + json);
        JSONObject result = new JSONObject();
        JSONObject params = JSONObject.parseObject(JSONObject.toJSONString(json.get("params")));
        String account_id = params.getString("pay_code");
        String devId = json.getString("dev_id");
        SysPeople people = peopleService.selectSysPeopleById(Long.parseLong(account_id));
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = new Date(params.getLong("sign_time"));
        String timeType = "";
        Long timeId = 0L;
        try {
            Date date1 = sdf1.parse(sdf2.format(startDate) + " 14:00:00");
            Date date2 = sdf1.parse(sdf2.format(startDate) + " 16:00:00");
            if (date1.getTime() > startDate.getTime()) {
                timeType = "2";
                timeId = 187L;
            } else if (date2.getTime() < startDate.getTime()) {
                timeType = "3";
                timeId = 188L;
            } else {
                timeType = "4";
                timeId = 189L;
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("recordDateTime", sdf1.format(startDate));
        paramMap.put("code", people.getId());//认证人员员工号
        paramMap.put("consumeInterval", timeType);
        //请求当天的消费信息
        JSONObject jsons1 = queryPeopleDay(paramMap);
        if (!"0".equals(jsons1.get("code") + "")) {
            result.put("tts", jsons1.get("msg") + "");
            result.put("result_code", "1");
            Long time = new Date().getTime() / 1000;
            String noncestr = UUID.randomUUID().toString();
            result.put("noncestr", noncestr);
            JSONArray results = new JSONArray();
            JSONObject results1 = new JSONObject();
            results1.put("account_id", account_id);
            results1.put("emp_id", people.getGh());
            results1.put("emp_fname", people.getName());
            results1.put("card_sn", people.getDoorNo());
            results.add(results1);
            result.put("result", results);
            result.put("time", time);
            String sign = EncodeByMD5(time + noncestr + "FFFFFFFFFFFF");
            result.put("sign", sign);
            result.put("result_msg", jsons1.get("msg") + "");
            return result;
        }
        result.put("tts", "请通行");
        result.put("result_code", 0);
        Long time = new Date().getTime() / 1000;
        String noncestr = UUID.randomUUID().toString();
        result.put("noncestr", noncestr);
        JSONArray results = new JSONArray();
        JSONObject results1 = new JSONObject();
        results1.put("account_id", account_id);
        results1.put("emp_id", people.getGh());
        results1.put("emp_fname", people.getName());
        results1.put("card_sn", people.getDoorNo());
        results.add(results1);
        result.put("result", results);
        result.put("time", time);
        String sign = EncodeByMD5(time + noncestr + "FFFFFFFFFFFF");
        result.put("sign", sign);
        result.put("result_msg", "请通行");
        //保存消费记录
        ConsumeRecord consumeRecord = new ConsumeRecord();
        consumeRecord.setEmpId(people.getGh());
        if ("null".equals(account_id)) {
            consumeRecord.setAccountId(null);
        } else {
            consumeRecord.setAccountId(account_id);
        }
        consumeRecord.setConsumeMode(params.get("consume_mode") + "");
        consumeRecord.setConsumeMoney("");
        consumeRecord.setOutTradeId(params.get("trade_id") + "");
        consumeRecord.setStartTime(params.get("sign_time") + "");
        consumeRecord.setEndTime(new Date().getTime() + "");
        consumeRecord.setResultCode("0");
        consumeRecord.setPayMode(params.get("pay_mode") + "");
        consumeRecord.setOrderType("0");
        consumeRecord.setWalletConsumeMode("0");
        consumeRecord.setDevId(devId);
        consumeRecord.setStartDate(startDate);
        consumeRecord.setEndDate(new Date());
        consumeRecord.setTimeId(timeId);
        consumeRecordService.insertConsumeRecord(consumeRecord);
        return result;
    }



    private void sendWeixin(String trade_id, String qrCode, int amounts,ConsumeRecord consumeRecord) throws Exception {
        WxPayConfig wxPayConfig = new WxPayConfig();// 支付宝配置

        Map<String,String> params = new HashMap<>();
        params.put("appid",wxPayConfig.getAppid());
        params.put("mch_id",wxPayConfig.getMerchantId());
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        params.put("body","泰禾食堂消费");
        params.put("out_trade_no",trade_id);
        params.put("total_fee",amounts+"");
        params.put("auth_code",qrCode);
        //未来写成项目部署的ip
        params.put("spbill_create_ip",wxPayConfig.getSpbill_create_ip());
        //生成签名
        String sign = WXPayUtil.generateSignature(params, wxPayConfig.getApiV3Key());
        params.put("sign",sign);
        //创建Httpclient对象
        HttpClient client = new HttpClient(wxPayConfig.getMicropayUrl());
        //支持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")){//扣款成功
            consumeRecord.setOpenid(map.get("openid"));
            //根据openid查询人员
            SysPeople people=peopleService.selectSysPeopleByOpenId(map.get("openid"));
            if(people!=null){
                consumeRecord.setAccountId(people.getId()+"");
                consumeRecord.setEmpId(people.getGh());
            }
        }else{
            consumeRecord.setConsumeResult("1");
        }



    }


    private void sendZfb(String tradeId, String qrCode, 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("scene", "bar_code");
        //根据auth_code_type上传付款码，auth_code_type=bar_code，则填写用户支付宝钱包中的付款码；auth_code_type=security_code，则填写设备刷脸返回的付款码；
        bizContent.put("auth_code", qrCode);
        request.setBizContent(bizContent.toString());
        AlipayTradePayResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

    private boolean codevale(String qrCode) {
        char[] array = qrCode.toCharArray();
        if (array[0] == '2')
        {
            //支付宝
            if (array[1] == '5'
                    || array[1] == '6'
                    || array[1] == '7'
                    || array[1] == '8'
                    || array[1] == '9')
            {
                if (array.length >= 16 && array.length <= 24)
                {
                    return true;
                }
            }
        }
        return false;
    }


    @RequestMapping(value = "takephoto",method = RequestMethod.POST)
    @ApiOperation("设备上传自助拍照结果")
    public JSONObject takephoto(@RequestBody JSONObject json){
        JSONObject result=new JSONObject();
        //如果有记录时则要处理记录后再应答，保存后的id回传给设备，方便设备对记录作标志 cardpwd FFFFFFFFFFFF
        System.out.println("设备上传自助拍照结果========="+json);
        String account_id=json.get("account_id")+"";
        String photo=json.get("photo")+"";
        Map<String, Object> paramMap=new HashMap<>();
        paramMap.put("url",photo);
        String repose= HttpUtil.postData(port+"system/api/uploadMinioCar",paramMap);
        JSONObject obj=JSONObject.parseObject(repose);
        JSONObject datas= (JSONObject) obj.get("data");
        String url=datas.get("url")+"";
        SysPeople people =new SysPeople();
        people.setId(Long.parseLong(account_id));
        people.setAvatar(url);
        peopleService.updateSysPeople(people);
        //服务器应答
        result.put("api","takephoto");
        result.put("interval","10000");
        String noncestr= UUID.randomUUID().toString();
        result.put("noncestr",noncestr);
        Long time=new Date().getTime()/1000;
        result.put("time",time);
        String sign= EncodeByMD5(time+noncestr+"FFFFFFFFFFFF");
        result.put("sign",sign);
        result.put("result_code","0");
        result.put("result_msg","OK");


        return result;
    }


    @RequestMapping(value = "getparameters",method = RequestMethod.POST)
    @ApiOperation("设备主动请求获取参数接口")
    public JSONObject getparameters(@RequestBody JSONObject json){
        JSONObject api=new JSONObject();
        Gson gson = new Gson();
        String deviceNo=json.get("dev_id")+"";
        /*SysEquipment equipment= equipmentService.selectEquipmentBySequence(deviceNo);
        //查看设备消费方式
        //如果有记录时则要处理记录后再应答，保存后的id回传给设备，方便设备对记录作标志 cardpwd FFFFFFFFFFFF
        CardEntity  card=new CardEntity();
        card.setApi("parameters");
        Long time=new Date().getTime()/1000;
        card.setTime(time);
        String noncestr= UUID.randomUUID().toString();
        card.setNoncestr(noncestr);
        String sign= EncodeByMD5(time+noncestr+"FFFFFFFFFFFF");
        card.setSign(sign);
        card.setTransaction_id(json.get("transaction_id")+"");
        //设备参数
        JSONArray devSet=new JSONArray();
        JSONObject devSet1=new JSONObject();
        devSet1.put("key","admin_pwd");
        devSet1.put("value",equipment.getPassword());
        devSet1.put("param_id","000000");
        JSONObject devSet2=new JSONObject();
        devSet2.put("key","consume_type");
        devSet2.put("value",equipment.getConsumeType());//消费方式
        devSet2.put("param_id","000000");
        devSet.add(devSet1);
        devSet.add(devSet2);
        card.setDev_set(devSet);
        //支付宝参数
        //微信参数
        //时间段
        String cards=gson.toJson(card);
        api=JSONObject.parseObject(cards);*/
        return api;
    }

    @RequestMapping(value = "parameters",method = RequestMethod.POST)
    @ApiOperation("设备上传参数结果接口")
    public JSONObject parameters(@RequestBody JSONObject json){
        JSONObject api=new JSONObject();
        Gson gson = new Gson();
        String deviceNo=json.get("dev_id")+"";
        SysEquipment equipment= equipmentService.selectEquipmentBySequence(deviceNo);
        equipment.setConsumeFlag("1");
        equipmentService.updateSysEquipment(equipment);





        return api;
    }




    /**
     * 对字符串进行32位MD5加密
     * @param str
     * @return
     */
    public static String EncodeByMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes("UTF-8"));
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            String md5=new BigInteger(1, md.digest()).toString(16);
            //BigInteger会把0省略掉，需补全至32位
            return fillMD5(md5);
        } catch (Exception e) {
            throw new RuntimeException("MD5加密错误:"+e.getMessage(),e);
        }
    }

    private static String fillMD5(String md5) {
        //如果不够32位则回调自身补零，最后返回32位长度的签名
        return md5.length() == 32 ? md5 : fillMD5("0" + md5);
    }





}
