package com.yiqi.admin.controller.core;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.common.annotation.Log;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.core.domain.BaseEntity;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.core.page.TableDataInfo;
import com.yiqi.common.enums.BusinessType;
import com.yiqi.common.enums.DeleteStatus;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.core.domain.GoodsInfo;
import com.yiqi.core.domain.GoodsSku;
import com.yiqi.core.domain.GoodsSkuSpec;
import com.yiqi.core.domain.dto.GoodsInfoDto;
import com.yiqi.core.domain.dto.GoodsInfoQueryByCommentDTO;
import com.yiqi.core.domain.dto.GoodsSkuQueryByCommentDTO;
import com.yiqi.core.domain.vo.GoodsInfoQueryVO;
import com.yiqi.core.domain.vo.GoodsSkuInfoByCommentVO;
import com.yiqi.core.service.IGoodsInfoService;
import com.yiqi.core.service.IGoodsSkuService;
import com.yiqi.core.service.IGoodsSkuSpecService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 商品管理Controller
 *
 * @author ruoyi
 * @date 2023-08-21
 */
@Api(tags = "管理后台 - 商品管理")
@RestController
@RequestMapping(UrlConstants.managerApi + "/core/goods")
public class GoodsInfoController extends BaseController {
    @Autowired
    private IGoodsInfoService goodsService;

    @Autowired
    private IGoodsSkuService goodsSkuService;

    @Autowired
    private IGoodsSkuSpecService goodsSkuSpecService;

    /**
     * 查询商品管理列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询商品管理列表")
    public TableDataInfo list(GoodsInfoQueryVO goodsInfoQueryVO) {
        startPage();
        goodsInfoQueryVO.setSourceType(SecurityUtils.getLoginUser().getSourceType());
        goodsInfoQueryVO.setTargetId(SecurityUtils.getLoginUser().getOrgId());
        List<GoodsInfoQueryVO> list = goodsService.selectGoodsList(goodsInfoQueryVO);
        return getDataTable(list);
    }

    /**
     * 导出商品管理列表
     */
    @PreAuthorize("@ss.hasPermi('goods:commonGoods:export')")
    @Log(title = "商品管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出商品管理列表")
    public void export(HttpServletResponse response, GoodsInfoQueryVO goodsInfoQueryVO) {
        List<GoodsInfoQueryVO> list = goodsService.selectGoodsList(goodsInfoQueryVO);
        ExcelUtil<GoodsInfoQueryVO> util = new ExcelUtil<>(GoodsInfoQueryVO.class);
        util.exportExcel(response, list, "商品管理数据");
    }

    /**
     * 获取商品管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('goods:commonGoods:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取商品管理详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(goodsService.selectGoodsById(id));
    }

    /**
     * 新增商品管理
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('goods:commonGoods:add')")
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增商品管理")
    public AjaxResult add(@RequestBody GoodsInfoDto goods) {
        return toAjax(goodsService.insertGoods(goods));
    }

    /**
     * 修改商品管理
     */
    @PreAuthorize("@ss.hasPermi('goods:commonGoods:edit')")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改商品管理")
    public AjaxResult edit(@RequestBody GoodsInfoDto goods) {
        return toAjax(goodsService.updateGoods(goods));
    }

    /**
     * 删除商品管理
     */
    @PreAuthorize("@ss.hasPermi('goods:commonGoods:remove')")
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除商品管理")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(goodsService.deleteGoodsByIds(ids));
    }

    /**
     * 修改商品管理状态
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('goods:commonGoods:edit')")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PostMapping(value = "updateStatus")
    @ApiOperation(value = "修改商品管理状态")
    public AjaxResult updateGoodsStatus(@RequestBody GoodsInfo goods) {
        return toAjax(goodsService.updateGoodsStatus(goods));
    }


    /**
     * 修改商品虚拟销量
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('goods:commonGoods:edit')")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/updateGoodsVirtualSellNum")
    @ApiOperation(value = "修改商品虚拟销量")
    public AjaxResult updateGoodsVirtualSellNum(@RequestParam("goodsId") Long goodsId,
                                                @RequestParam("virtualSellNum") Integer virtualSellNum) {
        return toAjax(goodsService.updateGoodsVirtualSellNum(goodsId, virtualSellNum));
    }

    /**
     * 评论-商品查询
     */
    @PostMapping(value = "selectGoodsByGoodsType2Comment")
    @ApiOperation(value = "评论-商品查询")
    public R<List<GoodsInfo>> selectGoodsByGoodsType2Comment(@RequestBody @Valid GoodsInfoQueryByCommentDTO goodsInfoQueryByCommentDTO) {
        return R.ok(goodsService.page(new Page<>(goodsInfoQueryByCommentDTO.getPageNum()
                        , goodsInfoQueryByCommentDTO.getPageSize())
                ,new QueryWrapper<GoodsInfo>().lambda()
                        .eq(GoodsInfo::getGoodsType, goodsInfoQueryByCommentDTO.getGoodsType())
                        .eq(GoodsInfo::getDelFlag, DeleteStatus.OK.getCode())
                        .eq(GoodsInfo::getStatus, DeleteStatus.OK.getCode())
                        .orderByDesc(BaseEntity::getCreateTime)).getRecords());
    }

    /**
     * 评论-商品物料查询
     */
    @PostMapping(value = "selectGoodsSkuByGoodsId2Comment")
    @ApiOperation(value = "评论-商品物料查询")
    public R<List<GoodsSku>> selectGoodsSkuByGoodsId2Comment(@RequestBody @Valid GoodsSkuQueryByCommentDTO goodsSkuQueryByCommentDTO) {
        List<GoodsSku> goodsSkuList = goodsSkuService.list(new QueryWrapper<GoodsSku>().lambda()
                .in(GoodsSku::getGoodsId, goodsSkuQueryByCommentDTO.getGoodsId())
                .eq(GoodsSku::getDelFlag, DeleteStatus.OK.getCode())
                .eq(GoodsSku::getStatus, DeleteStatus.OK.getCode()));
        for(GoodsSku goodsSku : goodsSkuList){
            List<String> specValLists = JSONUtil.toList(JSONUtil.parseArray(goodsSku.getSpecs()), String.class);
            if(CollUtil.isNotEmpty(specValLists)){
                goodsSku.setSkuValues(CollUtil.join(specValLists, " "));
            }else{
                goodsSku.setSkuValues("默认规格");
            }
        }
        return R.ok(goodsSkuList);
    }
}
