package com.huimv.receive.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.huimv.receive.common.token.TokenSign;
import com.huimv.receive.common.utils.Result;
import com.huimv.receive.common.utils.ResultCode;
import com.huimv.receive.common.utils.ResultUtil;
import com.huimv.receive.entity.BaseVisiting;
import com.huimv.receive.entity.BaseWashoutPoint;
import com.huimv.receive.service.IBaseVisitingService;
import com.huimv.receive.service.IBaseWashoutPointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-03-06
 */
@RestController
@RequestMapping("/base-visiting")
@CrossOrigin
public class BaseVisitingController {

    @Autowired
    private IBaseVisitingService baseVisitingService;
    @Autowired
    private IBaseWashoutPointService baseWashoutPointService;

    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(HttpServletRequest httpServletRequest, @RequestBody BaseVisiting baseVisiting){
        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        if (baseVisitingService.count(new QueryWrapper<BaseVisiting>().lambda()
                .eq(BaseVisiting::getVisitingName,baseVisiting.getVisitingName())
                .ne(ObjectUtil.isNotNull(baseVisiting.getId()),BaseVisiting::getId,baseVisiting.getId())
                .eq(BaseVisiting::getFarmId,baseVisiting.getFarmId())) > 0) {
            return new Result(10001,"来访类型已存在!",false);
        }
        baseVisiting.setCreateUser(userId);
        baseVisiting.setCreateTime(LocalDateTime.now());
        return ResultUtil.booleanResult(baseVisitingService.saveOrUpdate(baseVisiting));
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id){
        if (baseWashoutPointService.count(new QueryWrapper<BaseWashoutPoint>().lambda().eq(BaseWashoutPoint::getVisitingType,id)) > 0) {
            return new Result(10001,"请先删除该来访类型相关洗消点!",false);
        }
        return baseVisitingService.delete(id);
    }

    @PostMapping("/list")
    public Result list(@RequestBody Integer farmId){
        return new Result(ResultCode.SUCCESS,baseVisitingService.list(new QueryWrapper<BaseVisiting>().lambda().eq(BaseVisiting::getFarmId,farmId)));
    }


}
