package com.fs.app.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fs.app.annotation.Login;
import com.fs.app.param.SignParam;
import com.fs.app.utils.CityTreeUtil;
import com.fs.app.utils.JwtUtils;
import com.fs.app.vo.CityVO;
import com.fs.app.vo.ImMsgVO;
import com.fs.common.constant.Constants;
import com.fs.common.core.domain.AjaxResult;

import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.file.OssException;
import com.fs.common.utils.sign.Base64;
import com.fs.common.utils.uuid.IdUtils;
import com.fs.his.config.FsSysConfig;
import com.fs.his.domain.FsAppVersion;
import com.fs.his.domain.FsCity;
import com.fs.his.domain.FsFollow;
import com.fs.his.param.ImMsgParam;
import com.fs.his.service.*;

import com.fs.his.utils.ConfigUtil;
import com.fs.im.dto.*;
import com.fs.im.service.IImService;
import com.fs.im.service.OpenIMService;
import com.fs.im.vo.OpenImMsgCallBackVO;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.system.service.ISysConfigService;
import com.fs.system.service.ISysDictDataService;
import com.fs.system.vo.DictVO;
import com.google.code.kaptcha.Producer;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.tencentyun.TLSSigAPIv2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.FastByteArrayOutputStream;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

@Api("公共接口")
@RestController
@RequestMapping(value="/app/common")
public class CommonController {

	private static Logger logger = Logger.getLogger("com.fs.app.controller.CommonController");
	@Autowired
    JwtUtils jwtUtils;
	@Autowired
	private ISysDictDataService dictDataService;
	@Autowired
	ConfigUtil configUtil;
	@Autowired
	private IFsCityService cityService;

	@Autowired
	private IFsAppVersionService appVersionService;

	@Autowired
	private IFsInquiryOrderMsgService inquiryOrderMsgService;

	@Resource(name = "captchaProducer")
	private Producer captchaProducer;

	@Resource(name = "captchaProducerMath")
	private Producer captchaProducerMath;

	@Autowired
	private RedisCache redisCache;

	// 验证码类型
	@Value("${fs.captchaType}")
	private String captchaType;

	@Autowired
	private ISysConfigService configService;

	@Autowired
	private IFsFollowService followService;
	@Autowired
	private IImService imService;
	@Autowired
	private OpenIMService openIMService;
	@ApiOperation("测试")
	@GetMapping(value = "/getTest")
	public AjaxResult getTest()
	{

		FsFollow follow=followService.selectFsFollowByFollowId(2l);
		//发送给用户
		MsgDTO msgDTO=new MsgDTO();
		MsgCustomDTO customDTO=new MsgCustomDTO();
		customDTO.setType("startDrugReport");
		customDTO.setImType(2);
		customDTO.setOrderId(follow.getStoreOrderId().toString());
		customDTO.setFollowId(follow.getFollowId().toString());
		msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
		msgDTO.setFrom_Account("U-"+follow.getUserId());
		msgDTO.setTo_Account("D-76");
		List<MsgDataDTO> msgs=new ArrayList<>();
		MsgDataDTO msg=new MsgDataDTO();
		msg.setMsgType("TIMTextElem");
		msg.setMsgContent(new MsgDataFormatDTO("您好,请问有什么可以帮您吗?"));
		msgs.add(msg);
		msgDTO.setMsgBody(msgs);
		imService.sendMsg(msgDTO);


		return AjaxResult.success("");
	}


	@ApiOperation("获取最新版本")
	@GetMapping("/getNewAppVersion")
	public R getNewAppVersion(@RequestParam("appType")Integer appType)
	{
		FsAppVersion version=appVersionService.getNewAppVersion(appType);
		return R.ok().put("data",version);
	}

	@ApiOperation("获取最新版本")
	@GetMapping("/testGit")
	public R testGit(@RequestParam("appType")Integer appType)
	{
		FsAppVersion version=appVersionService.getNewAppVersion(appType);
		return R.ok().put("data",version);
	}

	@ApiOperation("获取数据字典")
	@GetMapping("/getDictByKey")

	public R getDictByKey(@RequestParam(value = "key", required = false) String key){
		List<DictVO> dicts=dictDataService.selectDictDataListByType(key);
		return R.ok().put("data",dicts);
	}




