package com.fzm.mall.server.admin.goods_center.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fzm.mall.server.admin.annotation.AdminLog;
import com.fzm.mall.server.admin.constant.MALLGlobalConfig;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.distribution.model.Template;
import com.fzm.mall.server.admin.distribution.service.ITemplateService;
import com.fzm.mall.server.admin.enums.log.OperateModuleEnum;
import com.fzm.mall.server.admin.enums.log.OperateTypeEnum;
import com.fzm.mall.server.admin.enums.setting.GoodsConfigureEnum;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.goods_center.entity.dto.*;
import com.fzm.mall.server.admin.goods_center.entity.vo.*;
import com.fzm.mall.server.admin.goods_center.enums.status.SpuStatusEnum;
import com.fzm.mall.server.admin.goods_center.model.Spu;
import com.fzm.mall.server.admin.goods_center.service.IExternalTokenService;
import com.fzm.mall.server.admin.goods_center.service.ISkuService;
import com.fzm.mall.server.admin.goods_center.service.ISpuService;
import com.fzm.mall.server.admin.home_page.enums.type.AdminTypeEnum;
import com.fzm.mall.server.admin.home_page.model.Admin;
import com.fzm.mall.server.admin.home_page.model.Merchant;
import com.fzm.mall.server.admin.home_page.service.IAdminService;
import com.fzm.mall.server.admin.home_page.service.IMerchantService;
import com.fzm.mall.server.admin.repo.ResponseFactory;
import com.fzm.mall.server.admin.repo.ResponseVO;
import com.fzm.mall.server.admin.shop.entity.dto.ShopDTO;
import com.fzm.mall.server.admin.shop.service.IShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author wangp
 * @date 2021/3/4 16:06
 * @description 商品
 * @since JDK 1.8
 */
