package digital.laboratory.platform.imr.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.imr.component.GetClientIPUtil;
import digital.laboratory.platform.imr.dto.DepositToDTO;
import digital.laboratory.platform.imr.dto.QueryDTO;
import digital.laboratory.platform.imr.dto.UseOutboundDTO;
import digital.laboratory.platform.imr.dto.UserInfoDTO;
import digital.laboratory.platform.imr.entity.CabinetOpeningRecord;
import digital.laboratory.platform.imr.entity.SampleStorage;
import digital.laboratory.platform.imr.mapper.DestructionDetailMapper;
import digital.laboratory.platform.imr.mapper.SampleStorageMapper;
import digital.laboratory.platform.imr.service.CabinetOpeningRecordService;
import digital.laboratory.platform.imr.vo.CabinetSampleVO;
import digital.laboratory.platform.imr.vo.StatisticsCount;
import digital.laboratory.platform.sys.feign.RemoteEnvironmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/cabinetOpen" )
@Api(value = "cabinetOpen", tags = "智能物证柜管理")
public class CabinetOpenController {

    private static final PasswordEncoder ENCODER = new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5");



    public final SampleStorageMapper storageMapper;


    private final DestructionDetailMapper ddMapper;


    public final RemoteEnvironmentService environmentService;


    public final CabinetOpeningRecordService openingRecordService;

    /*
    通过请求获取id判断是属于哪个房间获取温湿度
    这个接口不需要验证
     */

