package com.huimv.receive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.receive.common.utils.Result;
import com.huimv.receive.common.utils.ResultUtil;
import com.huimv.receive.entity.BaseLocation;
import com.huimv.receive.entity.Farm;
import com.huimv.receive.mapper.BaseLocationMapper;
import com.huimv.receive.mapper.FarmMapper;
import com.huimv.receive.service.IBaseLocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-07-21
 */
@Service
public class BaseLocationServiceImpl extends ServiceImpl<BaseLocationMapper, BaseLocation> implements IBaseLocationService {

    @Autowired
    private FarmMapper farmMapper;
    @Autowired
    private BaseLocationMapper baseLocationMapper;

    @Override
    public Result add(HttpServletRequest httpServletRequest, BaseLocation baseLocation) {
        String[] farmIds = baseLocation.getFarmIds().split(",");
        for (String farmId : farmIds) {
            int locationCount = baseLocationMapper.countLocation(baseLocation.getLocationName(),farmId);
            if (locationCount > 0){
                Farm farm = farmMapper.selectById(farmId);
                return new Result(10001,farm.getFarmName()+"存在相同地点!",false);
            }
        }
        return ResultUtil.addResult(baseLocationMapper.insert(baseLocation));
    }

    @Override
    public Result delete(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String id = paramsMap.get("id");
        return ResultUtil.deleteResult(baseLocationMapper.deleteById(id));
    }

    @Override
    public Result edit(HttpServletRequest httpServletRequest, BaseLocation baseLocation) {
        String[] farmIds = baseLocation.getFarmIds().split(",");
        for (String farmId : farmIds) {
            int locationCount = baseLocationMapper.selectCount(new QueryWrapper<BaseLocation>().lambda()
                    .ne(BaseLocation::getId,baseLocation.getId()).like(BaseLocation::getFarmIds,farmId).eq(BaseLocation::getLocationName,baseLocation.getLocationName()));
            if (locationCount > 0){
                Farm farm = farmMapper.selectById(farmId);
                return new Result(10001,farm.getFarmName()+"存在相同地点!",false);
            }
        }
        return ResultUtil.updateResult(baseLocationMapper.updateById(baseLocation));
    }
}
