package com.fzm.mall.server.front.asset.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzm.mall.server.front.asset.model.dto.UserAssetTransferSaveDTO;
import com.fzm.mall.server.front.asset.model.dto.UserAssetTransferUpdateDTO;
import com.fzm.mall.server.front.asset.model.vo.GoodsTransVO;
import com.fzm.mall.server.front.asset.model.vo.UserAssetTransferVO;
import com.fzm.mall.server.front.asset.service.ITranService;
import com.fzm.mall.server.front.asset.service.IUserAssetService;
import com.fzm.mall.server.front.base.PageVO;
import com.fzm.mall.server.front.base.ResponseVO;
import com.fzm.mall.server.front.constant.MallResponseEnum;
import com.fzm.mall.server.front.goods.model.Category;
import com.fzm.mall.server.front.goods.model.vo.GoodsViewVo;
import com.fzm.mall.server.front.goods.model.vo.SaleHotVo;
import com.fzm.mall.server.front.goods.model.vo.SearchVo;
import com.fzm.mall.server.front.goods.service.ICategoryService;
import com.fzm.mall.server.front.goods.service.ICountService;
import com.fzm.mall.server.front.goods.service.ISpuService;
import com.fzm.mall.server.front.repo.ResponseFactory;
import com.fzm.mall.server.front.user.model.Header;
import com.fzm.mall.server.front.user.service.IRedisService;
import com.fzm.mall.server.front.util.IdUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fzm
 * @since 2021-09-07
 */
@Api(tags = "商品转让市场接口", description = "商品转让市场，列表等")
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping(value = "/mall/tran", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TranController {
    private final ICountService countService;
    private final ITranService tranService;
    private final ResponseFactory resFac;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private ISpuService spuService;

    @ApiOperation(value = "查询前十的值得买商品")
    @PostMapping("/without/getTopTenSaleHotVo")
    public ResponseVO<GoodsViewVo> getTopTenSaleHotVo(@RequestBody PageVO pageVo) {
        List<SaleHotVo> saleHotVos = countService.getTopTenSaleHotVo(pageVo);
        int count = pageVo.getSize();
        GoodsViewVo goodsViewVo = new GoodsViewVo();
        goodsViewVo.setList(saleHotVos);
        goodsViewVo.setTotal(count);
        return new ResponseVO<>(MallResponseEnum.SUCCESS, goodsViewVo);
    }

    @ApiOperation(value = "查询转让交易市场商品搜索")
    @PostMapping("/without/getTranGoods")
    public ResponseVO getTranGoods(@RequestBody SearchVo searchVo) {
        Page<GoodsTransVO> page = new Page<>();
        String searchKey = searchVo.getSearchKey();
        long pageSize = searchVo.getSize();
        long pageNum = searchVo.getPage();
        if (ObjectUtils.isNotEmpty(pageSize) && ObjectUtils.isNotEmpty(pageNum)) {
            page.setSize(pageSize);
            page.setCurrent(pageNum);
        }
        String categoryId = searchVo.getCategoryId();
        List<String> cateGoryIdsAll = new ArrayList<>();
        List<String> gids = new ArrayList<>();
        String gidStr = "";
        String sale = "";
        String price = "";
        searchVo.getSale();
        if (StringUtil.isNullOrEmpty(searchVo.getSale())) {
            sale = "desc";
        } else {
            sale = searchVo.getSale();
        }
        if (StringUtil.isNullOrEmpty(searchVo.getPrice())) {
            price = "desc";
        } else {
            price = searchVo.getPrice();
        }
        if (!StringUtil.isNullOrEmpty(categoryId)) {
            List<Category> categorys = categoryService.getList(categoryId);
            if (CollectionUtils.isEmpty(categorys)) {
                //只有当前一级
                cateGoryIdsAll.add(categoryId);
            } else {
                List<String> categoryIds = categorys.stream().distinct().map(Category::getCategoryId).collect(Collectors.toList());
                //下面有子集
                cateGoryIdsAll = categoryService.getCateGoryIdsList(categoryIds, categoryIds);
            }
            String categoryIdsStr = IdUtil.listToString(cateGoryIdsAll, ',');
            gids = spuService.getGidsByCategoryId(categoryIdsStr);
            gidStr = IdUtil.listToString(gids, ',');
        }
        IPage<GoodsTransVO> result = tranService.pageSerach(page, searchKey, gidStr,price,sale);
        return new ResponseVO<>(MallResponseEnum.SUCCESS, result);
    }

    @ApiOperation(value = "转让-新增")
    @ApiOperationSupport(order = 1)
    @PostMapping("/save")
    public ResponseVO save(@Ignore @RequestAttribute Header header, @RequestBody @Valid UserAssetTransferSaveDTO saveDTO) {
        saveDTO.setUid(header.getUid());
        tranService.save(saveDTO);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "转让-修改价格")
    @ApiOperationSupport(order = 2)
    @PostMapping("/update")
    public ResponseVO update(@RequestBody @Valid UserAssetTransferUpdateDTO updateDTO) {

        Long updateTime = tranService.update(updateDTO);
        return resFac.getSuccessResponseWithData(updateTime);
    }

    @ApiOperation(value = "转让-撤销")
    @ApiOperationSupport(order = 3)
    @PostMapping("/cancle/{tranId}")
    public ResponseVO cancle(@Ignore @RequestAttribute Header header,
                             @ApiParam(value = "transferId", required = true) @PathVariable(value = "tranId") String tranId) {
        try {
            tranService.cancle(header.getUid(), tranId);
        } catch (Exception e) {
            if ("record_exist".equals(e.getMessage())) {
                return new ResponseVO(MallResponseEnum.TRAN_CANCLE_FAIL);
            } else {
                throw e;
            }
        }
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "转让-主键查询")
    @ApiOperationSupport(order = 4)
    @PostMapping("/without/{tranId}")
    public ResponseVO read(
            @ApiParam(value = "transferId", required = true) @PathVariable(value = "tranId") String tranId) {
        UserAssetTransferVO result = tranService.read(tranId);
        return resFac.getSuccessResponseWithData(result);
    }

    @ApiOperation(value = "转让-列表查询")
    @ApiOperationSupport(order = 5)
    @PostMapping("/list")
    public ResponseVO list(@Ignore @RequestAttribute Header header,
                           @ApiParam(value = "商品名称或通证名称") @RequestParam(required = false) String keyword,
                           @ApiParam(value = "每页条数") @RequestParam(required = false) Long size,
                           @ApiParam(value = "页码") @RequestParam(required = false) Long page) {
        Page<UserAssetTransferVO> iPage = new Page<>();
        if (ObjectUtils.isNotEmpty(size) && ObjectUtils.isNotEmpty(page)) {
            iPage.setSize(size);
            iPage.setCurrent(page);
        }

        IPage<UserAssetTransferVO> result = tranService.page(iPage, header.getUid(), keyword);
        return resFac.getSuccessResponseWithData(result);
    }

}
