package org.springblade.modules.appmenu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
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.appmenu.entity.AppMenu;
import org.springblade.modules.appmenu.entity.FileBase64;
import org.springblade.modules.appmenu.service.IAppMenuService;
import org.springblade.modules.appmenu.service.IFileBase64Service;
import org.springblade.modules.appmenu.vo.AppMenuVO;
import org.springblade.modules.appmenu.vo.DbsxVO;
import org.springblade.modules.appmenu.vo.QzgxVO;
import org.springblade.modules.appmenu.vo.SssjVO;
import org.springblade.modules.csInfo.service.ICsInfoService;
import org.springblade.modules.log.userLogin.entity.UserLoginEntity;
import org.springblade.modules.log.userLogin.service.IUserLoginService;
import org.springblade.modules.mdjfdj.service.IMdjfDjService;
import org.springblade.modules.sjapp.entity.SjApp;
import org.springblade.modules.sjapp.service.ISjAppService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.DeptListVo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author BladeX
 * @since 2022-11-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("appmenu")
@Api(value = "", tags = "接口")
public class AppMenuController extends BladeController {

	private final IAppMenuService appMenuService;
	private final IFileBase64Service fileBase64Service;
	private IMdjfDjService mdjfDjService;
	private IDeptService deptService;
	private ISjAppService sjAppService;
	private ICsInfoService csInfoService;
	private final IUserService userService;
	private final IUserLoginService userLoginService;

	/**
	 * 实时数据统计
	 */
	@Transactional
	@GetMapping("/getSssj")
	public R getSssj(@RequestParam Map<String, Object> params) {
		params.put("deptId", AuthUtil.getDeptId());
		params.put("userId", AuthUtil.getUserId());
		SssjVO sssjVO = csInfoService.getSssj(params);
		userService.updateLastLoginTime(AuthUtil.getUserAccount());
		UserLoginEntity userLoginEntity = new UserLoginEntity();
		userLoginEntity.setUserId(AuthUtil.getUserId());
		userLoginService.save(userLoginEntity);
		return R.data(sssjVO);
	}

