package org.springblade.modules.api.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
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 org.springblade.common.constant.CommonConstant;
import org.springblade.common.utils.DistanceUtils;
import org.springblade.core.log.exception.ServiceException;
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.api.request.AddFacilityReq;
import org.springblade.modules.api.request.UpdateFacilityReq;
import org.springblade.modules.business.entity.Facility;
import org.springblade.modules.business.entity.FacilityModel;
import org.springblade.modules.business.service.IFacilityModelService;
import org.springblade.modules.business.service.IFacilityService;
import org.springblade.modules.business.service.IShopService;
import org.springblade.modules.business.vo.FacilityModelVO;
import org.springblade.modules.business.vo.FacilityVO;
import org.springblade.modules.business.wrapper.FacilityModelWrapper;
import org.springblade.modules.business.wrapper.FacilityWrapper;
import org.springblade.modules.system.service.IUserMerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

    @Autowired
    private  IFacilityService iFacilityService;
    @Autowired
    private  IFacilityModelService iFacilityModelService;
    @Autowired
    private  IShopService iShopService;
    @Autowired
    private  IUserMerchantService iUserMerchantService;
    @Autowired
    private  IFacilityModelService facilityModelService;

    @Value("${qrCode.domainUrl}")
    private String domainUrl;

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

    /**
     * 分页 设备型号表
     */
    @GetMapping("/modelList")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "设备型号分页", notes = "传入facilityModel")
    public R<IPage<FacilityModelVO>> modelList(FacilityModel facilityModel, Query query) {
        IPage<FacilityModel> pages = facilityModelService.page(Condition.getPage(query), Condition.getQueryWrapper(facilityModel));
        return R.data(FacilityModelWrapper.build().pageVO(pages));
    }

    /**
     * 添加设备-商家端
     *
     * @param req
     * @return
     */
    @PostMapping("/appAdd")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "添加设备", notes = "传入facility")
    public R<Void> appAdd(@Valid @RequestBody AddFacilityReq req) {
        Facility facility = new Facility();
        BeanUtil.copyProperties(req, facility);
        facility.setUseStatus(1);
        facility.setFacilityStatus(1);

        if (isMerchant()) {//所属商家
            facility.setMerchantId(AuthUtil.getUserId());
        } else {
            throw new ServiceException("非法操作！");
        }
        return R.status(iFacilityService.add(facility));
    }

    @PostMapping("/appUpdate")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "更新设备", notes = "传入facility")
    public R<Void> appUpdate(@Valid @RequestBody UpdateFacilityReq req) {
        if (!isMerchant()) {//所属商家
            throw new ServiceException("非法操作！");
        }

        Facility facility = iFacilityService.getById(req.getId());
        BeanUtil.copyProperties(req, facility);
        return R.status(iFacilityService.updateById(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);

        //补充设备图片
        if (CollectionUtil.isNotEmpty(pages.getRecords())) {
            //获取所有设备型号
            List<Long> facilityTypeIds = pages.getRecords().stream().map(Facility::getFacilityType).distinct().collect(Collectors.toList());
            //查询设备型号图片
            List<FacilityModel> facilityModels = iFacilityModelService.lambdaQuery().in(FacilityModel::getId, facilityTypeIds).list();
            //按型号分组
            Map<Long, String> facilityModelMap = facilityModels.stream().collect(Collectors.toMap(FacilityModel::getId, FacilityModel::getFacilityImage));
            pages.getRecords().forEach(facility -> {
                facility.setFacilityImage(facilityModelMap.get(facility.getFacilityType()));
            });

            pages.getRecords().forEach(facilityVO -> {
                facilityVO.setQrCode(domainUrl + "?merchantCode=" + facilityVO.getId());
            });
        }

        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.isNull(Facility::getShopId)))
                .eq(Facility::getIsDelete, 0)
                .list();
        return R.data(FacilityWrapper.build().listVO(list));
    }

    @GetMapping("/buildQrcode")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "下载设备码", notes = "下载设备码")
    public void buildQrcode(HttpServletResponse response, String id) throws IOException {
        OutputStream osOut = response.getOutputStream();
        QrConfig qrConfig = new QrConfig();
        qrConfig.setWidth(600);
        qrConfig.setHeight(600);
        QrCodeUtil.generate(domainUrl + "?merchantCode=" + id,qrConfig, "jpg", osOut);
        osOut.close();
    }

}
