package com.junmp.jyzb.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.AES;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.junmp.jyzb.api.bean.dto.UploadPolicePhotoDto;
import com.junmp.jyzb.api.bean.query.DbAccessReq;
import com.junmp.jyzb.api.bean.query.PolicemanReq;
import com.junmp.jyzb.api.bean.req.UploadPolicePhotoReq;
import com.junmp.jyzb.api.bean.vo.AuthAccessVo;
import com.junmp.jyzb.api.exception.enums.PublicExceptionEnum;
import com.junmp.jyzb.entity.Policeman;
import com.junmp.jyzb.entity.PubOrg;
import com.junmp.jyzb.service.PolicemanService;
import com.junmp.jyzb.service.PubOrgService;
import com.junmp.jyzb.service.PublicService;
import com.junmp.jyzb.utils.FileUtil;
import com.junmp.v2.common.bean.request.ValidationApi;
import com.junmp.v2.common.bean.response.ApiRes;
import com.junmp.v2.common.enums.StatusEnum;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.exception.enums.DefaultBizExceptionEnum;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.dict.api.bean.req.SysDictItemReq;
import com.junmp.v2.dict.api.bean.vo.SimpleDictItemVo;
import com.junmp.v2.dict.api.bean.vo.SimpleDictVo;
import com.junmp.v2.dict.api.exception.DictException;
import com.junmp.v2.dict.api.exception.DictExceptionEnum;
import com.junmp.v2.dict.entity.SysDict;
import com.junmp.v2.dict.entity.SysDictItem;
import com.junmp.v2.dict.service.SysDictItemService;
import com.junmp.v2.dict.service.SysDictService;
import com.junmp.v2.file.api.bean.req.SysFileInfoReq;
import com.junmp.v2.file.api.bean.res.SysFileInfoResp;
import com.junmp.v2.file.biz.entity.SysFileInfo;
import com.junmp.v2.file.biz.service.SysFileInfoService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * 描述：
 * 版本：1.0.0
 * 日期：2022/8/30 16:24
 * 作者：ningzp@junmp.com.cn
 * <br>修改记录
 * <br>修改日期        修改人          修改内容
 *
 * </pre>
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class PublicController {

    @Resource
    private PolicemanService policemanService;

    @Resource
    private PublicService publicService;

    @Resource
    private SysDictService sysDictService;


    private final static String DB_URL_TEMPLATE = "jdbc:mysql://{}:{}/{}?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT&nullCatalogMeansCurrent=true";

    @GetMapping(path = "/pub/authInfo", name = "生成数据库认证信息")
    public ApiRes<AuthAccessVo> genAccessInfo(DbAccessReq req) {
        if (null != req && StrUtil.isNotEmpty(req.getDbName())
                && StrUtil.isNotEmpty(req.getHost())
                && ObjectUtil.isNotNull(req.getPort())
                && StrUtil.isNotEmpty(req.getUsername())
                && StrUtil.isNotEmpty(req.getPassword())) {
            String rmdKey = AES.generateRandomKey();
            String dbUrl = StrUtil.format(DB_URL_TEMPLATE, req.getHost(), req.getPort(), req.getDbName());
            String enDbUrl = AES.encrypt(dbUrl, rmdKey);
            String enUserName = AES.encrypt(req.getUsername(), rmdKey);
            String enPassword = AES.encrypt(req.getPassword(), rmdKey);
            return ApiRes.success(new AuthAccessVo(rmdKey, enDbUrl, enUserName, enPassword));
        } else {
            return ApiRes.failure(DefaultBizExceptionEnum.VALID_PARAMS_ERROR);
        }

    }


    //上传人脸照片
    @PostMapping(path="/uploadPolicePhoto",name="上传人脸照片#logType=30")
    public ApiRes<UploadPolicePhotoDto> uploadPolicePhoto(@RequestPart("picture") MultipartFile picture, UploadPolicePhotoReq req) {

        return ApiRes.success(policemanService.uploadPolicePhoto(picture,req));
    }

    @PostMapping(
            name = "添加字典类型#logType=30",
            path = {"/sys/dictType"}
    )
    public ApiRes<Long> addDictType(@RequestBody @Validated({ValidationApi.add.class}) SysDictItemReq req) {

        return ApiRes.success(publicService.addDictType(req));
    }

    @GetMapping(
            name = "查询所有字典项#enable",
            path = {"/getAllDictItem"}
    )
    public ApiRes<List<SimpleDictVo>> getAllDictItem() {
        List<SysDict> list = sysDictService.list();
        if (CollectionUtil.isNotEmpty(list)) {
            List<SimpleDictVo> tempList = (List)list.stream().map((it) -> {
                SimpleDictVo dict = (SimpleDictVo)BeanPlusUtil.toBean(it, SimpleDictVo.class);
                List<SimpleDictItemVo> itemVoList = publicService.findListByDict(dict.getDictId());
                dict.setItemList(itemVoList);
                return dict;
            }).collect(Collectors.toList());
            return ApiRes.success(tempList);
        } else {
            return ApiRes.failure("暂无数据");
        }
    }


}
