package com.yx.face.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.yx.face.boot.component.security.Authority;
import com.yx.face.boot.core.BaseController;
import com.yx.face.boot.core.Constants;
import com.yx.face.boot.restful.RestDTO;
import com.yx.face.boot.restful.RestResponse;
import com.yx.face.boot.restful.RestResult;
import com.yx.face.boot.restful.ServiceException;
import com.yx.face.model.dto.FaceDeviceDTO;
import com.yx.face.model.excel.FaceLogVoExcel;
import com.yx.face.model.query.FaceServerLogQu;
import com.yx.face.model.query.QueryUser;
import com.yx.face.model.search.FaceDeviceSearch;
import com.yx.face.model.search.FaceServerLogSearch;
import com.yx.face.model.vo.*;
import com.yx.face.service.AdminService;
import com.yx.face.service.FaceService;
import com.yx.face.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @description: 地址编码表(AreaCode)表控制层 <br>
 * @author: PWB <br>
 * @since: 1.0 <br>
 * @date: 2021-06-04 14:25:45 <br>
 */

@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = "B 管理人脸下发相关API")
@RestController
@RequestMapping("admin/face")
public class AdminFaceController extends BaseController {
    private final FaceService faceService;
    private final AdminService adminService;
    private final UserInfoService userInfoService;
    @Value("${web.address}")
    private String address;

    @ApiOperation("获取设备列表")
    @PostMapping("doGetFaceDevices")
    public RestResult<PageInfo<FaceDeviceVO>> doGetFaceDevices(@RequestBody RestDTO<FaceDeviceSearch> dto) {
        return RestResponse.ok(faceService.getFaceDevices(dto));
    }

    @ApiOperation("获取设备列表 sn / name")
    @PostMapping("getFaceDeviceList")
    public RestResult<List<FaceDeviceVO>> getFaceDeviceList(@RequestBody JSONObject adminId) {
        return RestResponse.ok(faceService.getFaceDeviceList(adminId));
    }


    @ApiOperation("授权设备使用权限")
    @Authority({1, 2})
    @GetMapping("doAuthFaceDevice/{deviceId}")
    public RestResult<Boolean> doAuthFaceDevice(@PathVariable Integer deviceId) {
        return RestResponse.ok(faceService.authFaceDevice(deviceId));
    }

    @ApiOperation("停止设备使用权限")
    @Authority({1, 2})
    @GetMapping("doStopFaceDevice/{deviceId}")
    public RestResult<Boolean> doStopFaceDevice(@PathVariable Integer deviceId) {
        return RestResponse.ok(faceService.stopFaceDevice(deviceId));
    }


    @ApiOperation("编辑设备信息")
    @PostMapping("doEditFaceDevices")
    public RestResult<Boolean> doEditFaceDevices(@RequestBody FaceDeviceDTO dto) {
        if (dto.getAdminId() == null) {
            throw new ServiceException("请传入adminId");
        }

        if (dto.getDeviceId() == null) {
            if (!StringUtils.hasText(dto.getSn())) {
                throw new ServiceException("请填写设备编号");
            }
            if (dto.getEnable() == null) {
                throw new ServiceException("请设置使用状态");
            }
            if (dto.getEnable() < 0 || dto.getEnable() > 1) {
                throw new ServiceException("请设置使用状态不规范");
            }
            faceService.addFaceDevice(dto);
        } else {
            if (dto.getEnable() != null) {
                if (dto.getEnable() < 0 || dto.getEnable() > 1) {
                    dto.setEnable(null);
                }
            }
            if (!StringUtils.hasText(dto.getSn())) {
                dto.setSn(null);
            }
            faceService.modifyFaceDevice(dto);
        }
        return RestResponse.ok(true);
    }

    @ApiOperation("删除设备")
    @DeleteMapping("doDeleteDevice/{deviceId}")
    public RestResult<Boolean> doDeleteDevice(@PathVariable Integer deviceId) {
        return RestResponse.ok(faceService.deleteDevice(deviceId));
    }


    @ApiOperation("设备重启")
    @GetMapping("doReboot")
    public RestResult<Boolean> doReboot(String sn) {
        if (org.apache.commons.lang3.StringUtils.isBlank(sn)) {
            throw new ServiceException("设备编号为空");
        }
        return RestResponse.ok(faceService.doReboot(sn));
    }


    @ApiOperation("获取人脸下发列表")
    @PostMapping("doGetFacePass")
    public RestResult<PageInfo<FacePassVO>> doGetFacePass(@RequestBody RestDTO<QueryUser> dto) {
        reBuildQuery(dto);
        return RestResponse.ok(faceService.getFacePasses(dto));
    }


    @ApiOperation("获取人脸服务日志列表")
    @PostMapping("doGetFaceServerLog")
    public RestResult<PageInfo<FaceLogVO>> doGetFaceServerLog(@RequestBody RestDTO<FaceServerLogSearch> dto) {
        return RestResponse.ok(faceService.getFaceLogs(dto));
    }

    @ApiOperation("获取通行记录详情")
    @PostMapping("/getDetails")
    public RestResult<FaceLogVO> getDetails(@RequestBody FaceServerLogQu qu) {
        if (qu.getId() == null) {
            throw new ServiceException("缺少参数哦~");
        }
        return RestResponse.ok(faceService.getDetails(qu, getUserId()));
    }

    @ApiOperation("导出人脸日志Excel")
    @PostMapping("doGetFaceServerLogExcel")
    public RestResult<String> doGetFaceServerLogExcel(@RequestBody FaceServerLogSearch dto) {
        List<FaceLogVoExcel> faceLogsExcel = faceService.getFaceLogsExcel(dto);
        String uploadExcel = Constants.UPLOAD_EXCEL;
        String fileName = uploadExcel + "/进出记录-" + System.currentTimeMillis() + ".xlsx";


        // 这里 需要指定写用哪个class去写
        ExcelWriter excelWriter = null;
        try {
            Path directory = Paths.get(uploadExcel);
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }
            excelWriter = EasyExcel.write(fileName, FaceLogVoExcel.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("进出记录").build();
            excelWriter.write(faceLogsExcel, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
        String filePath = address.concat(fileName);
        return RestResponse.ok(filePath);
    }


    @ApiOperation("获取人员列表")
    @PostMapping("doGetUsers")
    public RestResult<PageInfo<UserInfoVO>> doGetUsers(@RequestBody RestDTO<QueryUser> dto) {
        reBuildQuery(dto);
        return RestResponse.ok(userInfoService.getUsers(dto));
    }


    private void reBuildQuery(@RequestBody RestDTO<QueryUser> dto) {
        AdminVO adminVO = adminService.getAuthInfo(getUserId());
        QueryUser queryUser = dto.getData();
        if (queryUser == null) {
            queryUser = new QueryUser();
        }
        if (adminVO.getType() == 2) {
            queryUser.setAdminId(adminVO.getAdminId());
        }
        dto.setData(queryUser);
    }

    @ApiOperation("设备logo下发")
    @GetMapping("issuedAll")
    public RestResult<Boolean> issuedAll(Integer type, Integer adminId, String sn)  {
        return RestResponse.ok(faceService.issuedAll(type, adminId, sn));
    }

    @ApiOperation("获取logo")
    @GetMapping("getLogo")
    public RestResult<String> getLogo() {
        return RestResponse.ok(faceService.getLogo(getUserId()));
    }
}

