package digital.laboratory.platform.imr.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.common.log.annotation.SysLog;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.imr.dto.DestructionPublicityDTO;
import digital.laboratory.platform.imr.dto.PublicityDTO;
import digital.laboratory.platform.imr.dto.QueryDTO;
import digital.laboratory.platform.imr.dto.UserInfoDTO;
import digital.laboratory.platform.imr.entity.DestructionPublicity;
import digital.laboratory.platform.imr.entity.SampleStorage;
import digital.laboratory.platform.imr.mapper.DestructionDetailMapper;
import digital.laboratory.platform.imr.mapper.DestructionPublicityMapper;
import digital.laboratory.platform.imr.mapper.SampleStorageMapper;
import digital.laboratory.platform.imr.service.DestructionPublicityService;
import digital.laboratory.platform.imr.vo.DestructionPublicityVO;
import digital.laboratory.platform.imr.vo.OutSampleVO;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;

/**
 * 
 *
 * @author Zhang Xiaolong created at  2023-03-23
 * @describe  前端控制器
 *
 * 这是与表示层的接口, 不应该接业务逻辑写在这里, 业务逻辑应该写在 service 中
 * 这里写什么:
 *     为前端提供数据, 接受前端的数据
 *     为前端提供的数据, 从 service 取得后, 可以做一些适当的加工, 这种加工不是业务层面的, 只能是数据格式上, 为方便前端处理
 *     接受前端的数据, 每一个函数的参数可以先做一些整理后, 再调用 service 中的函数。这里对参数的整理, 应该只是格式上的, 而不能是业务上的
 * 数据层在 mapper 中, 数据层不涉及业务, 只管技术上的 对象<->表 之间的转换
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/destruction_publicity" )
@Api(value = "destruction_publicity", tags = "检材销毁与公示管理")
public class DestructionPublicityController {

    private final  DestructionPublicityService dpService;


	private final DestructionDetailMapper ddMapper;

	private final DestructionPublicityMapper dpMapper;


	private final SampleStorageMapper storageMapper;

	/**
	 * 通过id查询
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询公示详情", notes = "通过id查询公示详情")
	@GetMapping("/getOneById/{id}" )
	@PreAuthorize("@pms.hasPermission('imr_destruction_publicity_get')" )
	public R<DestructionPublicity> getOneById(@PathVariable("id" ) String id, HttpServletRequest theHttpServletRequest) {
		if(id==null||"".equals((id))){
			throw new RuntimeException(String.format("申请id不能为空" ));
		}
		DestructionPublicity  vo = dpService.getOneById(id);
		return R.ok(vo);
	}

	/**
     * 分页查询
     * @param dto 分页对象
     * @param dto
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('imr_destruction_publicity_get')" )
    public R<IPage<DestructionPublicityVO>> getDestructionPublicityPage(PublicityDTO dto, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

		Page<DestructionPublicity> page = new Page<>(dto.getCurrent(),dto.getSize());

		IPage<DestructionPublicityVO> vo =  dpService.getDestructionPublicityPage(page,Wrappers.<DestructionPublicity>query()
				.between(dto.getBeginDate()!=null && dto.getFinishDate()!=null,"release_date",dto.getBeginDate(),dto.getFinishDate())
				.eq("status",dto.getStatus())
		);
		return R.ok(vo,"查询成功");
    }

	/**
	 * 列表查询
	 */


    /**
     * 新增
     * @param dto
     * @return R
     */
    @ApiOperation(value = "创建检材销毁与公示", notes = "新增")
    @SysLog("新增" )
    @PostMapping("/createPublicity")
    @PreAuthorize("@pms.hasPermission('imr_destruction_publicity_add')" )
    public R createPublicity(@RequestBody DestructionPublicityDTO dto, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

		if (dto.getDestroyDate()==null||
			dto.getReviewerId()==null||
			dto.getDestroyCompany()==null||
			dto.getSampleIds().isEmpty()
		){
			throw new RuntimeException(String.format("公示数据不能为空"));
		 }

		DestructionPublicityVO vo = null;
		if(dto.getId()==null){
			vo = dpService.createPublicity(dto,dlpUser);
		}else {
			vo = dpService.updatePublicity(dto,dlpUser);
		}

		if (vo!=null){
			return R.ok(vo,"公示创建成功");
		}else{
			return R.failed("公示创建失败");
		}
    }

    /**
     * 修改
     * @param dto
     * @return R
     */
    @ApiOperation(value = "修改", notes = "修改")
    @SysLog("修改" )
    @PutMapping("/updatePublicity")
    @PreAuthorize("@pms.hasPermission('imr_destruction_publicity_edit')" )
    public R<DestructionPublicity> updatePublicity(@RequestBody DestructionPublicityDTO dto, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
		if (dto.getDestroyDate()==null||
				dto.getReviewerId()==null||
				dto.getDestroyCompany()==null||
				dto.getSampleIds().isEmpty()||
				dto.getId()==null
		){
			throw new RuntimeException(String.format("创建销毁与申请的数据不能为空"));
		}
		DestructionPublicityVO vo = dpService.updatePublicity(dto,dlpUser);

		if (vo!=null){
			return R.ok(vo,"操作成功");
		}else{
			return R.failed("操作失败");
		}
    }

    /**
     * 单个通过id删除
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @SysLog("通过id删除" )
    @DeleteMapping("/delete/{id}" )
    @PreAuthorize("@pms.hasPermission('imr_destruction_publicity_del')" )
    public R deleteOneById(@PathVariable("id") String id) {


		dpService.deleteOneById(id);

		return R.ok(null,"删除成功");
    }



	@ApiOperation(value = "批量删除", notes = "批量删除")
	@SysLog("通过id删除" )
	@DeleteMapping("/deleteList" )
	@PreAuthorize("@pms.hasPermission('imr_destruction_publicity_del')" )
	public R deleteOneById(@RequestBody List<String> ids) {


		for (String id : ids) {
			dpService.deleteOneById(id);
		}
		return R.ok(null,"删除成功");

	}


	@ApiOperation(value = "查询审核人接口", notes = "查询审核人接口")
	@GetMapping("/getApprove" )
	@PreAuthorize("@pms.hasPermission('imr_destruction_publicity_get')" )
	public R getApprove(String name, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();


		//查询全部接收人
		List<UserInfoDTO> user = ddMapper.getApprove(name,dlpUser.getId());
		return R.ok(user,"查询成功");
	}

	/**
	 * 发布/提交
	 */
	@ApiOperation(value = "发布/提交", notes = "发布/提交")
	@PutMapping("/release" )
	@PreAuthorize("@pms.hasPermission('imr_destruction_publicity_edit')" )
	public R release(String id, HttpServletRequest theHttpServletRequest) {

		if(id == null){
			throw new RuntimeException(String.format("id不能为空"));
		}

		DestructionPublicity  vo = dpService.release(id);

		return R.ok(vo,"发布成功");
	}


	/*
		查询可公示的样本(审核审批成功后的)
	 */
	@ApiOperation(value = "查询可公示的样本(审核审批成功后的)", notes = "查询可公示的样本(审核审批成功后的)")
	@GetMapping("/getSampleInfo" )
	@PreAuthorize("@pms.hasPermission('imr_destruction_publicity_get')" )
	public R getSampleInfo(QueryDTO dto) {

		List<String> sampleIds = Arrays.asList(dto.getSampleIds().split(","));
		int size = sampleIds.size();
		if ("".equals(dto.getSampleIds())){
			size = sampleIds.size()-1;
		}


		if(dto.getTotal()!=0){
			int num = 0;//去重后目前能分的页数

			if((dto.getTotal()-size)%8==0){
				num = (dto.getTotal()-size)/8;
			}else {
				num = (dto.getTotal()-size)/8+1;
			}

			System.out.println(num);

			if(dto.getCurrent()>num){
				//求余数
				int a = dto.getTotal()%8;//求最后一页的剩余条数
				if(a==0){
					a=8;
					if(sampleIds.size()>=a){
						dto.setCurrent(num);
					}
				}else {
					if(sampleIds.size()>=a){
						dto.setCurrent(num);
					}
				}
			}
		}
		Page<SampleStorage> page = new Page<>(dto.getCurrent(),dto.getSize());

		IPage<OutSampleVO> sampleVOIPage = storageMapper.getSampleInfo(page,Wrappers.<SampleStorage>query()
				.notIn(!sampleIds.isEmpty(),"storage.sample_id",sampleIds)//去重数组sampleIds
				.like(!dto.getName().isEmpty(),"storage.name",dto.getName())
				.eq("storage.early_warning",2)  //只能查找通过审核审批的样本
				.eq("s.status",7)//状态等于待销毁

		);
		List<OutSampleVO> records = sampleVOIPage.getRecords();
		for (OutSampleVO vo : records) {
			vo.setSampleId(vo.getId());
		}

		return R.ok(sampleVOIPage,"查询成功");
	}

}