package com.artfess.base.controller;

import java.util.Map;
import java.util.Optional;

import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.cache.CacheManager;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.constants.WebsocketConst;
import com.artfess.base.id.IdGenerator;
import com.artfess.base.model.CommonResult;
import com.artfess.base.util.AppUtil;
import com.artfess.base.util.JsonUtil;
import com.artfess.base.util.PinyinUtil;
import com.artfess.base.util.time.DateUtil;
import com.artfess.base.vo.DruidEncryptDTO;
import com.artfess.base.webSocket.PushService;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.dynamic.datasource.toolkit.CryptoUtils;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.annotation.Resource;

@RestController
@RequestMapping("/base/tools/v1/")
@Api(tags = "工具接口")
@ApiGroup(group = {ApiGroupConsts.GROUP_BPM, ApiGroupConsts.GROUP_FORM, ApiGroupConsts.GROUP_SYSTEM, ApiGroupConsts.GROUP_UC})
public class ToolsController {

    @Value("${spring.profiles.version:''}")
    String platformVersion;
    @Autowired
    private PushService pushService;

    @Resource
    IdGenerator idGenerator;

    @RequestMapping(value = "getPinyin", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取拼音", httpMethod = "GET", notes = "获取拼音")
    public CommonResult<String> getPinyin(
            @ApiParam(required = true, name = "chinese", value = "中文内容") @RequestParam String chinese,
            @ApiParam(name = "type", value = "类型是1 则为全拼，否则为首字母") @RequestParam Optional<Integer> type
    ) throws AuthenticationException {
        Integer ptype = type.orElse(1);
        String pinying = "";
        //如果是类型是1 则为全拼，否则为首字母
        if (ptype == 1) {
            pinying = PinyinUtil.getPinyin(chinese);
        } else {
            pinying = PinyinUtil.getPinYinHeadChar(chinese);
        }
        return new CommonResult<String>(true, "获取拼音成功！", pinying);
    }

    @RequestMapping(value = "getPlatformVersion", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取平台版本", httpMethod = "GET", notes = "获取平台版本")
    public CommonResult<String> getPlatformVersion() {
        return new CommonResult<String>(true, "", platformVersion);
    }

    @RequestMapping(value = "encryptDbPassword", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取数据库密码加密字符串", httpMethod = "POST", notes = "获取数据库密码加密信息")
    public CommonResult<DruidEncryptDTO> encryptDbPassword(@ApiParam(required = true, name = "password", value = "待加密密码") @RequestBody Map<String, String> map) throws Exception {
        String[] arr = CryptoUtils.genKeyPair(512);
        DruidEncryptDTO druidEncryptDTO = new DruidEncryptDTO();
        druidEncryptDTO.setPassword(CryptoUtils.encrypt(arr[0], map.get("password")));
        druidEncryptDTO.setPublicKey(arr[1]);
        return new CommonResult<DruidEncryptDTO>(true, "获取拼音成功！", druidEncryptDTO);
    }


    @RequestMapping(value = "clearCacheByKey", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据缓存key清除缓存", httpMethod = "GET", notes = "根据缓存key清除缓存")
    public CommonResult<String> clearCacheByKey(@ApiParam(required = true, name = "key", value = "缓存key") @RequestParam String key) throws AuthenticationException {
        CacheManager manager = AppUtil.getBean(CacheManager.class);
        manager.clearCascadeByKey(key);
        return new CommonResult<String>(true, "操作成功！");
    }

    @RequestMapping(value = "getCurrentDate", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取当前服务器的时间", httpMethod = "GET", notes = "获取当前服务器的时间")
    public CommonResult<String> getCurrentDate(@ApiParam(required = true, name = "valFormat", value = "日期格式") @RequestParam String valFormat) throws AuthenticationException {
        String date = DateUtil.getCurrentTime(valFormat);//取当前系统日期，并按指定格式或者是默认格式返回
        return new CommonResult<String>(true, "获取成功", date);
    }

    @PostMapping("/webSocket/sendAll")
    @ApiOperation("websocket群发消息")
    public CommonResult<String> sendAll(@RequestBody ObjectNode jsonObject) throws Exception {
        String message = jsonObject.get("message").asText();
        ObjectNode obj = JsonUtil.getMapper().createObjectNode();
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC);
        obj.put(WebsocketConst.MSG_ID, idGenerator.nextId());
        obj.put(WebsocketConst.MSG_TXT, message);
        pushService.pushMsgToAll(obj.toString());
        return new CommonResult<>("群发！");

    }

    @PostMapping("/webSocket/sendUser")
    @ApiOperation("websocket单发消息")
    public CommonResult<String> sendUser(@RequestBody ObjectNode jsonObject) throws Exception {
        String userId = JsonUtil.getString(jsonObject, "userId");
        String message = JsonUtil.getString(jsonObject, "message");
        ObjectNode obj = JsonUtil.getMapper().createObjectNode();
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
        obj.put(WebsocketConst.MSG_USER_ID, userId);
        obj.put(WebsocketConst.MSG_ID, idGenerator.nextId());
        obj.put(WebsocketConst.MSG_TXT, message);
        pushService.pushMsgToAccount(userId, obj.toString());
        return new CommonResult<>("单发！");

    }
}