package com.qmth.sop.server.api;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.sop.business.bean.params.DeviceInOutSubmitParam;
import com.qmth.sop.business.bean.result.DeviceInOutResult;
import com.qmth.sop.business.bean.result.SearchResult;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBDeviceInOut;
import com.qmth.sop.business.service.SysUserService;
import com.qmth.sop.business.service.TBDeviceInOutService;
import com.qmth.sop.common.annotation.OperationLog;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.DeviceStatusEnum;
import com.qmth.sop.common.enums.DeviceUsageTypeEnum;
import com.qmth.sop.common.enums.LogTypeEnum;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 设备出入库登记 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2023-08-01
 */
@Api(tags = "设备出入库管理前端控制器")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_DEVICE_IN_OUT)
public class TBDeviceInOutController {
    @Resource
    private TBDeviceInOutService tbDeviceInOutService;
    @Resource
    private SysUserService sysUserService;

    @ApiOperation(value = "sop管理 - 设备出入库登记查询")
    @RequestMapping(value = "/sop_page", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = DeviceInOutResult.class)})
    public Result findDeviceInOutPageBySop(@ApiParam(value = "服务单元id") @RequestParam(required = false) String serviceUnitId,
                                           @ApiParam(value = "用途类型") @RequestParam(required = false) DeviceUsageTypeEnum usageType,
                                           @ApiParam(value = "登记人") @RequestParam(required = false) String userId,
                                           @ApiParam(value = "运行状态") @RequestParam(required = false) DeviceStatusEnum deviceStatus,
                                           @ApiParam(value = "出入库时间 - 开始") @RequestParam(required = false) Long inOutTimeStart,
                                           @ApiParam(value = "出入库时间 - 结束") @RequestParam(required = false) Long inOutTimeEnd,
                                           @ApiParam(value = "设备编号") @RequestParam(required = false) String deviceNo,
                                           @ApiParam(value = "设备序列号") @RequestParam(required = false) String deviceSerialNo,
                                           @ApiParam(value = "客户名称") @RequestParam(required = false) String customName,
                                           @ApiParam(value = "当前地") @RequestParam(required = false) String location,
                                           @ApiParam(value = "发往地") @RequestParam(required = false) String address,
                                           @ApiParam(value = "登记流水号") @RequestParam(required = false) String serialNo,
                                           @ApiParam(value = "分页页数", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                           @ApiParam(value = "分页容量", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {

        return ResultUtil.ok(tbDeviceInOutService.findDeviceInOutPageBySop(SystemConstant.convertIdToLong(serviceUnitId),
                usageType, SystemConstant.convertIdToLong(userId), deviceStatus, inOutTimeStart, inOutTimeEnd, deviceNo, deviceSerialNo, customName, location, address, serialNo,
                pageNumber, pageSize));
    }

    @ApiOperation(value = "查询可出库的设备信息")
    @RequestMapping(value = "/can_out_info", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = DeviceInOutResult.class)})
    public Result findDeviceCanOutInfo(@ApiParam(value = "供应商id") @RequestParam(required = false) String supplierId,
                                       @ApiParam(value = "sop编号") @RequestParam(required = false) String sopNo) {
        return ResultUtil.ok(tbDeviceInOutService.findDeviceCanOutInfo(SystemConstant.convertIdToLong(supplierId), sopNo));
    }

    @ApiOperation(value = "查询可入库的设备信息")
    @RequestMapping(value = "/can_in_info", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = DeviceInOutResult.class)})
    public Result findDeviceCanInInfo(@ApiParam(value = "供应商id") @RequestParam(required = false) String supplierId,
                                      @ApiParam(value = "派单号") @RequestParam(required = false) String sopNo) {
        return ResultUtil.ok(tbDeviceInOutService.findDeviceCanInInfo(SystemConstant.convertIdToLong(supplierId), sopNo));
    }

    @ApiOperation(value = "设备出入库提交")
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "更新成功", response = Result.class)})
    @OperationLog(logType = LogTypeEnum.ADD)
    public Result deviceInOutSubmit(@Valid @RequestBody DeviceInOutSubmitParam deviceInOutSubmitParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        tbDeviceInOutService.deviceInOutSubmit(deviceInOutSubmitParam);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "资源保障-设备保障-出入库登记查询")
    @RequestMapping(value = "/source_page", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = DeviceInOutResult.class)})
    public Result findDeviceInOutPageBySource(@ApiParam(value = "服务单元id") @RequestParam(required = false) String serviceUnitId,
                                              @ApiParam(value = "用途类型") @RequestParam(required = false) DeviceUsageTypeEnum usageType,
                                              @ApiParam(value = "登记人") @RequestParam(required = false) String userId,
                                              @ApiParam(value = "运行状态") @RequestParam(required = false) DeviceStatusEnum deviceStatus,
                                              @ApiParam(value = "出入库时间 - 开始") @RequestParam(required = false) Long inOutTimeStart,
                                              @ApiParam(value = "出入库时间 - 结束") @RequestParam(required = false) Long inOutTimeEnd,
                                              @ApiParam(value = "设备编号") @RequestParam(required = false) String deviceNo,
                                              @ApiParam(value = "设备序列号") @RequestParam(required = false) String deviceSerialNo,
                                              @ApiParam(value = "客户名称") @RequestParam(required = false) String customName,
                                              @ApiParam(value = "当前地") @RequestParam(required = false) String location,
                                              @ApiParam(value = "发往地") @RequestParam(required = false) String address,
                                              @ApiParam(value = "登记流水号") @RequestParam(required = false) String serialNo,
                                              @ApiParam(value = "分页页数", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                              @ApiParam(value = "分页容量", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {

        return ResultUtil.ok(tbDeviceInOutService.findDeviceInOutPageBySource(SystemConstant.convertIdToLong(serviceUnitId),
                usageType, SystemConstant.convertIdToLong(userId), deviceStatus, inOutTimeStart, inOutTimeEnd, deviceNo, deviceSerialNo, customName, location, address, serialNo,
                pageNumber, pageSize));
    }

    @ApiOperation(value = "资源保障-设备保障-出入库登记查询-查询登记人列表")
    @RequestMapping(value = "/registrant_list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = SearchResult.class)})
    public Result findDeviceInOutPageBySource() {
        List<SearchResult> resultList = new ArrayList<>();
        List<Long> userIdList = tbDeviceInOutService.list(new QueryWrapper<TBDeviceInOut>()
                        .lambda()
                        .select(TBDeviceInOut::getUserId))
                .stream()
                .map(TBDeviceInOut::getUserId)
                .distinct()
                .collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(userIdList)) {
            resultList = sysUserService.list(new QueryWrapper<SysUser>()
                            .lambda()
                            .select(SysUser::getId, SysUser::getRealName)
                            .in(SysUser::getId, userIdList))
                    .stream()
                    .flatMap(e -> {
                        SearchResult searchResult = new SearchResult();
                        searchResult.setId(e.getId());
                        searchResult.setValue(e.getRealName());
                        return Stream.of(searchResult);
                    }).collect(Collectors.toList());
        }
        return ResultUtil.ok(resultList);
    }
}