package com.huimv.video.dhicc.controller.ClientController;


import com.alibaba.fastjson.JSON;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.http.IClient;
import com.dahuatech.icc.oauth.model.v202010.GeneralRequest;
import com.dahuatech.icc.oauth.model.v202010.GeneralResponse;
import com.huimv.common.utils.StringUtilsWork;
import com.huimv.video.dhicc.result.R;
import com.huimv.video.dhicc.util.GetResponse;
import com.huimv.video.dhicc.util.HttpClient;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


//门禁是不一样的
@RestController
@RequestMapping("person")
public class ClientPersonManageController {

    //添加图片
    @RequestMapping("/addPersonPicture")
    public R addPersonPicture(@RequestParam(name = "file") MultipartFile multipartFile) throws ClientException, IOException {

        //文件上传前的名称
        long s = System.currentTimeMillis();
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(fileName);
        OutputStream out = null;
        try {
            //获取文件流，以文件流的方式输出到新文件
            out = new FileOutputStream(file);
            byte[] ss = multipartFile.getBytes();
            for (int i = 0; i < ss.length; i++) {
                out.write(ss[i]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        long e = System.currentTimeMillis();
        System.out.println(e - s);
        String URL = "/evo-apigw/evo-brm/1.0.0/person/upload/img";
        IClient iClient = new DefaultClient();
        GeneralRequest generalRequest = new GeneralRequest(URL, Method.POST);
        //generalRequest.header("Content-Type", "multipart/form-data");
        HashMap<String, Object> formMap = new HashMap<>();
        // formMap.put("enctype","multipart/form-data");
        formMap.put("file", file);
        generalRequest.form(formMap);
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());

        // 操作完上的文件 需要删除在根目录下生成的文件
        File f = new File(file.toURI());
        if (f.delete()) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
        Object data = jsonObject.get("data");
        JSONObject jsonObject1 = JSONObject.fromObject(data);
        Object fileUrl = jsonObject1.get("fileUrl");
        return R.ok("请求成功").put("data", fileUrl.toString());






/*

        Map map  = new HashMap();
        HttpClient httpClient = new HttpClient(URL);
        httpClient.setHttps(true);
        Map<String ,String> header = new HashMap();
        //header.put("Authorization","bearer 1:7bdc436b-e68c-4d78-aae0-fcf0bdf92f1e");
        String content = httpClient.httpClientUploadFilePost(URL, file, header,map);
*/


    }


    //删除人员
    @RequestMapping("/deletePercon")
    public R deletePercon(@RequestBody Map<String, Object> params1) throws ClientException {
        List<Integer> ids = (List<Integer>) params1.get("ids");
        String URL = "/evo-apigw/evo-brm/1.2.0/person/delete";
        Map map = new HashMap();
        map.put("departmentId", 1);
        map.put("ids", ids);
        IClient iClient = new DefaultClient();
        GeneralRequest generalRequest = new GeneralRequest(URL, Method.POST);
        generalRequest.header("Content-Type", "application/json");
        generalRequest.body(JSON.toJSONString(map));
        System.out.println(JSON.toJSONString(map));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());
        return R.ok("请求成功").put("data", jsonObject);
    }


    //人员管理--添加用户
    @RequestMapping("/addPerson")
    public R addPerson(@RequestBody Map<String, Object> params1) throws ClientException {
        params1.put("paperType", 111);
        params1.put("code", (int) ((Math.random() * 9 + 1) * 10000));
        params1.put("departmentId", (int) params1.get("departmentId"));
        params1.put("name", (String) params1.get("name"));
        params1.put("paperNumber", "1101011990d3d" + (int) ((Math.random() * 9 + 1) * 10000));
        params1.put("phone", 15171709858L + (int) ((Math.random() * 9 + 1) * 10000));
        params1.put("id", (int) ((Math.random() * 9 + 1) * 10000));

        String URL = "/evo-apigw/evo-brm/1.0.0/person/subsystem/add";
        IClient iClient = new DefaultClient();
        GeneralRequest generalRequest = new GeneralRequest(URL, Method.POST);
        generalRequest.header("Content-Type", "application/json");
        generalRequest.body(JSON.toJSONString(params1));
        System.out.println(JSON.toJSONString(params1));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());
        return R.ok("请求成功").put("data", jsonObject);
    }


