package org.springblade.modules.sign.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.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.JlrhJws.service.IJlrhJwsService;
import org.springblade.modules.JlrhJws.vo.JlrhJwsVO;
import org.springblade.modules.sign.entity.SignEntity;
import org.springblade.modules.sign.excel.SignExcel;
import org.springblade.modules.sign.excel.SignExceptionExcel;
import org.springblade.modules.sign.service.ISignService;
import org.springblade.modules.sign.vo.SignExceptionVO;
import org.springblade.modules.sign.vo.SignVO;
import org.springblade.modules.sign.vo.SignVOS;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * 考勤 控制器
 *
 * @author BladeX
 * @since 2023-07-07
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-sign/Sign")
@Api(value = "考勤", tags = "考勤接口")
public class SignController extends BladeController {

	private final ISignService SignService;
	private final IUserService userService;
	private final IJlrhJwsService jlrhJwsService;

	/**
	 * 考勤 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入Sign")
	public R<SignEntity> detail(SignEntity Sign) {
		SignEntity detail = SignService.getOne(Condition.getQueryWrapper(Sign));
		QueryWrapper<User> qe = new QueryWrapper<>();
		qe.eq("id",detail.getUserId());
		User user = userService.getOne(qe);
		detail.setName(user.getName());
		return R.data(detail);
	}

	@GetMapping("/getDkfw")
	public R getDkfw() {
		String deptIds = AuthUtil.getDeptId();
		String[] deptIdList = deptIds.split(",");
		List<JlrhJwsVO> data = new ArrayList<>();
		for (String deptId : deptIdList) {
			List<JlrhJwsVO> jwsList = jlrhJwsService.getDkfw(deptId);
			if (!jwsList.isEmpty()) {
				for (JlrhJwsVO jwsVO : jwsList) {
					data.add(jwsVO);
				}
			}
		}
		JlrhJwsVO jwsVO = jlrhJwsService.getPcsJwd(deptIdList[0]);
		if (null != jwsVO) {
			data.add(jwsVO);
		}
		return R.data(data);
	}

	/**
	 * 考勤 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入Sign")
	public R<IPage<SignEntity>> list(@ApiIgnore @RequestParam Map<String, Object> Sign, Query query) {
		IPage<SignEntity> pages = SignService.page(Condition.getPage(query), Condition.getQueryWrapper(Sign, SignEntity.class));
		for (SignEntity signEntity:pages.getRecords()){
			QueryWrapper<User> qe = new QueryWrapper<>();
			qe.eq("id",signEntity.getUserId());
			User user = userService.getOne(qe);
			signEntity.setName(user.getName());
		}
		return R.data(pages);
	}

	/**
	 * 考勤 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入Sign")
	public R<IPage<SignVO>> page(SignVO signVOa, Query query) {
//		IPage<SignVO> pages = SignService.selectSignPage(Condition.getPage(query), signVOa);
		// 查参与考勤的人员列表
		IPage<SignVO> pages = SignService.selectSignUser(Condition.getPage(query), signVOa);
		for (SignVO signVO:pages.getRecords()){
			List<String> signVOSSS = new ArrayList<>();
			List<SignVOS> list = SignService.selectSign(signVO.getUserId(),signVOa.getMathvalue());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MONTH,0 );
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			int max = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
			int a = 0;
			for (int i = 0; a < max; a++) {
				for (SignVOS signVOS:list) {
					calendar.set(Calendar.DAY_OF_MONTH, ++i);
					String day = sdf.format(calendar.getTime());
					if (signVOS.getRq().equals(day)){
						signVOSSS.add(signVOS.getType());
						//signVOSSS.setType(signVOS.getType());
					}else {
						signVOSSS.add("0");
						break;
						//signVOSSS.setType(0);
					}
				}
			}
			signVO.setChildren(signVOSSS);
		}
		return R.data(pages);
	}

	/**
	 * 考勤 导出
	 */
	@GetMapping("/export-sign")
	public void page(@RequestParam Map<String, Object> params, HttpServletResponse response) {
		OutputStream os = null;
		try {
			OutputStream out = response.getOutputStream();
			String filePath = "C:\\Users\\86188\\Desktop\\考勤数据.xlsx";
			if (filePath.startsWith("file:")) {
				filePath = filePath.substring(5);
			}
			FileInputStream tps = new FileInputStream(new File(filePath));
			final XSSFWorkbook tpWorkbook = new XSSFWorkbook(tps);
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode("考勤数据", "UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
			response.setContentType("application/vnd.ms-excel");
			// 新建一个Excel的工作空间
			XSSFWorkbook workbook = new XSSFWorkbook();
			// 把模板复制到新建的Excel
			workbook = tpWorkbook;
			XSSFCellStyle xssfCellStyle = workbook.createCellStyle();
			xssfCellStyle.setBorderTop(BorderStyle.THIN);
			xssfCellStyle.setBorderBottom(BorderStyle.THIN);
			xssfCellStyle.setBorderLeft(BorderStyle.THIN);
			xssfCellStyle.setBorderRight(BorderStyle.THIN);
			// 以下是填充数据
			// 第1个sheet
			Sheet sheet1 = workbook.getSheetAt(0);
			Row row2 = sheet1.getRow(1);
			// 第2行 A列 : 查库日期
			row2.getCell(0).setCellValue("李冬雪");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 考勤 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入Sign")
	public R save(@RequestBody SignEntity Sign) {
		if (null == Sign.getUserId()) {
			BladeUser user = AuthUtil.getUser();
			Long userId = user.getUserId();
			Sign.setUserId(userId);
		}
		return R.status(SignService.save(Sign));
	}

	/**
	 * 考勤 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入Sign")
	public R update(@Valid @RequestBody SignEntity Sign) {
		return R.status(SignService.updateById(Sign));
	}

	/**
	 * 考勤 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入Sign")
	public R submit(@Valid @RequestBody SignEntity Sign) {
		return R.status(SignService.saveOrUpdate(Sign));
	}

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


	/**
	 * 导出数据
	 */
	@GetMapping("/export-Sign")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入Sign")
	public void exportSign(@ApiIgnore @RequestParam Map<String, Object> Sign, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<SignEntity> queryWrapper = Condition.getQueryWrapper(Sign, SignEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(Sign::getTenantId, bladeUser.getTenantId());
		//}
		queryWrapper.lambda().eq(SignEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<SignExcel> list = SignService.exportSign(queryWrapper);
		ExcelUtil.export(response, "考勤数据" + DateUtil.time(), "考勤数据表", list, SignExcel.class);
	}

	/**
	 * 根据userid查询这个人的打卡记录
	 */
	@GetMapping("/selectDkjlByUserid")
	public R selectDkjlByUserid(Long userId,String yf){
		int index = yf.lastIndexOf("-");
		String date = yf.substring(0,index);
		return R.data(SignService.selectDkjlByUserid(userId,date));
	}

	/**
	 * 获取当前登陆人的下级部门
	 */
	@GetMapping("selectBm")
	public R selectBm(){
		return R.data(SignService.selectBm(AuthUtil.getDeptId()));
	}

	/**
	 * 获取打卡异常列表
	 */
	@GetMapping("/getSignException")
	public R getSignException(@RequestParam Map<String, Object> params, Query query){
		params.put("deptId", AuthUtil.getDeptId());
		IPage<SignExceptionVO> pages = SignService.getSignException(Condition.getPage(query), params);
		return R.data(pages);
	}

	/**
	 * 导出打卡异常列表
	 */
	@GetMapping("/export-info")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入info")
	public void exportInfo(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) {
		params.put("deptId", AuthUtil.getDeptId());
		List<SignExceptionExcel> list = SignService.exportInfo(params);
		ExcelUtil.export(response, "打卡异常表" + DateUtil.time(), "打卡异常表", list, SignExceptionExcel.class);
	}

	/**
	 * 获取打卡异常照片
	 */
	@GetMapping("/getSignZp")
	public R getSignZp(@RequestParam Map<String, Object> params){
		String header = "data:image/jpeg;base64,";
		SignEntity zp = SignService.getSignZpById(params);
		zp.setZps(header + zp.getQdzp());
		return R.data(zp);
	}

}
