package org.springblade.modules.api.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.enums.GrouponSourceEnum;
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.modules.api.response.GroupStatisResponse;
import org.springblade.modules.distribution.entity.Appoint;
import org.springblade.modules.distribution.service.IAppointService;
import org.springblade.modules.distribution.vo.AppointVO;
import org.springblade.modules.distribution.wrapper.AppointWrapper;
import org.springblade.modules.finance.entity.AppointGoods;
import org.springblade.modules.finance.service.IAppointGoodsService;
import org.springblade.modules.groupon.entity.UserSelfTake;
import org.springblade.modules.groupon.service.IGrouponGoodsService;
import org.springblade.modules.groupon.service.IGrouponService;
import org.springblade.modules.groupon.service.ISelfTakeService;
import org.springblade.modules.groupon.service.IUserSelfTakeService;
import org.springblade.modules.groupon.vo.GrouponVO;
import org.springblade.modules.groupon.vo.SelfTakeVO;
import org.springblade.modules.mall.service.IGoodsInfoService;
import org.springblade.modules.platform.service.UserAppService;
import org.springblade.modules.system.entity.UserApp;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Author pangqijun
 * Date 2023/6/2
 * Description
 */
@RestController
@RequestMapping(CommonConstant.API_URL)
@Api(value = "团购接口", tags = "04.团购接口")
public class ApiGrouponController {

    @Resource
    private IGrouponService grouponService;
    @Resource
    private IGoodsInfoService goodsInfoService;
    @Resource
    private UserAppService userAppService;
    @Resource
    private ISelfTakeService selfTakeService;
    @Resource
    private IUserSelfTakeService userSelfTakeService;
    @Resource
    private IAppointService appointService;
    @Resource
    private IAppointGoodsService appointGoodsService;
    @Resource
    private IGrouponGoodsService grouponGoodsService;

    @GetMapping("/groupon/latest")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "查询最新团购列表")
    public R<IPage<GrouponVO>> latestGroupon(@ApiParam("地址") String address, @ApiParam("经度") Double longitude,
                                             @ApiParam("纬度") Double latitude, Query query) {
        return R.data(grouponService.latestGroupon(this.analysisAddress(address), longitude, latitude, Condition.getPage(query)));
    }

    @GetMapping("/groupon/history")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "查询历史团购数据")
    public R<IPage<GrouponVO>> historyGroupon(@ApiParam("地址") String address, @ApiParam("经度") Double longitude,
                                              @ApiParam("纬度") Double latitude, Query query) {
        return R.data(grouponService.historyGroupon(this.analysisAddress(address), longitude, latitude, Condition.getPage(query)));
    }

    @GetMapping("/groupon/detail")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "团购详情")
    public R<GrouponVO> detailGroupon(@RequestParam("grouponId") Long grouponId) {
        return R.data(grouponService.detail(grouponId));
    }

    @PostMapping("/groupon/publish")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "发布团购", notes = "传入groupon")
    public R publishGroupon(@Valid @RequestBody GrouponVO groupon) {
        Assert.notBlank(groupon.getMainTitle(), "主标题不能为空");
        Assert.notBlank(groupon.getSubTitle(), "副标题不能为空");
        // 判断当前用户是否有团长的角色
        UserApp userApp = userAppService.getByUserId(AuthUtil.getUserId());
        if (userApp.getLivingHall() != 1) {
            return R.fail("抱歉，您不是团长，不能发起团购");
        }
        groupon.setOrganizerUserId(AuthUtil.getUserId());
        groupon.setSource(GrouponSourceEnum.USER.getValue());
        grouponService.publishGroupon(groupon);
        return R.status(true);
    }

    @GetMapping("/self-take/list")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "查询自提点")
    public R<List<SelfTakeVO>> getSelfTakeByGrouponId(@ApiParam("地址") String address, @ApiParam("经度") Double longitude,
                                                      @ApiParam("纬度") Double latitude,
                                                      @ApiParam("团购Id") Long grouponId) {
        return R.data(selfTakeService.getSelfTakeByGrouponId(this.analysisAddress(address), longitude, latitude, grouponId));
    }

    @PostMapping("appointList")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "团长相关履约单列表")
    public R<List<AppointVO>> appointList(@RequestBody  Query query, @RequestParam(value = "type") Integer type){
        UserSelfTake userSelfTake = userSelfTakeService.getOne(Wrappers.lambdaQuery(UserSelfTake.class).eq(UserSelfTake::getUserId, AuthUtil.getUserId()));
        LambdaQueryWrapper<Appoint> wrapper = Wrappers.lambdaQuery(Appoint.class).eq(Appoint::getTakeId, userSelfTake.getSelfTakeId());
        if(!type.equals(0)){
            wrapper.eq(Appoint::getState, type-1);
        }
        IPage<Appoint> pages = appointService.page(Condition.getPage(query), wrapper);
        List<AppointVO> appointVOS = AppointWrapper.build().listVO(pages.getRecords());
        if (appointVOS.size()<=0){
            return R.data(appointVOS);
        }
        List<String> codeList = appointVOS.stream().map(Appoint::getArrivalCode).collect(Collectors.toList());
        List<AppointGoods> list = appointGoodsService.list(Wrappers.lambdaQuery(AppointGoods.class).in(AppointGoods::getArrivalCode, codeList));
        Map<String, List<AppointGoods>> collect = list.stream().collect(Collectors.groupingBy(AppointGoods::getArrivalCode));
        for (AppointVO appointVO : appointVOS) {
            appointVO.setAppointGoodsList(collect.get(appointVO.getArrivalCode()));
        }
        return R.data(appointVOS);
    }

    @PostMapping("commitAppoint")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "到货核销")
    public R commitAppoint(@ApiParam("履约单id") Long appointId){
        appointService.commitAppoint(appointId);
        return R.success("核销成功");
    }

    @GetMapping("/groupon/statis")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "查询团购统计")
    public R<GroupStatisResponse> groupStatistics() {
        GroupStatisResponse result = grouponService.groupStatistics(AuthUtil.getUserId());
        return R.data(result);
    }

    @GetMapping("/groupon-mng/list")
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "查询团购管理列表")
    public R<IPage<GrouponVO>> grouponMngList(@ApiParam("state") Integer state, Query query) {
        return R.data(grouponService.grouponMngList(Condition.getPage(query), AuthUtil.getUserId(), state));
    }

    @GetMapping("/groupon-mng/detail")
    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "查询团购管理列表详情")
    public R<GrouponVO> grouponMngDetail(@ApiParam("拼团ID") Long groupId) {
        return R.data(grouponService.grouponMngDetail(groupId));
    }

    private String analysisAddress(String address) {
        if (StrUtil.isNotBlank(address)) {
            if (address.contains("市")) {
                int index = address.indexOf("市");
                return address.substring(0, index + 1);
            } else {
                if (address.length() > 8) {
                    return address.substring(0, 7);
                }
                return address;
            }
        }
        return address;
    }

}