	/**
	 * 待办事项
	 */
	@GetMapping("/getDbsx")
	public R getDbsx(@RequestParam Map<String, Object> params) {
		String deptId = AuthUtil.getDeptId();
		if (StringUtils.isNotBlank(deptId)) {
			params.put("userId", AuthUtil.getUserId());
			params.put("deptId", AuthUtil.getDeptId());
			List<DbsxVO> dbsxList = new ArrayList<>();
			// 查需调解的矛盾纠纷数量
			DbsxVO dbsxVOtj = mdjfDjService.getDbsxVOtj(deptId);
			dbsxVOtj.setType("矛盾纠纷");
			dbsxVOtj.setBz("您有" + dbsxVOtj.getTotal() + "起矛盾纠纷待调解");
			dbsxList.add(dbsxVOtj);
			// 查需回访的矛盾纠纷数量
			DbsxVO dbsxVOhf = mdjfDjService.getDbsxVOhf(deptId);
			dbsxVOhf.setType("矛盾纠纷");
			dbsxVOhf.setBz("您有" + dbsxVOhf.getTotal() + "起矛盾纠纷待回访");
			dbsxList.add(dbsxVOhf);
			// 查需检查的九小场所数量
			DbsxVO dbsxVOjc = csInfoService.getDbsxVOjc(deptId);
			dbsxVOjc.setType("消防检查");
			dbsxVOjc.setBz("您有" + dbsxVOjc.getTotal() + "家九小场所待检查");
			dbsxList.add(dbsxVOjc);
			return R.data(dbsxList);
		} else {
			return R.fail("请重新登录");
		}
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入appMenu")
	public R<AppMenu> detail(AppMenu appMenu) {
		AppMenu detail = appMenuService.getOne(Condition.getQueryWrapper(appMenu));
		return R.data(detail);
	}

	/**
	 * 判断当前APP是否需要强制更新 0无更新 1有更新 但不强制 2需要强制更新
	 */
	@GetMapping("/getQzgx")
	public R getQzgx(@RequestParam Map<String, Object> params) {
		Integer qzgx = appMenuService.getQzgx(params);
		if (null == qzgx) {
			qzgx = 0;
		} else if (qzgx >= 1) {
			qzgx = 1;
		} else if (qzgx == 0) {
			qzgx = 2;
		}
		QzgxVO qzgxVO = new QzgxVO();
		qzgxVO.setQzgx(qzgx);
		return R.data(qzgxVO);
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入appMenu")
	public R<IPage<AppMenu>> list(AppMenu appMenu, Query query) {
		IPage<AppMenu> pages = appMenuService.page(Condition.getPage(query), Condition.getQueryWrapper(appMenu));
		return R.data(pages);
	}

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

	/**
	 * 根据登陆用户的不同，产看不同的app授权列表
	 * 主要区分admin及地市
	 */
	@GetMapping("/listAppMc")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入appMenu")
	public R<List<AppMenu>> listAppMc() {
		Dept dept = deptService.getById(AuthUtil.getUser().getDeptId());
		String[] split = dept.getAncestors().split(",");
		List<AppMenu> listAppMc = new ArrayList<>();
		//地市查询本地市授权的app  admin查询所有
		if (split.length == 2) {
			QueryWrapper<SjApp> qe = new QueryWrapper<>();
			qe.select("appid");
			qe.eq("sjid", dept.getId().toString());
			qe.groupBy("appid");
			List<SjApp> list = sjAppService.list(qe);
			for (SjApp s:list) {
				if(StringUtils.isNotEmpty(s.getAppid())){
					listAppMc.add(appMenuService.getById(s.getAppid()));
				}
			}
		} else {
			listAppMc = appMenuService.list();

		}
		return R.data(listAppMc);
	}

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

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

	/**
	 * 新增或修改
	 */
	@PostMapping(path = "/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入appMenu")
	public R submit(@Valid AppMenu appMenu) {
		appMenu.setUserId(AuthUtil.getUser().getAccount());
		appMenu.setAppId("1678253135519535106");
		if (appMenu.getAppUrl().contains("172.16.1.41")) {
			appMenu.setAppUrl(appMenu.getAppUrl().replace("172.16.1.41", "111.26.204.4"));
		}
		/*if (file != null) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String format = simpleDateFormat.format(new Date());
			String uploadPath = "D:\\ydjwapp\\apkFile\\";
//			String uploadPath = "C:\\Users\\ASUS\\Desktop\\www\\";
			String uploadUrl = uploadPath + format + "_" + file.getOriginalFilename();
			// 判断文件是否为空
			if (!file.isEmpty()) {
				try {
					File filepath = new File(uploadUrl);
					if (!filepath.getParentFile().exists()) {
						filepath.getParentFile().mkdirs();
					}
					// 文件保存路径
					// 转存文件
					file.transferTo(filepath);
					List<String> srcFiles = new ArrayList<String>();
					srcFiles.add(uploadUrl);
					String originalFilename = file.getOriginalFilename();
					originalFilename = "_" + originalFilename.substring(0, originalFilename.indexOf(".")) + ".zip";
					String destFile = uploadPath + format + originalFilename;
					String passwd = null;
					long fileSize = 2 * 1024 * 1024;
					try {
						//1.压缩
						try {
							String zipUrls = ZipUtils.zip(srcFiles, destFile, passwd, fileSize);
							String[] split = zipUrls.split(",");
							for (int i = 0; i < split.length; i++) {
								//文件转换base64
								FileToBase64 fileToBase64 = new FileToBase64();
								String base64Code = fileToBase64.encodeBase64File(split[i].trim());
								//存base
								FileBase64 fileBase64 = new FileBase64();
								fileBase64.setFileBase64(base64Code);
								fileBase64.setFileName(split[i].trim());
								fileBase64Service.save(fileBase64);
							}
							appMenu.setAppUrl(zipUrls.replaceAll(" ", ""));
						} catch (net.lingala.zip4j.exception.ZipException e) {
							e.printStackTrace();
						}
					} catch (ZipException e) {
						e.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}*/
		return R.status(appMenuService.saveOrUpdate(appMenu));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		if(StringUtils.isNotEmpty(ids)){
			String[] split = ids.split(",");
			for (int i = 0; i < split.length; i++) {
				appMenuService.getById(split[i]);
				//删除app时，将市局app列表中相关app数据关联删除
				QueryWrapper<SjApp> qe = new QueryWrapper<>();
				qe.eq("appid",split[i]);
				sjAppService.remove(qe);
			}
		}
		return R.status(appMenuService.removeByIds(Func.toLongList(ids)));
	}


	/**
	 * 查看文件base64编码
	 */
	@PostMapping("/listFileBase64")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "FileBase64")
	public R<FileBase64> listFileBase64(FileBase64 fileBase64) {
		FileBase64 detail = fileBase64Service.getOne(Condition.getQueryWrapper(fileBase64));
		return R.data(detail);
	}

	/**
	 * 获取当前用户属于哪几个部门
	 */
	@PostMapping("/getDeptList")
	public R getDeptList() {
		List<DeptListVo> data = deptService.getDeptList(AuthUtil.getUserId());
		return R.data(data);
	}


	@GetMapping("/getDeptList1")
	public R getDeptList1() {
		List<DeptListVo> data = deptService.getDeptList(AuthUtil.getUserId());
		return R.data(data);
	}
}