    //人员管理--添加绑定用户的图片
    @RequestMapping("/addPictureToPerson")
    public GeneralResponse addPicture(@RequestBody Map<String, Object> params1) throws ClientException {

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

        Map<String, Object> value1 = new HashMap<>();
        value1.put("personId", (int) params1.get("personId"));
        value1.put("type", 3);
        value1.put("index", 1);
        value1.put("path", (String) params1.get("path"));

        List mapList = new ArrayList();
        System.out.println(mapList);
        mapList.add(value1);
        params.put("personBiosignatures", mapList);
        String URL = "/evo-apigw/evo-brm/1.0.0/person/subsystem/update-biosignature-face";
        IClient iClient = new DefaultClient();
        GeneralRequest generalRequest = new GeneralRequest(URL, Method.PUT);
        generalRequest.header("Content-Type", " application/json");
        generalRequest.body(JSON.toJSONString(params));
        System.out.println(JSON.toJSONString(params));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());
        return generalResponse;
    }


    //刷脸失败记录
    @RequestMapping("/getPersonOpenDoorFail")
    public R getAccidentRecord(@RequestBody Map<String, Object> params1) throws ClientException {
        Integer farmId = (int) params1.get("farmId");
        if (farmId != 1) {
            //返回为空数据
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date A = c.getTime();
        String formatA = format.format(A);
        c.set(Calendar.HOUR, +24);
        Date d = c.getTime();
        String formatD = format.format(d);
        if (!StringUtilsWork.isNotEmpty((String) params1.get("startSwingTime"))) {
            params1.put("startSwingTime", formatA);
            params1.put("endSwingTime", formatD);
        }
        params1.put("containDomain", "1");
        params1.put("openResult", 0); //刷脸失败
        String URL = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combined?systime=";
        IClient iClient = new DefaultClient();
        GeneralRequest generalRequest = new GeneralRequest(URL + Long.valueOf(String.valueOf((new Date()).getTime())), Method.POST);
        generalRequest.header("Content-Type", " application/json");
        generalRequest.body(JSON.toJSONString(params1));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject jsonObject = JSONObject.fromObject(generalResponse.getResult());
        GetResponse getResponse = new GetResponse();
        return R.ok("请求成功").put("data", jsonObject).put("total", getResponse.SendMassageGetPagePersonAlarm((String) params1.get("startSwingTime"), (String) params1.get("endSwingTime")));
    }


    /*
         * @param params
         *   下面是前端提交的参数 直接让她写死了   这个是查不同部门的人的接口
         *{searchKey: "", pageNum: 1, pageSize: 10, departmentId: 4, isContain: true, statusList: [1, 2]}      维修部门
          {searchKey: "", pageNum: 1, pageSize: 10, departmentId: 2, isContain: true, statusList: [1, 2]}      技术部门
          {searchKey: "", pageNum: 1, pageSize: 10, departmentId: 5, isContain: true, statusList: [1, 2]}      基层部门
         * @return
         * @throws ClientException
         */
    @RequestMapping("/ge_person_list")
    public GeneralResponse ge_person_list(@RequestBody Map<String, Object> params) throws ClientException {
        Integer farmId = (int) params.get("farmId");
        if (farmId != 1) {
            //返回为空数据
            return null;
        }

        IClient iClient = new DefaultClient();
        GeneralRequest generalRequest = new GeneralRequest("/evo-apigw/evo-brm/1.2.0/person/page", Method.POST);
        generalRequest.header("Content-Type", " application/json");
        generalRequest.body(JSON.toJSONString(params));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        System.out.println("执行结束");
        return generalResponse;
    }


    @RequestMapping("/get_person_record")
    public GeneralResponse getAccidentRecord1(@RequestBody Map<String, Object> params) throws ClientException {
        Integer farmId = (int) params.get("farmId");
        if (farmId != 1) {
            //返回为空数据
            return new GeneralResponse();
        }
        String URL = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combined";  //获取事件URL    post请求
        IClient iClient = new DefaultClient();
        System.out.println("开始执行");
        //这种已经在配置文件里面安排了账号ip以及密码
        GeneralRequest generalRequest = new GeneralRequest(URL, Method.POST);
        generalRequest.header("Content-Type", " application/json");
        System.out.println(JSON.toJSONString(params));
        generalRequest.body(JSON.toJSONString(params));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        System.out.println("执行结束");
        return generalResponse;
    }


    //总页数
    @RequestMapping("/get_person_record_totalpage")
    public GeneralResponse get_person_record_totalpage(@RequestBody Map<String, Object> params) throws ClientException {
        Integer farmId = (int) params.get("farmId");
        if (farmId != 1) {
            //返回为空数据
            return new GeneralResponse();
        }
        String URL = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combinedCount?systime=";
        IClient iClient = new DefaultClient();
        String timestamp = String.valueOf((new Date()).getTime());
        Long aLong = Long.valueOf(timestamp);
        GeneralRequest generalRequest = new GeneralRequest(URL + aLong, Method.POST);
        generalRequest.header("Content-Type", " application/json");
        generalRequest.body(JSON.toJSONString(params));
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        return generalResponse;
    }


    @RequestMapping("/get_person_detail")
    public GeneralResponse getPersonDetail(@RequestBody Map<String, Object> params) throws ClientException {

        Integer farmId = (int) params.get("farmId");
        if (farmId != 1) {
            //返回为空数据
            return new GeneralResponse();
        }
        String URL = "/evo-apigw/evo-accesscontrol/${version}/card/accessControl/swingCardRecord/19241";  //获取事件URL    post请求
        IClient iClient = new DefaultClient();
        String URL_id = URL + params.get("id");
        GeneralRequest generalRequest = new GeneralRequest(URL_id, Method.POST);
        generalRequest.header("Content-Type", " application/json");
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        return generalResponse;
    }

}
