package org.springblade.modules.api.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.utils.DistanceUtils;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.business.entity.Facility;
import org.springblade.modules.business.service.IFacilityService;
import org.springblade.modules.business.service.IShopService;
import org.springblade.modules.business.vo.FacilityVO;
import org.springblade.modules.business.wrapper.FacilityWrapper;
import org.springblade.modules.system.service.IUserMerchantService;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping(CommonConstant.API_URL + "/facility")
@Api(value = "设备管理接口", tags = "设备管理接口")
public class ApiFacilityController extends BaseController {

    private final IFacilityService iFacilityService;
    private final IShopService iShopService;
    private final IUserMerchantService iUserMerchantService;

    @PostMapping("/save")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "添加设备", notes = "传入facility")
    public R<Void> save(@Valid @RequestBody Facility facility) {
        return R.status(iFacilityService.add(facility));
    }

    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "查询设备列表", notes = "传入facility")
    public R<IPage<FacilityVO>> list(Query query) {
        LambdaQueryWrapper<Facility> wrapper = Wrappers.lambdaQuery(Facility.class);
        if (isMerchant()) {
            List<Long> merchantShopIds = iShopService.getMerchantShopIds(AuthUtil.getUserId());
            if (CollUtil.isEmpty(merchantShopIds)) {
                return R.data(new Page<>());
            }
            wrapper.in(Facility::getShopId, merchantShopIds);
        } else {
            List<Long> authShopId = iUserMerchantService.getAuthShopId(AuthUtil.getUserId());
            if (CollUtil.isEmpty(authShopId)) {
                return R.data(new Page<>());
            }
            wrapper.in(Facility::getShopId, authShopId);
        }
        IPage<Facility> pages = iFacilityService.page(Condition.getPage(query), wrapper);
        return R.data(FacilityWrapper.build().pageVO(pages));
    }

    @PostMapping("/update")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "设备修改", notes = "传入facility")
    public R<FacilityVO> update(@Valid @RequestBody Facility facility) {
        Facility facilityInData = iFacilityService.getById(facility.getId());
        BeanUtil.copyProperties(facility, facilityInData);
        return R.status(iFacilityService.updateById(facilityInData));
    }

    @PostMapping("/details")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "设备详情", notes = "传入id")
    public R<FacilityVO> details(@ApiParam(value = "主键集合", required = true) @RequestParam Long facilityId) {
        Facility facility = iFacilityService.getById(facilityId);
        return R.data(FacilityWrapper.build().entityVO(facility));
    }

    @PostMapping("/delete")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "删除设备", notes = "传入ids")
    public R<Void> remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.status(iFacilityService.removeByIds(Func.toLongList(ids)));
    }

    /**
     * 小程序查询所有设备，并返回距离
     */
    @GetMapping("/all")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "小程序查询所有设备，并返回距离", notes = "经度纬度")
    public R<List<FacilityVO>> all(@ApiParam(value = "经度", required = true) @RequestParam Double longitude,
                                   @ApiParam(value = "纬度", required = true) @RequestParam Double latitude) {
        List<Facility> pages = iFacilityService.list(Wrappers.lambdaQuery(Facility.class).eq(Facility::getUseStatus, 1));
        List<FacilityVO> facilityVOS = FacilityWrapper.build().listVO(pages);
        for (FacilityVO facilityVO : facilityVOS) {
            facilityVO.setDistance(DistanceUtils.getDistance(longitude, latitude, Double.parseDouble(facilityVO.getLongitude()), Double.parseDouble(facilityVO.getLatitude())));
        }
        return R.data(facilityVOS);
    }

    /**
     * 获取商家所有未绑定设备
     */
    @GetMapping("/allMerchantFacility")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "获取商家所有未绑定设备", notes = "获取商家所有未绑定设备")
    public R<List<FacilityVO>> allMerchantFacility(@ApiParam(value = "门店id，编辑门店时必传") @RequestParam(required = false) Long shopId) {
        List<Facility> list = iFacilityService.lambdaQuery()
                .eq(Facility::getMerchantId, AuthUtil.getUserId())
                .and((item) -> item.eq(shopId != null, Facility::getShopId, shopId)
                        .or(item1 -> item1.eq(Facility::getShopId, shopId)))
                .eq(Facility::getIsDelete, 0)
                .list();
        return R.data(FacilityWrapper.build().listVO(list));
    }

}
