/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.modules.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import jakarta.validation.Valid;

import org.apache.commons.codec.Charsets;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.project.pojo.entity.WorkFocusProgressEntity;
import org.springblade.modules.project.pojo.excel.WorkFocusExcel;
import org.springblade.modules.project.pojo.excel.WorkFocusExcel2;
import org.springblade.modules.project.pojo.excel.WorkFocusImporter;
import org.springblade.modules.project.pojo.vo.WorkFocusDataInfoVO;
import org.springblade.modules.project.pojo.vo.WorkFocusListVO;
import org.springblade.modules.project.pojo.vo.WorkFocusProgressVO;
import org.springblade.modules.project.service.IWorkFocusProgressService;
import org.springblade.modules.system.pojo.entity.Menu;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.project.pojo.entity.WorkFocusEntity;
import org.springblade.modules.project.pojo.vo.WorkFocusVO;
import org.springblade.modules.project.wrapper.WorkFocusWrapper;
import org.springblade.modules.project.service.IWorkFocusService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

/**
 * 附件表 控制器
 *
 * @author BladeX
 * @since 2024-04-09
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-attach/workfocus")
@Tag(name = "工作要点表", description = "工作要点接口")
public class WorkFocusController extends BladeController {

	private final IWorkFocusService workfocusService;

	private final IWorkFocusProgressService workFocusProgressService;

	/**
	 * 附件表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description  = "传入workfocus")
	public R<WorkFocusVO> detail(WorkFocusEntity workfocus) {
		WorkFocusEntity detail = workfocusService.getOne(Condition.getQueryWrapper(workfocus));
		return R.data(WorkFocusWrapper.build().entityVO(detail));
	}
	/**
	 * 工作要点表 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description  = "传入workfocus")
	public R<IPage<WorkFocusVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> workfocus, Query query) {
		IPage<WorkFocusEntity> pages = workfocusService.page(Condition.getPage(query), Condition.getQueryWrapper(workfocus, WorkFocusEntity.class));
		return R.data(WorkFocusWrapper.build().pageVO(pages));
	}

	/**
	 * 工作要点表 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "自定义分页", description  = "传入workfocus")
	public R<IPage<WorkFocusVO>> page(WorkFocusVO workfocus, Query query) {
		IPage<WorkFocusVO> pages = workfocusService.selectWorkFocusPage(Condition.getPage(query), workfocus);
		return R.data(pages);
	}

	/**
	 * 工作要点表 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description  = "传入workfocus")
	public R save(@Valid @RequestBody WorkFocusEntity workfocus) {
		return R.status(workfocusService.save(workfocus));
	}

	/**
	 * 工作要点表 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description  = "传入workfocus")
	public R update(@Valid @RequestBody WorkFocusEntity workfocus) {
		return R.status(workfocusService.updateById(workfocus));
	}

	/**
	 * 工作要点表 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description  = "传入workfocus")
	public R submit(@Valid @RequestBody WorkFocusEntity workfocus) {
		return R.status(workfocusService.saveOrUpdate(workfocus));
	}

	/**
	 * 工作要点表 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description  = "传入ids")
	public R remove(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		return R.status(workfocusService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 导出数据
	 */
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@GetMapping("/export-workfocus")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导出数据", description  = "传入workfocus")
	public void exportWorkFocus(@Parameter(hidden = true) @RequestParam Map<String, Object> workfocus, BladeUser bladeUser, HttpServletResponse response) {
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(WorkFocus::getTenantId, bladeUser.getTenantId());
		//}
		LambdaQueryWrapper<WorkFocusEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(WorkFocusEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED).in(WorkFocusEntity::getId,Func.toLongList(workfocus.get("id_equal")+""));
		List<WorkFocusExcel> list = workfocusService.exportWorkFocus(queryWrapper);
		ExcelUtil.export(response, "工作要点表" + DateUtil.time(), "工作要点数据表", list, WorkFocusExcel.class);
	}

	/**
	 * 工作要点表 新增或修改
	 */
	@PostMapping("/submitList")
	@ApiOperationSupport(order = 10)
	@Operation(summary = "新增或修改", description  = "传入workfocus")
	public R submitList(@Valid @RequestBody WorkFocusListVO workFocusListVO) {
		if(workFocusListVO!=null && workFocusListVO.getWorkFocusEntityList().size()>=1){
			List<WorkFocusEntity> workFocusEntityList = workFocusListVO.getWorkFocusEntityList();
			for(WorkFocusEntity workFocusEntity:workFocusEntityList){
				workfocusService.saveOrUpdate(workFocusEntity);
				// 添加进度信息
				Integer startYear = workFocusEntity.getStartYear();
				Integer endYear = workFocusEntity.getEndYear();
				for(int i = startYear ; i <= endYear ; i++){
					List<WorkFocusProgressEntity> list = new ArrayList<>();
					for(int j=1 ; j <=14 ; j++){
						WorkFocusProgressEntity workFocusProgress = new WorkFocusProgressVO();
						workFocusProgress.setYear(i);
						workFocusProgress.setWorkFocusId(workFocusEntity.getId());
						workFocusProgress.setMonth(j);
						if(j==13){
							workFocusProgress.setSchedule("unitInfo");
						}if(j==14){
							workFocusProgress.setSchedule("linkInfo");
						}
						list.add(workFocusProgress);
					}
					workFocusProgressService.saveOrUpdateBatch(list);
				}
			}
		}
		return R.status(true);
	}


	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@ApiOperationSupport(order = 11)
	@Operation(summary = "导出模板", description  = "导出模板")
	public void exportUser(HttpServletResponse response) throws Exception {
		//List<WorkFocusEntity> list = new ArrayList<>();
		//ExcelUtil.export(response, "用户数据模板" + DateUtil.time(), "用户数据表", list, WorkFocusEntity.class);

		String mame="工作要点导入模版";
		String url = "https://blade-oss-chongqing.oss-cn-shenzhen.aliyuncs.com//upload/20240507/977249de5d6d16e57fe3ed21235b743e.xlsx";
		String fileName = URLEncoder.encode(mame, Charsets.UTF_8.name());
		InputStream redio = CommonUtil.getOSSInputStream(url);
		byte[] buffer = IoUtil.readToByteArray(redio);
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(org.apache.commons.codec.Charsets.UTF_8.name());
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
	}


	/**
	 * 导入 数据模板
	 */
	@PostMapping("import-workfocus")
	@ApiOperationSupport(order = 12)
	@Operation(summary = "导入工作要点", description  = "导出模板")
	public R importUser(MultipartFile file, Integer isCovered) {
		List<WorkFocusExcel2> read = ExcelUtil.read(file, 0, 0, WorkFocusExcel2.class);

		int moth = 0;
		int year = 0;
		Integer maxId = 1;
		List<WorkFocusEntity> workFocus = new ArrayList<>();
		List<WorkFocusProgressEntity> workFocusProgressEntities = new ArrayList<>();
		WorkFocusListVO workFocusListVO = new WorkFocusListVO();
		for (int i = 0; i < read.size(); i++) {
			WorkFocusExcel2 readInfo = read.get(i);
			String dataNo = readInfo.getDataNo();
			if(dataNo.indexOf("、")>=0){
				String node= dataNo.substring(0,dataNo.indexOf("、"));
				if(node.equals("一")){
					maxId=1;
				}
				if(node.equals("二")){
					maxId=2;
				}
				if(node.equals("三")){
					maxId=3;
				}
				if(node.equals("四")){
					maxId=4;
				}
				if(node.equals("五")){
					maxId=5;
				}
				if(node.equals("六")){
					maxId=6;
				}
				if(node.equals("七")){
					maxId=7;
				}
				if(node.equals("八")){
					maxId=8;
				}

			}else {
				if (i < 2) {
					if (dataNo.indexOf("年") >= 0 && dataNo.indexOf("月") >= 0) {
						String moth2 = dataNo.substring(dataNo.indexOf("年") + 1, dataNo.indexOf("月"));
						moth = Func.toInt(moth2);
					}
					if (dataNo.indexOf("交通强市建设") >= 0 && dataNo.indexOf("月") >= 0) {
						String year2 = dataNo.substring(dataNo.indexOf("交通强市建设") + 6, dataNo.indexOf("年"));
						year = Func.toInt(year2);
					}
				} else {

					WorkFocusEntity region = new WorkFocusEntity();
					List<WorkFocusEntity> workFocusEntities = workfocusService.getBaseMapper().selectList(Wrappers.<WorkFocusEntity>lambdaQuery().eq(WorkFocusEntity::getWorkPlan, readInfo.getWorkPlan()));
					if(workFocusEntities!=null && workFocusEntities.size()>=1){
						WorkFocusEntity  region2 = workFocusEntities.get(0);
						region = BeanUtil.copyProperties(readInfo, WorkFocusEntity.class);
						region.setId(region2.getId());

					}else{
						region = BeanUtil.copyProperties(readInfo, WorkFocusEntity.class);
					}

					BeanUtil.copyProperties(readInfo, WorkFocusProgressEntity.class);

					region.setWorkFocusStage(maxId);
					if(Func.isNotEmpty(readInfo.getStartYear())){
						region.setStartYear(Func.toInt(readInfo.getStartYear()));
					}
					if(Func.isNotEmpty(readInfo.getEndYear())){
						region.setEndYear(Func.toInt(readInfo.getEndYear()));
					}
					if(Func.isNotEmpty(readInfo.getEndYear()) && Func.isNotEmpty(readInfo.getEndYear())){

						workfocusService.saveOrUpdate(region);
						// 添加进度信息
						Integer startYear = region.getStartYear();
						Integer endYear = region.getEndYear();
						for(int k = startYear ; k <= endYear ; k++){
							List<WorkFocusProgressEntity> list = new ArrayList<>();

							for(int j=1 ; j <=14 ; j++) {
								WorkFocusProgressEntity workFocusProgress = new WorkFocusProgressEntity();
								// 数据判读是否存在
								List<WorkFocusProgressEntity>  workF = workFocusProgressService.getBaseMapper().selectList(Wrappers.<WorkFocusProgressEntity>lambdaQuery().
											eq(WorkFocusProgressEntity::getWorkFocusId, region.getId()).
											eq(WorkFocusProgressEntity::getYear, k).
											eq(WorkFocusProgressEntity::getMonth, j)
									);

								if(workF!=null && workF.size()>=1 ){
									workFocusProgress = workF.get(0);
									if(year==k && moth==j){
										long p_Key_id =workFocusProgress.getId();
										workFocusProgress = BeanUtil.copyProperties(readInfo, WorkFocusProgressEntity.class);
										workFocusProgress.setId(p_Key_id);
									}
								}else{
									if(year==k && moth==j){
										workFocusProgress = BeanUtil.copyProperties(readInfo, WorkFocusProgressEntity.class);
										workFocusProgress.setYear(k);
										workFocusProgress.setMonth(j);
									}else{
										workFocusProgress.setYear(k);
										workFocusProgress.setMonth(j);
									}
								}

								workFocusProgress.setWorkFocusId(region.getId());
								if(j==13){

									workFocusProgress.setSchedule("unitInfo");
									if(k==year){
										WorkFocusProgressEntity workFocusPss = BeanUtil.copyProperties(readInfo, WorkFocusProgressEntity.class);
										workFocusProgress.setProgress(workFocusPss.getUnitInfo());
									}
								}if(j==14){
									workFocusProgress.setSchedule("linkInfo");
									if(k==year) {
										WorkFocusProgressEntity workFocusPss = BeanUtil.copyProperties(readInfo, WorkFocusProgressEntity.class);
										workFocusProgress.setProgress(workFocusPss.getLinkInfo());
									}
								}
								list.add(workFocusProgress);
							}
							workFocusProgressService.saveOrUpdateBatch(list);
						}
					}
				}
			}
		}
		return R.success("操作成功");
	}

	/**
	 * 工作要点表 数据看板
	 */
	@GetMapping("/queryWorkFocusDataInfo")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "数据看板", description  = "数据看板")
	public R<WorkFocusDataInfoVO> queryWorkFocusDataInfo(WorkFocusVO workfocus, Query query) {
		WorkFocusDataInfoVO pages = workfocusService.queryWorkFocusDataInfo(workfocus);
		return R.data(pages);
	}
}
