package com.junmp.jyzb.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.AES;
import com.junmp.jyzb.api.bean.dto.UploadPolicePhotoDto;
import com.junmp.jyzb.api.bean.query.DbAccessReq;
import com.junmp.jyzb.api.bean.req.UploadPolicePhotoReq;
import com.junmp.jyzb.api.bean.vo.AuthAccessVo;
import com.junmp.jyzb.cache.MsgRedisCache;
import com.junmp.jyzb.cache.OutInRecordRedisCache;
import com.junmp.jyzb.entity.PubOrg;
import com.junmp.jyzb.mapper.PolicemanMapper;
import com.junmp.jyzb.service.PolicemanService;
import com.junmp.jyzb.service.PubOrgService;
import com.junmp.jyzb.service.PublicService;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.jyzb.utils.RabbitMQSendMsg;
import com.junmp.v2.common.bean.request.ValidationApi;
import com.junmp.v2.common.bean.response.ApiRes;
import com.junmp.v2.common.exception.enums.DefaultBizExceptionEnum;
import com.junmp.v2.dict.api.bean.req.SysDictItemReq;
import com.junmp.v2.dict.api.bean.vo.SimpleDictVo;
import com.junmp.v2.message.api.bean.req.MessageReq;
import com.junmp.v2.sys.api.bean.user.req.SysUserReq;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * <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 MsgRedisCache redisCache;

    @Resource
    private PubOrgService pubOrgService;

    @Resource
    private OutInRecordRedisCache outInRecordRedisCache;
    
    @Resource
    private PolicemanMapper policemanMapper;

    @Autowired
    private RabbitMQSendMsg MQ;

    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() {
        return ApiRes.success(publicService.getAllDictItem());

    }

    @PostMapping(path = "/updateMessage",name = "更新消息#logType=30")
    @ApiOperation("更新消息")
    public ApiRes<Boolean> updateMessage(@RequestBody MessageReq req){
        return ApiRes.success(publicService.updateMessage(req));
//        return ApiRes.success(true);
    }




    @PostMapping(path = "/findCodeToOrgId",name = "通过区域短码获取组织机构id#logType=30")
    @ApiOperation("通过区域短码获取组织机构id")
    public ApiRes<Long> findCodeToOrgId(@RequestBody PubOrg pubOrg){
        return ApiRes.success(pubOrgService.findCodeToOrgId(pubOrg));
    }

    @PostMapping(path = "/isRedirect",name = "是否需要重定向#logType=30")
    @ApiOperation("是否需要重定向")
    public ApiRes<Boolean> isRedirect(@RequestBody SysUserReq user){
        return ApiRes.success(publicService.isRedirect(user));
    }

//
    @PostMapping("/shutdown")
    public ApiRes<Boolean> shutdown(){
        outInRecordRedisCache.addProcessDefinitionId("1","3", DateTimeUtil.TimeDateToLong(DateTimeUtil.getCurrentDateTime()));
        return ApiRes.success(true);
    }
    @PostMapping("/apiRes")
    public ApiRes<String> apiRes(){
        String processDefinitionIds = outInRecordRedisCache.getProcessDefinitionIds("1");
        return ApiRes.success(processDefinitionIds);
    }

}