	@PostMapping("uploadOSS")
	public R uploadOSS(@RequestParam("file") MultipartFile file) throws Exception
	{

		if (file.isEmpty())
		{
			throw new OssException("上传文件不能为空");
		}
		// 上传文件
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		CloudStorageService storage = OSSFactory.build();
		String url = storage.uploadSuffix(file.getBytes(), suffix);
		return R.ok().put("url",url);
	}


//	@Login
//	@GetMapping(value = "/getTlsSig")
//	@ApiOperation("获取腾讯云签名")
//	public R getTlsSig(@Validated SignParam signParam)
//	{
//		TLSSigAPIv2 api = new TLSSigAPIv2(fsConfig.getSdkAppId(), fsConfig.getSdkAppKey());
//		String sign=api.genUserSig(signParam.getUserId(),180*86400);
//		return R.ok().put("data",sign);
//	}


	@Login
	@ApiOperation("获取城市数据")
	@GetMapping("/getCitys")
	@Cacheable("cityData")
	public R getCitys(HttpServletRequest request){
		List<FsCity> list=cityService.selectFsCityList(new FsCity());
		List<CityVO> cityVOS = Lists.newArrayList();
		for (FsCity city : list){
			CityVO cityVO = new CityVO();
			cityVO.setV(city.getCityId());
			cityVO.setN(city.getCityName());
			cityVO.setPid(city.getParentId());
			cityVOS.add(cityVO);
		}
		return R.ok().put("data", CityTreeUtil.list2TreeConverter(cityVOS, "0"));

	}

	@Login
	@GetMapping(value = "/getTlsSig")
	@ApiOperation("获取腾讯云签名")
	public R getTlsSig(@Validated SignParam signParam)
	{
		FsSysConfig fsConfig = configUtil.getSysConfig();
		TLSSigAPIv2 api = new TLSSigAPIv2(fsConfig.getSdkAppId(), fsConfig.getSdkAppKey());
		String sign=api.genUserSig(signParam.getUserId(),180*86400);
		return R.ok().put("data",sign);
	}



	@ApiOperation("聊天数据回调")
	@PostMapping(value = "/notifyImMsg")
	public ImMsgVO notifyImMsg(@RequestBody String body,HttpServletRequest request)
	{

		FsSysConfig fsConfig = configUtil.getSysConfig();
		Gson gson = new Gson();
		ImMsgParam messageInfo = gson.fromJson(body, ImMsgParam.class);
		ImMsgVO vo=new ImMsgVO();
		String sdkAppid = request.getParameter("SdkAppid");
		String sdk = fsConfig.getSdkAppId().toString();
		if (!sdk.equals(sdkAppid)){
			vo.setErrorCode(1);
			vo.setActionStatus("appKey错误");
			logger.info("appKey错误");
			return vo;
		}
		inquiryOrderMsgService.saveMsg(messageInfo);
		vo.setErrorCode(0);
		vo.setActionStatus("OK");
		return vo;
	}
	@ApiOperation("openIm聊天数据回调")
	@PostMapping(value = "/callbackAfterSendSingleMsgCommand")
	public OpenImMsgCallBackResponse openImMsgCallBack(@RequestBody String body, HttpServletRequest request) throws JsonProcessingException {

		Gson gson = new Gson();
		OpenImMsgCallBackVO messageInfo = gson.fromJson(body, OpenImMsgCallBackVO.class);

		//openIMService.AiAutoReply(messageInfo);

		//log.info("收到的参数{}", JSON.toJSONString(messageInfo));
		return inquiryOrderMsgService.openImSaveMsg(messageInfo);
	}
	/**
	 * 生成验证码
	 */
	@GetMapping("/captchaImage")
	public AjaxResult getCode(HttpServletResponse response) throws IOException
	{
		AjaxResult ajax = AjaxResult.success();
		boolean captchaOnOff = configService.selectCaptchaOnOff();
		ajax.put("captchaOnOff", captchaOnOff);
		if (!captchaOnOff)
		{
			return ajax;
		}

		// 保存验证码信息
		String uuid = IdUtils.simpleUUID();
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

		String capStr = null, code = null;
		BufferedImage image = null;

		// 生成验证码
		if ("math".equals(captchaType))
		{
			String capText = captchaProducerMath.createText();
			capStr = capText.substring(0, capText.lastIndexOf("@"));
			code = capText.substring(capText.lastIndexOf("@") + 1);
			image = captchaProducerMath.createImage(capStr);
		}
		else if ("char".equals(captchaType))
		{
			capStr = code = captchaProducer.createText();
			image = captchaProducer.createImage(capStr);
		}

		redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
		// 转换流信息写出
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		try
		{
			ImageIO.write(image, "jpg", os);
		}
		catch (IOException e)
		{
			return AjaxResult.error(e.getMessage());
		}

		ajax.put("uuid", uuid);
		ajax.put("img", Base64.encode(os.toByteArray()));
		return ajax;
	}


}
