/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.fwbbjq.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.fwbbjq.entity.Fwbbjq;
import org.springblade.modules.fwbbjq.service.IFwbbjqService;
import org.springblade.modules.fwbbjq.util.Base64Util;
import org.springblade.modules.fwbbjq.vo.FwbbjqVO;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 控制器
 *
 * @author BladeX
 * @since 2022-12-05
 */
@RestController
@AllArgsConstructor
@ApiSort(2)
@RequestMapping("fwbbjq")
@Api(value = "测试2", tags = "接口")
public class FwbbjqController extends BladeController {

	private final IFwbbjqService fwbbjqService;
	private final IDeptService deptService;

	/**
	 * 对象存储构建类
	 */
	private final OssBuilder ossBuilder;

	/**
	 * 详情
	 */
	@ApiLog("查看通知通告详情")
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入fwbbjq")
	public R<Fwbbjq> detail(Fwbbjq fwbbjq) {
		Fwbbjq detail = fwbbjqService.getOne(Condition.getQueryWrapper(fwbbjq));
		return R.data(detail);
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入fwbbjq")
	public R<IPage<Fwbbjq>> list(Fwbbjq fwbbjq, Query query) {
		QueryWrapper<Fwbbjq> qe = new QueryWrapper<>();
		Dept dept = deptService.getById(Long.parseLong(AuthUtil.getUser().getDeptId()));
		String[] split = dept.getAncestors().split(",");
		if (split.length == 3) {
			qe.eq("bmid", dept.getParentId()).or().eq("bmid", split[1]);
		}
		if (split.length == 2) {
			qe.eq("bmid", dept.getId()).or().eq("bmid", split[1]);
		}
		if (dept.getParentId() == 0) {
			qe.isNotNull("bmid");
		}
		IPage<Fwbbjq> pages = fwbbjqService.page(Condition.getPage(query), qe);
		return R.data(pages);
	}

	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入fwbbjq")
	public R<IPage<FwbbjqVO>> page(FwbbjqVO fwbbjq, Query query) {
		IPage<FwbbjqVO> pages = fwbbjqService.selectFwbbjqPage(Condition.getPage(query), fwbbjq);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入fwbbjq")
	public R save(@Valid @RequestBody Fwbbjq fwbbjq) {
		return R.status(fwbbjqService.save(fwbbjq));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入fwbbjq")
	public R update(@Valid @RequestBody Fwbbjq fwbbjq) {
		return R.status(fwbbjqService.updateById(fwbbjq));
	}

	/**
	 * 新增或修改
	 */
	@ApiLog("通知通告新增或修改")
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入fwbbjq")
	public R submit(@Valid @RequestBody Fwbbjq fwbbjq) {
//		Base64Util base64 = new Base64Util();
//
//		fwbbjq.setBmid(Long.parseLong(AuthUtil.getUser().getDeptId()));
//		//图片转base64
//		if (fwbbjq.getTznr().contains("img")) {
//			//替换内容的中照片url为base64
//			String tznr = getUrl(fwbbjq.getTznr());
//			//获取一张zp
//			String word = base64.getImgSrc(fwbbjq.getTznr()).get(0);
//			base64.imageUrlToBase64(word);
//			fwbbjq.setZp(base64.imageUrlToBase64(word));
//			fwbbjq.setTznr(tznr);
//		}
		String url = fwbbjq.getTznr();
		StringBuilder stringBuilder = new StringBuilder(url);
		String str = stringBuilder.substring(url.indexOf("http:"),url.indexOf("\" style"));
		fwbbjq.setZp(str);
		System.out.println(str);

		return R.status(fwbbjqService.saveOrUpdate(fwbbjq));
	}

	/**
	 * 将路径中的如片地址转成替换成base64形式
	 *
	 * @param urlStr
	 * @return
	 */
	public static String getUrl(String urlStr) {
		Pattern pattern = Pattern.compile("(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
		Matcher matcher = pattern.matcher(urlStr);
		while (matcher.find()) {
			//替换路径中的://   注意不要只替换//
			String replaceStr = matcher.group().replace("://", "");
			String base64 = getBase64(matcher.group());
			urlStr = urlStr.replace("://", "").replace(replaceStr, "data:image/png;base64," + base64);
		}
		return urlStr;
	}

	/**
	 * 根据图片地址转成base64
	 *
	 * @param imageUrl
	 * @return
	 */
	public static String getBase64(String imageUrl) {
		InputStream in = null;
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		try {
			URL url = new URL(imageUrl);
			byte[] by = new byte[1024];
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			in = conn.getInputStream();
			int len = -1;
			while ((len = in.read(by)) != -1) {
				data.write(by, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		String encode = encoder.encode(data.toByteArray());
		return encode;
	}

	/**
	 * 删除
	 */
	@ApiLog("删除通知通告")
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(fwbbjqService.removeByIds(Func.toLongList(ids)));
	}


	/**
	 * 上传文件
	 *
	 * @param file 文件
	 * @return ObjectStat
	 */
	@SneakyThrows
	@PostMapping("/put-file")
	public R<BladeFile> putFile(@RequestParam MultipartFile file) {
		BladeFile bladeFile = ossBuilder.template().putFile(file.getOriginalFilename(), file.getInputStream());
		return R.data(bladeFile);
	}


	/**
	 * 移动端  查询最新的三条通知通告
	 */
	@GetMapping("/newList")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入fwbbjq")
	public R<List<Fwbbjq>> newList() {
		QueryWrapper<Fwbbjq> qe = new QueryWrapper<>();
//		Dept dept = deptService.getById(Long.parseLong(AuthUtil.getUser().getDeptId()));
//		String[] split = dept.getAncestors().split(",");
//		if (split.length == 3) {
//			qe.eq("bmid", dept.getParentId()).or().eq("bmid", split[1]);
//		}
//		if (split.length == 2) {
//			qe.eq("bmid", dept.getId()).or().eq("bmid", split[1]);
//		}
//		if (dept.getParentId() == 0) {
//			qe.isNotNull("bmid");
//		}
		qe.orderByDesc("tzsj");
		qe.last("limit 3");
		List<Fwbbjq> pages = fwbbjqService.list(qe);
		return R.data(pages);
	}

	/**
	 * 通过部门id  获取部门信息
	 */
	@GetMapping("/getDept")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "获取部门信息", notes = "")
	public R<Dept> getDept() {
		Dept dept = deptService.getById(Long.parseLong(AuthUtil.getUser().getDeptId()));
		return R.data(dept);
	}

	/**
	 * 通过登录用户获取用户下的县区部门结构
	 */
	@GetMapping("/getSsxq")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "获取部门信息", notes = "")
	public R<List<Dept>> getSsxq(@RequestParam String sssjDm) {
		QueryWrapper<Dept> qe = new QueryWrapper<>();
//		String regex = "[\u4e00-\u9fa5]";
//		Pattern pattern = Pattern.compile(regex);
//		Matcher match = pattern.matcher(sssjDm);
//		if(match.find()){
//			queryWrapper.eq("dept_name",sssjDm);
//			Dept one = deptService.getOne(queryWrapper);
//			qe.eq("parent_id",one.getId());
//		} else if (StringUtils.isNotEmpty(sssjDm)) {
//			qe.eq("parent_id", sssjDm);
//		} else {
//			if("1123598813738675201".equals(AuthUtil.getUser().getDeptId())){
//				qe.ne("parent_id", AuthUtil.getUser().getDeptId());
//				qe.ne("parent_id", "0");
//			}else{
//				qe.eq("parent_id", AuthUtil.getUser().getDeptId());
//			}
//		}


		if (StringUtils.isNotEmpty(sssjDm)) {
			String regex = "[\u4e00-\u9fa5]";
			Pattern pattern = Pattern.compile(regex);
			Matcher match = pattern.matcher(sssjDm);
			if (match.find()) {
				QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("dept_name", sssjDm);
				Dept one = deptService.getOne(queryWrapper);
				qe.eq("parent_id", one.getId());
			} else if (StringUtils.isNotEmpty(sssjDm)) {
				qe.eq("parent_id", sssjDm);
			}
		} else {
			if ("1123598813738675201".equals(AuthUtil.getUser().getDeptId())) {
				qe.ne("parent_id", AuthUtil.getUser().getDeptId());
				qe.ne("parent_id", "0");
			} else {
				qe.eq("parent_id", AuthUtil.getUser().getDeptId());
			}
		}
		List<Dept> list = deptService.list(qe);
		return R.data(list);
	}

	/**
	 * 通过登录用户获取用户下的市区部门结构
	 */
	@GetMapping("/getSssj")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "获取部门信息", notes = "")
	public R<List<Dept>> getSssj() {
		QueryWrapper<Dept> qe = new QueryWrapper<>();
		qe.eq("parent_id", AuthUtil.getUser().getDeptId());
		List<Dept> list = deptService.list(qe);
		return R.data(list);
	}

	/**
	 * 通过登录用户获取用户下的部门结构
	 */
	@GetMapping("/getSsxqToAdmin")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "获取部门信息", notes = "")
	public R<List<Dept>> getSsxqToAdmin() {
		QueryWrapper<Dept> qe = new QueryWrapper<>();
		qe.ne("parent_id", AuthUtil.getUser().getDeptId());
		qe.ne("parent_id", "0");
		List<Dept> list = deptService.list(qe);
		return R.data(list);
	}
}
