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.InAndOutRecordReq.PurchaseEqsReq;
import com.junmp.jyzb.api.bean.query.OrderMainReq;
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.cache.MsgRedisCache;
import com.junmp.jyzb.cache.OutInRecordRedisCache;
import com.junmp.jyzb.entity.Inventory;
import com.junmp.jyzb.entity.Policeman;
import com.junmp.jyzb.entity.PubOrg;
import com.junmp.jyzb.service.InventoryService;
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.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 com.junmp.v2.message.api.bean.req.MessageReq;
import com.junmp.v2.message.api.bean.req.MessageSendReq;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
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.*;
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 MsgRedisCache redisCache;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RabbitAdmin rabbitAdmin;
    @Resource
    private InventoryService inventoryService;

    @Resource
    private OutInRecordRedisCache outInRecordRedisCache;

    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 = "更新消息#logType30")
    @ApiOperation("更新消息")
    public ApiRes<Boolean> updateMessage(@RequestBody MessageReq req){
        return ApiRes.success(publicService.updateMessage(req));
    }


    @PostMapping("/aaa")
    public ApiRes<List<Object>> aaa(@RequestBody OrderMainReq req){

        List<Object> dataByTimestampRange = outInRecordRedisCache.getDataByTimestampRange(req.getId());

        return ApiRes.success(dataByTimestampRange);
    }

    @PostMapping("/bbb")
    public ApiRes<Boolean> bbb(@RequestBody PurchaseEqsReq eqsReq){
        List<Inventory> collect1=new ArrayList<>();
        Inventory inventory = new Inventory();
        inventory.setEpc(eqsReq.getEpc());
        inventory.setTypeId(eqsReq.getTypeId());
        inventory.setSizeId(eqsReq.getSizeId());
        inventory.setMaintenancePeriod(eqsReq.getMaintenancePeriod());
        inventory.setWarrantyPeriod(eqsReq.getWarrantyPeriod());
        inventory.setProperty(eqsReq.getProperty());
        inventory.setLocationId(eqsReq.getLocationId());
        inventory.setSupplierId(eqsReq.getSupplierId());
        inventory.setPrice(eqsReq.getPrice());
//                    BeanPlusUtil.copyProperties(eqsReq, inventory);
        inventory.setId(UUID.randomUUID().toString());
        inventory.setCreateTime(DateTimeUtil.getCurrentDateTime());
        inventory.setState("normal");
        inventory.setBussinessState("normal");
        inventory.setLocationState("in");
        inventory.setLocationType(0);
//        inventory.setOrgId(order.getOrgId());
        collect1.add(inventory);
        inventoryService.saveBatch(collect1);
        return ApiRes.success(true);
    }



}
