/*
 *      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.xpgxb.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.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springblade.common.utils.AESUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.xpgxb.entity.XpgxbEntity;
import org.springblade.modules.xpgxb.excel.XpgxImporter;
import org.springblade.modules.xpgxb.excel.XpgxbExcel;
import org.springblade.modules.xpgxb.service.IXpgxbService;
import org.springblade.modules.xpgxb.vo.XpgxbVO;
import org.springblade.modules.xpgxb.wrapper.XpgxbWrapper;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 下派关系表 控制器
 *
 * @author BladeX
 * @since 2023-07-09
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-xpgxb/xpgxb")
@Api(value = "下派关系表", tags = "下派关系表接口")
public class XpgxbController extends BladeController {

	private final IXpgxbService xpgxbService;
	private final IDeptService deptService;
	private final IUserService userService;

	/**
	 * 下派关系表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入xpgxb")
	public R<XpgxbVO> detail(XpgxbEntity xpgxb) {
		XpgxbEntity detail = xpgxbService.getOne(Condition.getQueryWrapper(xpgxb));
		if (null != detail && StringUtils.isNotBlank(detail.getXpmjzzjhm())) {
			detail.setXpmjzzjhm(AESUtil.decrypt(detail.getXpmjzzjhm(), "2SexR1rfjZ8CD3M6"));
		}
		return R.data(XpgxbWrapper.build().entityVO(detail));
	}

	/**
	 * 下派关系表 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入xpgxb")
	public R<IPage<XpgxbVO>> list(@ApiIgnore @RequestParam Map<String, Object> xpgxb, Query query) {
		IPage<XpgxbEntity> pages = xpgxbService.page(Condition.getPage(query), Condition.getQueryWrapper(xpgxb, XpgxbEntity.class));
		return R.data(XpgxbWrapper.build().pageVO(pages));
	}

	/**
	 * 下派关系表 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入xpgxb")
	public R<IPage<XpgxbEntity>> page(@RequestParam Map<String, Object> params, Query query) {
		params.put("deptId", AuthUtil.getDeptId());
		IPage<XpgxbEntity> pages = xpgxbService.selectXpgxbPage(Condition.getPage(query), params);
//		for (XpgxbEntity xpgxbEntity : pages.getRecords()) {
//			User user = userService.selectUserIdByPhone(xpgxbEntity.getXpmjlxdh());
//			if (user != null) {
//				xpgxbEntity.setUserId(user.getId());
//			}
//		}
		return R.data(pages);
	}

	/**
	 * 下派关系表 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入xpgxb")
	public R save(@Valid @RequestBody XpgxbEntity xpgxb) {
		return R.status(xpgxbService.save(xpgxb));
	}

	/**
	 * 下派关系表 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入xpgxb")
	public R update(@Valid @RequestBody XpgxbEntity xpgxb) {
		return R.status(xpgxbService.updateById(xpgxb));
	}

	/**
	 * 下派关系表 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入xpgxb")
	public R submit(@Valid @RequestBody XpgxbEntity xpgxb) {
		if (StringUtils.isNotEmpty(xpgxb.getXpfj())) {
			String deptName = xpgxb.getXpfj();
			String fjId = deptService.getDeptIdByDeptname(deptName);
			xpgxb.setXpfjdm(fjId);
		}
		if (StringUtils.isNotEmpty(xpgxb.getXppcs())) {
			String deptName = xpgxb.getXppcs();
			String pcsId = deptService.getDeptIdByDeptname(deptName);
			xpgxb.setXppcsdm(pcsId);
		}
		if (StringUtils.isNotEmpty(xpgxb.getXpjws())) {
			String deptName = xpgxb.getXpjws();
			String jwsId = deptService.getDeptIdByDeptname(deptName);
			xpgxb.setXpjwsid(jwsId);
		}
		return R.status(xpgxbService.saveOrUpdate(xpgxb));
	}

	/**
	 * 下派关系表 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(xpgxbService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 导出数据
	 */
	@GetMapping("/export-xpgxb")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入xpgxb")
	public void exportXpgxb(@ApiIgnore @RequestParam Map<String, Object> xpgxb, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<XpgxbEntity> queryWrapper = Condition.getQueryWrapper(xpgxb, XpgxbEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(Xpgxb::getTenantId, bladeUser.getTenantId());
		//}
		queryWrapper.lambda().eq(XpgxbEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<XpgxbExcel> list = xpgxbService.exportXpgxb(queryWrapper);
		ExcelUtil.export(response, "下派关系表数据" + DateUtil.time(), "下派关系表数据表", list, XpgxbExcel.class);
	}


	/**
	 * 下派民警导入
	 *
	 * @param file
	 * @return
	 */
	@PostMapping("write-zcjzwj")
	public R<Boolean> writeNotice(MultipartFile file) {
		XpgxImporter xpgxImporter = new XpgxImporter(xpgxbService, deptService);
		ExcelUtil.save(file, xpgxImporter, XpgxbExcel.class);
		return R.success("操作成功");
	}


	//模板下载
	@RequestMapping(value = "/xpmbxz")
	public ResponseEntity<Resource> xpmbxz(HttpServletResponse response, HttpServletRequest request) {
		try {
			InputStream is = this.getClass().getClassLoader().getResourceAsStream("templates/xpmjmb.xlsx");
			Workbook workbook = new XSSFWorkbook(is);
			String fileName = "xpmjmb.xlsx";
			downLoadExcel(fileName, response, workbook);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ResponseEntity<Resource>(HttpStatus.OK);
	}

	public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
				"attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
