package io.renren.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import io.renren.entity.SelfServerEntity;
import io.renren.entity.SysPeople;
import io.renren.service.ISysPeopleService;
import io.renren.util.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

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


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

    @RequestMapping(value = "capture",method = RequestMethod.POST)
    @ApiOperation("设备上传识别拍照的相片")
    @ResponseBody
    public JSONObject capture(@RequestParam("json") String jsons,@RequestParam("picture") MultipartFile picture){
        JSONObject result=new JSONObject();
        System.out.println("设备上传识别拍照的相片========="+jsons);
        JSONObject json= JSONObject.parseObject(jsons);
        //如果有记录时则要处理记录后再应答，保存后的id回传给设备，方便设备对记录作标志 cardpwd FFFFFFFFFFFF



        result.put("devid",json.get("devid"));
        result.put("emp_id",json.get("emp_id"));
        result.put("id",json.get("id"));

        return result;
    }

    @RequestMapping(value = "API/selfserver",method = RequestMethod.POST)
    @ApiOperation("自助机接口")
    public JSONObject selfserver(@RequestBody JSONObject json){
        Gson gson = new Gson();
        JSONObject result=new JSONObject();
        //服务器应答心跳
        SelfServerEntity card=new SelfServerEntity();
        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":"833c9f7187c752da42f1ed3405564692","login_pwd":"1234","version":"V1.0.3","mac":"E8519E98F18D","noncestr":"95c46a914cee4cafbc99c63f680b2dbd","dev_id":"1","serialno":"99032CFCBDFFEF1A","total_amount":0,"refund_amount":0,"return_money":0,"model":"17","pay_type":0,"api":"lostcard","time":"1727166931595","customer":"385946","emp_id":"1001"}
        String api=json.get("api")+"";
        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.setBuild_time(json.get("build_time")+"");
        if ("login".equals(api)){//自助机手工登录
            card.setApi("login");
            SysPeople people=new SysPeople();
            people.setGh(json.get("emp_id")+"");
            people.setLoginPwd(json.get("login_pwd")+"");
            SysPeople peoples= peopleService.selectSysPeopleByIdPwd(people);
            if(peoples!=null){
                JSONArray result1=new JSONArray(); //说明只有登录成功时才返回以下值，其它为空
                JSONObject ob=new JSONObject();
                ob.put("account_id",peoples.getId());
                ob.put("emp_id",peoples.getGh());
                ob.put("emp_fname",peoples.getName());
                result1.add(ob);
                card.setResult(result1);
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","登录成功");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("0");//0成功  非0失败
                card.setResult_msg("登录成功");
            }else{
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","登录失败");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("1");//0成功  非0失败
                card.setResult_msg("登录失败");
            }
        }
        if ("lostcard".equals(api)){//挂失卡
            card.setApi("lostcard");
            SysPeople people=new SysPeople();
            people.setGh(json.get("emp_id")+"");
            people.setLoginPwd(json.get("login_pwd")+"");
            SysPeople peoples= peopleService.selectSysPeopleByIdPwd(people);
            if(peoples!=null){
                peoples.setIsLock("1");
                peopleService.updateSysPeople(peoples);
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","挂失成功");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("0");//0成功  非0失败
                card.setResult_msg("成功");
                card.setTts("挂失成功");
            }else{
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","挂失失败");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("1");//0成功  非0失败
                card.setResult_msg("失败");
                card.setTts("挂失失败");
            }
        }
        if ("unlostcard".equals(api)){//解挂
            card.setApi("unlostcard");
            SysPeople people=new SysPeople();
            people.setGh(json.get("emp_id")+"");
            people.setLoginPwd(json.get("login_pwd")+"");
            SysPeople peoples= peopleService.selectSysPeopleByIdPwd(people);
            if(peoples!=null){
                peoples.setIsLock("0");
                peopleService.updateSysPeople(peoples);
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","解挂成功");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("0");//0成功  非0失败
                card.setResult_msg("解挂成功");
                card.setTts("解挂成功");
            }else{
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","解挂失败");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("1");//0成功  非0失败
                card.setResult_msg("解挂失败");
                card.setTts("解挂失败");
            }
        }
        if ("password".equals(api)){//修改密码
            card.setApi("password");
            SysPeople people=new SysPeople();
            people.setGh(json.get("emp_id")+"");
            people.setLoginPwd(json.get("old_pwd")+"");
            SysPeople peoples= peopleService.selectSysPeopleByIdPwd(people);
            if(peoples!=null){
                peoples.setLoginPwd(json.get("new_pwd")+"");
                peopleService.updateSysPeople(peoples);
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","修改成功");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("0");//0成功  非0失败
                card.setResult_msg("修改成功");
                card.setTts("修改成功");
            }else{
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","修改失败");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("1");//0成功  非0失败
                card.setResult_msg("修改失败");
                card.setTts("修改失败");
            }
        }
        if ("regist".equals(api)){//注册
            card.setApi("regist");
            String login_pwd=json.get("login_pwd")+"";
            String name=json.get("name")+"";
            String phone=json.get("phone")+"";
            String idNumber=json.get("idNumber")+"";
            String photo=json.get("photo")+"";
            SysPeople people=new SysPeople();
            people.setGh(phone);
            people.setLoginPwd(login_pwd);
            people.setName(name);
            people.setPhone(phone);
            people.setIdcard(idNumber);
            SysPeople peoples= peopleService.selectSysPeopleByIdPwd(people);
            if(peoples!=null){
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","注册失败");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("1");//0成功  非0失败
                card.setResult_msg("注册失败");
                card.setTts("注册失败");
            }else{
                Map<String, Object> paramMap=new HashMap<>();
                paramMap.put("url",photo);
                String repose= HttpUtil.postData(port+"system/api/uploadMinioCar",paramMap);
                JSONObject obj1=JSONObject.parseObject(repose);
                JSONObject datas= (JSONObject) obj1.get("data");
                String url=datas.get("url")+"";
                people.setAvatar(url);
                people.setBranchId("10000");
                people.setIsConsume("1");
                peopleService.insertSysPeople(people);
                JSONArray msg=new JSONArray();
                JSONObject obj=new JSONObject();
                obj.put("line","注册成功");
                msg.add(obj);
                card.setMsg(msg);
                card.setResult_code("0");//0成功  非0失败
                JSONArray result1=new JSONArray(); //说明只有登录成功时才返回以下值，其它为空
                JSONObject ob=new JSONObject();
                ob.put("account_id",people.getId());
                ob.put("emp_id",people.getGh());
                ob.put("emp_fname",people.getName());
                result1.add(ob);
                card.setResult(result1);
                card.setResult_msg("注册成功");
                card.setTts("注册成功");
            }
        }
        String cards=gson.toJson(card);
        result=JSONObject.parseObject(cards);
        System.out.println("自助机实现登录，挂失，解挂，修改密码推送结果========="+result);
        return result;
    }


    /**
     * 对字符串进行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);
    }

}