    @ApiOperation(value = "获取房间号", notes = "获取房间号")
    @GetMapping("/getRoom" )
    public R getRoom(HttpServletRequest request){

        //根据ip判断属于那个房间
        String ipAddress = GetClientIPUtil.getIpAddress(request);
        String roomNo = "";
        switch (ipAddress) {
            case "192.168.30.243":
                roomNo = "702";
                break;
            case "192.168.30.241":
                roomNo = "709";
                break;
            case "192.168.10.242":
                roomNo = "602";
                break;
            case "192.168.10.241":
                roomNo = "609";
                break;
            case "192.168.10.243":
                roomNo = "605";
                break;
            default:
                roomNo = "709";
        }


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




    @ApiOperation(value = "通过请求获取ip判断是属于哪个房间获取温湿度", notes = "通过请求获取ip判断是属于哪个房间获取温湿度")
    @GetMapping("/temperatureAndHumidity" )
    public R temperatureAndHumidity(HttpServletRequest request){

        //根据ip判断属于那个房间
        String ipAddress = GetClientIPUtil.getIpAddress(request);
        String roomNo = "";
        switch (ipAddress) {
            case "192.168.30.243":
                roomNo = "702";
                break;
            case "192.168.30.241":
                roomNo = "709";
                break;
            case "192.168.10.242":
                roomNo = "602";
                break;
            case "192.168.10.241":
                roomNo = "609";
                break;
            case "192.168.10.243":
                roomNo = "605";
                break;
            default:
                roomNo = "706";
        }

        R<Map<String, Double>> humiture = environmentService.getHumitureByRoomNo(roomNo);

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


	/*
	统计仓库模块的检材/样本
	 */

	@ApiOperation(value = "统计仓库模块的检材/样本type=1仓库现有样本总数;2出库待归还样本;3.退还出库/销毁出库样本", notes = "统计仓库模块的检材/样本")
	@GetMapping("/statisticsSampleCount/{type}" )
	public R<List<StatisticsCount>> statisticsSampleCount(@PathVariable("type") Integer type,HttpServletRequest request){


        //根据ip判断属于那个房间
        String ipAddress = GetClientIPUtil.getIpAddress(request);
        String roomNo = "";
        switch (ipAddress) {
            case "192.168.30.243":
                roomNo = "702";
                break;
            case "192.168.30.241":
                roomNo = "709";
                break;
            case "192.168.10.242":
                roomNo = "602";
                break;
            case "192.168.10.241":
                roomNo = "609";
                break;
            case "192.168.10.243":
                roomNo = "605";
                break;
            default:
                roomNo = "706";
        }


        ArrayList<StatisticsCount> list = new ArrayList<>();
        if(type==1){
			//仓库现有样本(要区分房间)
			QueryWrapper<SampleStorage> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("status",2);
            queryWrapper.eq("room_no",roomNo);
			Long count = storageMapper.selectCount(queryWrapper);
            list.add(new StatisticsCount("inbound",count));
		} else if (type==2) {
			//出库待归还样本
            QueryWrapper<SampleStorage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",3);
            queryWrapper.eq("is_return",1);
            queryWrapper.eq("room_no",roomNo);
            Long count = storageMapper.selectCount(queryWrapper);
            list.add(new StatisticsCount("return",count));

		} else if (type==3) {
			//出库样本
            QueryWrapper<SampleStorage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",3);
            queryWrapper.eq("room_no",roomNo);
            Long count = storageMapper.selectCount(queryWrapper);
            list.add(new StatisticsCount("outbound",count));
		}

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

	}


    /*
    扫码查询检材接口
     */
    @ApiOperation(value = "扫码查询检材接口/支持样本编号入库/取检码出库", notes = "扫码查询检材接口")
    @GetMapping("/scanCode/{number}" )
    public R<List<CabinetSampleVO>> scanCode(@PathVariable("number") String number){
        if(StrUtil.isEmpty(number)){
            throw new RuntimeException("编号不能为空");
        }
        List<CabinetSampleVO> vo = openingRecordService.scanCode(number);
        return R.ok(vo,"查询成功");
    }

    /*
    批量入库时扫码查询
     */
    @ApiOperation(value = "批量入库时扫码查询", notes = "批量入库时扫码查询")
    @GetMapping("/batchScanCode/{number}" )
    public R<List<CabinetSampleVO>> batchScanCode(@PathVariable("number") String number){
        if(StrUtil.isEmpty(number)){
            throw new RuntimeException("编号不能为空");
        }

        List<CabinetSampleVO> vo = openingRecordService.batchScanCode(number);

        if(vo==null || vo.size()==0){
            return R.failed("当前编号未查询到任何数据,请检查是否错误");
        }else {
            return R.ok(vo,"查询成功");
        }
    }

    /*
    扫码查询检材推荐位置入库(选择位置后确认入库)
     */
    @ApiOperation(value = "扫码推荐位置入库/批量入库--确认按钮--", notes = "扫码推荐位置入库--确认按钮")
    @PostMapping("/scanCodePromptInbound" )
    public R<String> scanCodePromptInbound(@RequestBody DepositToDTO dto, HttpServletRequest theHttpServletRequest){

        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        openingRecordService.scanCodePromptInbound(dto,dlpUser);

        return R.ok("存储成功","存储成功");
    }

    /*
    扫码查询检材显示存储位置出库(确认出库)
     */
    @ApiOperation(value = "扫码推荐出库--这里传入单个sampleId和监督人id", notes = "扫码推荐出库")
    @PostMapping("/scanCodePromptOutbound" )
    public R<String> scanCodePromptOutbound(@RequestBody UseOutboundDTO dto, HttpServletRequest theHttpServletRequest){

        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if(StrUtil.isEmpty(dto.getSupervisorId())){
            throw new RuntimeException("监督人不能为空");
        }

        openingRecordService.scanCodePromptOutbound(dto,dlpUser);

        return R.ok("出库成功","出库成功");
    }


    /*
    智能柜修改sample质量
     */
    @ApiOperation(value = "智能柜修改sample质量", notes = "智能柜修改sample质量")
    @PostMapping("/updateSampleQuality")
    public R<String> updateSampleQuality(String sampleId,double sampleQuality){

        if(StrUtil.isEmpty(sampleId)){
            throw new RuntimeException("id不能为空");
        }

        //查询并修改
        openingRecordService.updateSampleQuality(sampleId,sampleQuality);

        return R.ok(null,"修改质量成功");
    }




    /*
   根据取检码查询检材信息
     */
    @ApiOperation(value = "根据取检码查询检材信息", notes = "根据取检码查询检材信息")
    @GetMapping("/querySampleByCode" )
    public R<List<CabinetSampleVO>> querySampleByCode(String code,HttpServletRequest request){


        //根据ip判断属于那个房间
        String ipAddress = GetClientIPUtil.getIpAddress(request);
        String roomNo = "";
        switch (ipAddress) {
            case "192.168.30.243":
                roomNo = "702";
                break;
            case "192.168.30.241":
                roomNo = "709";
                break;
            case "192.168.10.242":
                roomNo = "602";
                break;
            case "192.168.10.241":
                roomNo = "609";
                break;
            case "192.168.10.243":
                roomNo = "605";
                break;
            default:
                roomNo = "709";
        }

        List<CabinetSampleVO> list = openingRecordService.querySampleByCode(code,roomNo);

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

    /*
    领用出库
     */
    @ApiOperation(value = "领用出库--这里传code和监督人id和sampleIds样本id集合", notes = "领用出库")
    @PostMapping("/useOutbound")
    public R<String> useOutbound(@RequestBody UseOutboundDTO dto, HttpServletRequest theHttpServletRequest){

        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if(StrUtil.isEmpty(dto.getSupervisorId())){
            throw new RuntimeException("监督人不能为空");
        }

        openingRecordService.useOutbound(dto,dlpUser);

        return R.ok("出库成功","出库成功");
    }



    /*
    强制开箱forceOpen
     */
    @ApiOperation(value = "强制开箱--这里传cellId和监督人id", notes = "强制开箱")
    @PostMapping("/forceOpen" )
    public R<String> forceOpen(@RequestBody UseOutboundDTO dto, HttpServletRequest theHttpServletRequest){

        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if(StrUtil.isEmpty(dto.getSupervisorId())){
            throw new RuntimeException("监督人不能为空");
        }
        if(StrUtil.isEmpty(dto.getPassword())){
            throw new RuntimeException("请填写密码");
        }

        String s = dlpUser.getPassword();
        String password = s.replace("{MD5}", "");
        Assert.isTrue(ENCODER.matches(dto.getPassword(), password), "密码错误, 请重试");
        openingRecordService.forceOpen(dto,dlpUser);
        return R.ok("出库成功","出库成功");
    }


    /*
    查询人接口
     */

    @ApiOperation(value = "查询人接口", notes = "查询人接口")
    @GetMapping("/getUserInfo" )
    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 = "分页查询开箱记录")
    @GetMapping("/page/openRecord" )
    public R<IPage<CabinetOpeningRecord>> openRecord(QueryDTO dto, HttpServletRequest theHttpServletRequest){

        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();


        String ipAddress = GetClientIPUtil.getIpAddress(theHttpServletRequest);
        String roomNo = "";
        switch (ipAddress) {
            case "192.168.30.243":
                roomNo = "702";
                break;
            case "192.168.30.241":
                roomNo = "709";
                break;
            case "192.168.10.242":
                roomNo = "602";
                break;
            case "192.168.10.241":
                roomNo = "609";
                break;
            case "192.168.10.243":
                roomNo = "605";
                break;
            default:
                roomNo = "706";
        }


        Page<CabinetOpeningRecord> recordPage = new Page<>(dto.getCurrent(), dto.getSize());

        QueryWrapper<CabinetOpeningRecord> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(StrUtil.isNotEmpty(dto.getName()),"open_person",dto.getName());
        queryWrapper.eq("warehouse",roomNo);
        queryWrapper.between(dto.getBeginDate()!=null && dto.getFinishDate()!=null,"open_time",dto.getBeginDate(),dto.getFinishDate());

        queryWrapper.orderByDesc("open_time");

        IPage<CabinetOpeningRecord> thisPage = openingRecordService.page(recordPage,queryWrapper);

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

    }

}
