package com.wms.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.constants.enums.ResponseCode;
import com.wms.entity.app.ResponseEntity;
import com.wms.entity.app.dto.PageDto;
import com.wms.entity.app.request.TaskRecordQuery;
import com.wms.entity.app.vo.TaskRecordVO;
import com.wms.entity.table.TaskRecord;
import com.wms.service.TaskRecordService;
import com.wms.utils.HttpUtils;
import com.wms.utils.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import static com.wms.constants.WmsConstants.MYSQL_JSON_CI;
import static com.wms.utils.StringUtils.convertJsonString;

/**
 * WMS记录控制类
 *
 * @author 梁州
 */
@Controller
@CrossOrigin
@RequestMapping(value = "/wms/record")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RecordController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 任务记录服务
     */
    private final TaskRecordService taskRecordService;
    /**
     * 请求头部信息
     */
    private final HttpServletRequest servletRequest;

    /**
     * 查找所有物料
     */
    @PostMapping("/getTaskRecordByPage")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public String getGoodsInfoByPage(@RequestBody TaskRecordQuery taskRecordQuery){
        logger.info("接收到查询任务记录请求：{}，请求ip：{}", convertJsonString(taskRecordQuery), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            Page<TaskRecord> page = taskRecordQuery.toMpPage();
            //更新条件
            LambdaQueryWrapper<TaskRecord> lambdaQueryWrapper = new LambdaQueryWrapper<TaskRecord>()
                    .eq(taskRecordQuery.getTaskType() != null, TaskRecord::getTaskType, taskRecordQuery.getTaskType())
                    .like(StringUtils.isNotEmpty(taskRecordQuery.getVehicleId()), TaskRecord::getVehicleId, taskRecordQuery.getVehicleId())
                    .apply(StringUtils.isNotEmpty(taskRecordQuery.getGoodsId()), "goods_related ->> '$.goodsId' like concat('%', {0}, '%')" + MYSQL_JSON_CI, taskRecordQuery.getGoodsId())
                    .apply(StringUtils.isNotEmpty(taskRecordQuery.getGoodsName()), "goods_related ->> '$.goodsName' like concat('%', {0}, '%')" + MYSQL_JSON_CI, taskRecordQuery.getGoodsName());
            Page<TaskRecord> taskRecordPage = taskRecordService.page(page, lambdaQueryWrapper);
            // 生成数据
            PageDto<TaskRecordVO> pageDto = PageDto.of(taskRecordPage, records -> BeanUtil.copyProperties(records, TaskRecordVO.class));
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询成功");
            response.setReturnData(pageDto);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询物料信息发生异常");
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询物料发生异常");
            return convertJsonString(response);
        }
    }
}
