package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.FileUtil;
import com.ruoyi.common.utils.GsonUtils;
import com.ruoyi.common.utils.HttpUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.QyCzrxx;
import com.ruoyi.system.domain.QyPerson;
import com.ruoyi.system.service.IAppSysService;
import com.ruoyi.system.service.IQyCzrxxService;
import com.ruoyi.system.service.IQyPersonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static com.ruoyi.common.utils.demo.getAuth;

/**
 * @Author: Abeiv
 * @Description:
 * @Date: 2019-12-9 9:57
 */
@Api("APP接口")
@Controller()
@RequestMapping("/api/system")
public class ApiController extends BaseController {

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IQyPersonService qyPersonService;
    @Autowired
    private IQyCzrxxService qyCzrxxService;

    public static  final String API_Key = "FT0WbhAaNw0dHSANKDAaFLDB";
    public static  final String Secret_Key = "OVC2rxIROkWcKmNpOAuOqzHLKfB4YjTr";



    @Autowired
    private IAppSysService appSysService;


    @ApiOperation("保存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bsid", value = "企业bsid", dataType = "string"),
            @ApiImplicitParam(name = "rencardno", value = "身份证", dataType = "string"),
            @ApiImplicitParam(name = "sfz1", value = "身份证正面", dataType = "string"),
            @ApiImplicitParam(name = "sfz2", value = "反面", dataType = "string"),
            @ApiImplicitParam(name = "video", value = "录像地址", dataType = "string"),
            @ApiImplicitParam(name = "paizhao", value = "拍照", dataType = "string"),
            @ApiImplicitParam(name = "renqianming", value = "签名", dataType = "string"),

    })
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult save( String bsid,String rencardno , String sfz1 , String sfz2, String video, String paizhao, String renqianming ) throws IOException {
        int result=0;
        //人员
        QyPerson qy=new QyPerson();
        qy.setBsid(bsid);
        qy.setRencardno(rencardno);
        qy.setRzqx("0");
        List<QyPerson> qyPersons= qyPersonService.selectQyPersonList(qy);
        for (QyPerson qyPerson :qyPersons){
            qyPerson.setCzrsfz(sfz1);
            qyPerson.setCzrsfz1(sfz2);
            qyPerson.setVideo(video);
            qyPerson.setPaiphoto(paizhao);
            qyPerson.setRenqianming("data:image/jpeg;base64,/"+renqianming);
            qyPerson.setAddtime(new Date());
            qyPerson.setRzqx("1");
            result+= qyPersonService.updateQyPerson(qyPerson);

        }
        //股东
        QyCzrxx qyCzrxx = new QyCzrxx();
        qyCzrxx.setBsid(bsid);
        qyCzrxx.setCzrcardno(rencardno);
        qyCzrxx.setRzQx("0");
        List<QyCzrxx> qyCzrxxs= qyCzrxxService.selectQyCzrxxList(qyCzrxx);

        for (QyCzrxx item :qyCzrxxs){
            item.setRzQx("1");
            item.setCzrsfz1(sfz1);
            item.setCzrsfz(sfz2);
            item.setVideo(video);
            item.setCzrpaizhao(paizhao);
            item.setCzfs("货币");
            item.setCzrqm("data:image/jpeg;base64,/"+renqianming);
            result += qyCzrxxService.updateQyCzrxx(item);
        }
        if (result >=1) {
            return AjaxResult.success("保存成功",result);
        }
        return AjaxResult.warn("保存失败,请重试");
    }


    @ApiOperation("登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardNo", value = "身份证账号", dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码身份证后六位", dataType = "String")})
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestParam("cardNo") String cardNo, @RequestParam("password") String password) {
        AjaxResult result = appSysService.login(cardNo, password);
        return result;
    }
    /**
     * 录像上传
     */
    @ApiOperation("录像上传")
    @PostMapping("/uploadvideo")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 人证对比
     */

    @ApiOperation("人证对比")
    @PostMapping("/verify")
    @ResponseBody
    public AjaxResult face(@RequestParam("renphoto") String renphoto,@RequestParam("paiphoto") String paiphoto){
//        String filePath = Global.getUploadPath();
//        String imgPath1 = filePath + "2.jpg";
//        String imgPath2 = filePath + "3.jpg";
        HashMap<String, String> map = new HashMap<>();
        String result1 = match(API_Key, Secret_Key, renphoto, paiphoto);
        System.out.println("对比结果为：" + result1);
        JSONObject jsonObject = JSONObject.parseObject(result1);
        String result = jsonObject.getString("result");
        if (result != null) {
            JSONObject jsonObject1 = JSONObject.parseObject(result);
            String score = jsonObject1.getString("score");
            if(Float.valueOf(score)>=60){
                return  AjaxResult.success("ok",jsonObject.getString("error_msg"));
            }
            System.err.println("score:=="+score);
        }else {
            return AjaxResult.warn("比对失败",jsonObject.getString("error_msg"));
        }
        return AjaxResult.error("链接超时");
    }

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String match(String API_Key, String Secret_Key, String imgPath1, String imgPath2) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
        try {
            // 【本地文件1地址】
//            byte[] bytes1 = FileUtil.readFileByBytes(imgPath1);
//            // 【本地文件2地址】
//            byte[] bytes2 = FileUtil.readFileByBytes(imgPath2);
//            String image1 = Base64Util.encode(bytes1);
//            String image2 = Base64Util.encode(bytes2);
//            System.err.println("img:=="+image1);
            List<Map<String, Object>> images = new ArrayList<>();

            Map<String, Object> map1 = new HashMap<>();
            map1.put("image", imgPath1);
            map1.put("image_type", "BASE64");
            map1.put("face_type", "LIVE");
            map1.put("quality_control", "LOW");
            map1.put("liveness_control", "NONE");

            Map<String, Object> map2 = new HashMap<>();
            map2.put("image", imgPath2);
            map2.put("image_type", "BASE64");
            map2.put("face_type", "LIVE");
            map2.put("quality_control", "LOW");
            map2.put("liveness_control", "NONE");

            images.add(map1);
            images.add(map2);

            String param = GsonUtils.toJson(images);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            // 【调用鉴权接口获取的token】
            String accessToken = getAuth();

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    public String face{
//        String filePath = "C:\\Users\\Administrator\\Downloads\\";
//        String ak = "PSce6S7M7WVRVyIux15iDToC";
//        String sk = "fvzwcYociG2GYnsZppKqEbSlUDQaQ9Sd";
//        String imgPath1 = filePath + "2.jpg";
//        String imgPath2 = filePath + "3.jpg";
//        String result1 = FaceMatch.match(ak, sk, imgPath1, imgPath2);
//        System.out.println("对比结果为：" + result1);
//        JSONObject jsonObject = JSONObject.parseObject(result1);
//        String result = jsonObject.getString("result");
//        if (result != null) {
//            JSONObject jsonObject1 = JSONObject.parseObject(result);
//            String score = jsonObject1.getString("score");
//            System.err.println("score:=="+score);
//            }
////        System.out.println("相似度："+score);
//        }

}