@Api(tags = "商品中心-商品")
@Validated
@RestController
@RequestMapping("/goods")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SpuController {

    private final IAdminService adminService;
    private final ISpuService spuService;
    private final ResponseFactory resFac;
    private final ITemplateService templateService;
    private final IMerchantService merchantService;
    private final IExternalTokenService externalTokenService;
    private final ISkuService skuService;
    private final IShopService shopService;

    //WAIT 商品评论--chart not create
    //BUG
    @ApiOperation(value = "新增")
    @AdminLog(description = "商品中心-新增商品", module = OperateModuleEnum.GOODS_CENTER, opType = OperateTypeEnum.ADD_GOODS)
    @PostMapping("/releaseGoods/add")
    public ResponseVO add(@RequestBody @Valid GoodsSpuDTO pDTO, @ApiParam(name = "adminId", value = "管理员id")
    @RequestHeader String adminId) {
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        Merchant merchant = merchantService.getByMerchantId(merchantId);
        if (merchant.getDelayDelivery().equals(GoodsConfigureEnum.IMMEDIATE_DELIVERY.status())
                && pDTO.getDelayDelivery().equals(GoodsConfigureEnum.DELAY_DELIVERY.status())) {
            return resFac.getResponse(MallResponseError.MERCHANT_NOT_DELAY_DELIVERY);
        }
        Spu spu = spuService.getByGoodsId(pDTO.getGoodsId());
        if (spu != null && !spu.getName().equals(pDTO.getName())) {
            return resFac.getResponse(MallResponseError.GOODS_NAME_EXIST);
        }
        /*Template template = templateService.getByMerchantId(merchantId);
        if (template == null) {
            return resFac.getResponse(MallResponseError.NULL_TEMPLATE);
        }*/
        ShopDTO shopDTO = shopService.readByMerchantId(merchantId);
        if (shopDTO == null) {
            return resFac.getResponse(MallResponseError.NULL_SHOP);
        }
        spuService.add(pDTO, merchantId, null, merchant.getTokenIssueAddr());
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "存为草稿")
    @PostMapping("/releaseGoods/draft")
    public ResponseVO draft(@RequestBody @Valid GoodsSpuDraftDTO pDTO, @ApiParam(name = "adminId", value = "管理员id")
    @RequestHeader String adminId) {
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        spuService.draft(pDTO, merchantId);
        return resFac.getSimpleSuccessResponse();
    }

    //BUG
    @ApiOperation(value = "编辑")
    @AdminLog(description = "商品中心-编辑商品", module = OperateModuleEnum.GOODS_CENTER, opType = OperateTypeEnum.EDIT_GOODS)
    @PutMapping("/goodsList/edit")
    public ResponseVO edit(@RequestBody @Valid GoodsEditDTO eDTO, @ApiParam(name = "adminId", value = "管理员id")
    @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        spuService.edit(eDTO, merchantId);
        return resFac.getSimpleSuccessResponse();
    }

    //BUG
    @ApiOperation(value = "重新发布")
    @PutMapping("/goodsList/republish")
    public ResponseVO republish(@RequestBody @Valid GoodsRepublishUpdateDTO dto, @ApiParam(name = "adminId", value = "管理员id")
    @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        spuService.republish(dto, merchantId);
        return resFac.getSimpleSuccessResponse();
    }

    //BUG
    @ApiOperation(value = "分页查询")
    @GetMapping("/goodsList/page")
    public ResponseVO pageGoods(
            @ApiParam(name = "goodsId", value = "商品编号")
            @RequestParam(required = false) String goodsId,
            @ApiParam(name = "goodsName", value = "商品名称")
            @RequestParam(required = false) String goodsName,
            @ApiParam(name = "status", value = "状态")
            @RequestParam(required = false) Integer status,
            @ApiParam(name = "addTimeHead", value = "开始时间")
            @RequestParam(required = false) Long addTimeHead,
            @ApiParam(name = "addTimeTail", value = "结束时间")
            @RequestParam(required = false) Long addTimeTail,
            @ApiParam(name = "goodsType", value = "商品类型")
            @RequestParam(required = false) Integer goodsType,
            @ApiParam(name = "pageNum", value = "当前页数")
            @RequestParam Integer pageNum,
            @ApiParam(name = "pageSize", value = "每页个数")
            @RequestParam Integer pageSize,
            @ApiParam(name = "adminId", value = "管理员id")
            @RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        IPage<GoodsSpuVO> page = spuService.page(admin.getMerchantId(), admin.getType(), goodsId, goodsName, status,
                addTimeHead, addTimeTail, goodsType, pageNum, pageSize);
        return resFac.getSuccessResponseWithData(page);
    }

    @ApiOperation(value = "分页查询-审核列表")
    @GetMapping("/goodsList/pagecheck")
    public ResponseVO pageCheck(
            @ApiParam(name = "goodsId", value = "商品编号")
            @RequestParam(required = false) String goodsId,
            @ApiParam(name = "goodsName", value = "商品名称")
            @RequestParam(required = false) String goodsName,
            @ApiParam(name = "addTimeHead", value = "开始时间")
            @RequestParam(required = false) Long addTimeHead,
            @ApiParam(name = "addTimeTail", value = "结束时间")
            @RequestParam(required = false) Long addTimeTail,
            @ApiParam(name = "goodsType", value = "商品类型")
            @RequestParam(required = false) Integer goodsType,
            @ApiParam(name = "pageNum", value = "当前页数")
            @RequestParam Integer pageNum,
            @ApiParam(name = "pageSize", value = "每页个数")
            @RequestParam Integer pageSize,
            @ApiParam(name = "adminId", value = "管理员id")
            @RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        IPage<GoodsSpuVO> page = spuService.page(admin.getMerchantId(), admin.getType(), goodsId, goodsName, SpuStatusEnum.WAIT_CHECK.getStatus(),
                addTimeHead, addTimeTail, goodsType, pageNum, pageSize);
        return resFac.getSuccessResponseWithData(page);
    }

    //BUG
    @ApiOperation(value = "详情")
    @GetMapping("/goodsList/detail")
    public ResponseVO detailGoods(@ApiParam(name = "goodsId", value = "商品id") @RequestParam String goodsId) {
        GoodsSpuDetailVO detailVO = spuService.getVoByGoodsId(goodsId);
        return resFac.getSuccessResponseWithData(detailVO);
    }

    //TODO 商户下架联动
    //BUG
    @ApiOperation(value = "上下架")
    @AdminLog(description = "商品中心-上下架", module = OperateModuleEnum.GOODS_CENTER, opType = OperateTypeEnum.ON_OFF)
    @PutMapping("/goodsList/onOff")
    public ResponseVO onOffGoods(@RequestBody OnOffDTO onOffDTO, @ApiParam(name = "adminId", value = "管理员id")
    @RequestHeader String adminId) {
        String goodsId = onOffDTO.getGoodsId();
        Integer type = onOffDTO.getType();
        String merchantId1 = adminService.getByAdminId(adminId).getMerchantId();
        String merchantId2 = spuService.getByGoodsId(goodsId).getMerchantId();
        if (merchantId1.equals(MALLGlobalConfig.PLATFORM_MERCHANT_ID)) {
            if (type.equals(SpuStatusEnum.ON.getStatus())) {
                return resFac.getResponse(MallResponseError.NO_AUTH_ERROR);
            }
        } else {
            if (!merchantId1.equals(merchantId2)) {
                return resFac.getResponse(MallResponseError.NO_AUTH_ERROR);
            }
        }
        spuService.offGoods(goodsId, type);
        return resFac.getSimpleSuccessResponse();
    }

    //BUG
    @ApiOperation(value = "取消审核")
    @AdminLog(description = "商品中心-取消审核", module = OperateModuleEnum.GOODS_CENTER, opType = OperateTypeEnum.DEFAULT_FIRST)
    @PutMapping("/goodsList/cancelCheck/{goodsId}")
    public ResponseVO cancel(@PathVariable String goodsId, @ApiParam(name = "adminId", value = "管理员id")
    @RequestHeader String adminId) {
        adminService.adminAuthCheck(adminId, AdminTypeEnum.MERCHANT.getType());
        String merchantId1 = adminService.getByAdminId(adminId).getMerchantId();
        String merchantId2 = spuService.getByGoodsId(goodsId).getMerchantId();
        if (!merchantId1.equals(merchantId2)) {
            return resFac.getResponse(MallResponseError.NO_AUTH_ERROR);
        }
        spuService.cancel(goodsId);
        return resFac.getSimpleSuccessResponse();
    }

    //TODO 什么情况下删除
    //BUG
    @ApiOperation(value = "批量删除")
    @AdminLog(description = "商品中心-批量删除", module = OperateModuleEnum.GOODS_CENTER, opType = OperateTypeEnum.DEFAULT_FIRST)
    @DeleteMapping("/goodsList/deleteBatch")
    public ResponseVO deleteGoodsBatch(@RequestBody List<String> goodsIds, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        spuService.deleteBatch(goodsIds, merchantId);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "审核")
    @AdminLog(description = "商品中心-审核", module = OperateModuleEnum.GOODS_CENTER, opType = OperateTypeEnum.GOODS_CHECK)
    @PutMapping("/goodsList/check")
    public ResponseVO check(@RequestBody @Valid GoodsCheckDTO checkDTO, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        spuService.goodsCheck(checkDTO);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "批量审核")
    @AdminLog(description = "商品中心-批量审核", module = OperateModuleEnum.GOODS_CENTER, opType = OperateTypeEnum.DEFAULT_FIRST)
    @PutMapping("/goodsList/checkBatch")
    public ResponseVO checkBatch(@RequestBody @Valid List<GoodsCheckDTO> checkDTOList, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        spuService.goodsCheckBatch(checkDTOList);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "根据商品编号或名称查询商品信息")
    @GetMapping("/goodsList/queryByNameOrId")
    public ResponseVO queryByNameOrId(
            @ApiParam(name = "goods", value = "商品编号或名称")
            @RequestParam(required = false) String goods,
            @ApiParam(name = "adminId", value = "管理员id")
            @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        List<GoodsListVO> vos = spuService.queryByNameOrId(merchantId, goods);
        return resFac.getSuccessResponseWithData(vos);
    }

    //BUG
    @ApiOperation(value = "获取商户前缀")
    @GetMapping("/merchantPrefix")
    public ResponseVO merchantPrefix(@RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        Admin admin = adminService.getByAdminId(adminId);
        Merchant merchant = merchantService.getByMerchantId(admin.getMerchantId());
        return resFac.getSuccessResponseWithData(merchant.getPrefix());
    }


    /*@ApiOperation(value = "根据类目查询对应商户商品")
    @PutMapping("/goodsList/queryByCategory")
    public ResponseVO queryByCategory(
            @ApiParam(name = "goods", value = "商品编号或名称")
            @RequestParam(required = false) String goods,
            @ApiParam(name = "categoryIds", value = "类目id")
            @RequestBody List<String> categoryIds,
            @ApiParam(name = "adminId", value = "管理员id")
            @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        List<GoodsListVO> vos = spuService.queryByCategory(categoryIds, merchantId, goods);
        return resFac.getSuccessResponseWithData(vos);
    }*/

    //BUG
    @ApiOperation(value = "获取外部未绑定token")
    @GetMapping("/unbindToken")
    public ResponseVO unbindToken(@RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        List<ExternalTokenListVO> externalTokenList = externalTokenService.unbindToken(admin.getMerchantId());
        return resFac.getSuccessResponseWithData(externalTokenList);
    }


    @ApiOperation(value = "商户是否允许延后提货")
    @GetMapping("/releaseGoods/merchantDelayDelivery")
    public ResponseVO merchantDelayDelivery(@RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        Merchant merchant = merchantService.getByMerchantId(admin.getMerchantId());
        return resFac.getSuccessResponseWithData(merchant.getDelayDelivery());
    }

    @ApiOperation(value = "打包商品-根据商品编号或名称获取商品信息")
    @GetMapping("/releaseGoods/spugetbyvague")
    public ResponseVO getSpuByVague(@RequestParam String goodsInfo, @RequestHeader String adminId) {
        System.err.println("dto:" + goodsInfo + "admin:" + adminId);
        Admin admin = adminService.getByAdminId(adminId);
        List<GoodsListVO> spuByVague = spuService.getSpuByVague(goodsInfo, admin.getMerchantId());
        return resFac.getSuccessResponseWithData(spuByVague);
    }

    @ApiOperation(value = "打包商品-根据商品编号获取商品规格")
    @GetMapping("/releaseGoods/skugetbygoodsId")
    public ResponseVO getSkuByGoodsId(@RequestParam String goodsId) {
        List<GoodsPackageSkuVO> list = skuService.getSkuByGoodsIdForPackage(goodsId);
        return resFac.getSuccessResponseWithData(list);
    }

    @ApiOperation(value = "查询是否已建模板或店铺")
    @GetMapping("/releaseGoods/templateorshopquery")
    public ResponseVO queryTemplateOrShop(@RequestHeader String adminId) {
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        /*Template template = templateService.getByMerchantId(merchantId);
        if (template == null) {
            return resFac.getResponse(MallResponseError.NULL_TEMPLATE);
        }*/
        ShopDTO shopDTO = shopService.readByMerchantId(merchantId);
        if (shopDTO == null) {
            return resFac.getResponse(MallResponseError.NULL_SHOP);
        }
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "查询外部nft")
    @GetMapping("/releaseGoods/externnftlist")
    public ResponseVO externNftList(@RequestHeader String adminId) {
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        List<ExternNFTVO> externNFTVOS = externalTokenService.queryByMerchantId(merchantId);
        return resFac.getSuccessResponseWithData(externNFTVOS);
    }

    @ApiOperation(value = "查询外部nft")
    @GetMapping("/releaseGoods/tesssss")
    public ResponseVO tesssss(@RequestParam Integer t) {
        if (t.equals(1)) {
            int i = 1 / 0;
        } else {
            throw new MyException(MallResponseError.NO_AUTH_ERROR);
        }
        return resFac.getSimpleSuccessResponse();
    }

}
