package com.slodon.b2b2c.controller.goods.admin;

import com.slodon.b2b2c.aop.OperationLogger;
import com.slodon.b2b2c.core.constant.*;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.goods.dto.GoodsAuditDTO;
import com.slodon.b2b2c.goods.dto.GoodsLookUpDTO;
import com.slodon.b2b2c.goods.example.*;
import com.slodon.b2b2c.goods.pojo.*;
import com.slodon.b2b2c.member.example.GoodsAnnexExample;
import com.slodon.b2b2c.model.goods.*;
import com.slodon.b2b2c.model.seller.StoreLabelBindGoodsModel;
import com.slodon.b2b2c.model.seller.VendorModel;
import com.slodon.b2b2c.seller.example.StoreLabelBindGoodsExample;
import com.slodon.b2b2c.seller.example.VendorExample;
import com.slodon.b2b2c.seller.pojo.StoreLabelBindGoods;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.vo.goods.GoodsVO;
import com.slodon.b2b2c.vo.goods.ProductVO;
import com.slodon.b2b2c.vo.goods.SellerGoodsDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "admin-商品管理")
@RestController
@RequestMapping("v3/goods/admin/goods")
public class GoodsController extends BaseController {

    @Resource
    private GoodsModel goodsModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private GoodsExtendModel goodsExtendModel;
    @Resource
    private GoodsBindLabelModel goodsBindLabelModel;
    @Resource
    private GoodsPictureModel goodsPictureModel;
    @Resource
    private GoodsBindReserveNameModel goodsBindReserveNameModel;
    @Resource
    private StoreLabelBindGoodsModel storeLabelBindGoodsModel;
    @Resource
    private GoodsRelatedTemplateModel goodsRelatedTemplateModel;
    @Resource
    private RedisTemplate<String, Object> objectRedisTemplate;

    @Resource
    private GoodsAnnexModel goodsAnnexModel;

    @Resource
    private VendorModel vendorModel;



    @ApiOperation("获取商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", paramType = "query"),
            @ApiImplicitParam(name = "storeName", value = "店铺名称", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态:2-待审核商品；3-在售商品；4-仓库中商品；6-违规下架商品", paramType = "query"),
            @ApiImplicitParam(name = "auditState", value = "审核状态：2-待审核；4-审核拒绝(待审核商品查询使用)", paramType = "query"),
            @ApiImplicitParam(name = "isVirtualGoods", value = "是否是虚拟商品：1-实物商品；2-虚拟商品", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query"),
            @ApiImplicitParam(name = "goodsCategoryId", value = "商品分类Id", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<GoodsVO>> getList(HttpServletRequest request,String webSite, String goodsName, String storeName,
                                               Date startTime, Date endTime,Date updateStartTime, Date updateEndTime, Integer state, Integer auditState, Integer isVirtualGoods,Integer goodsCategoryId) {
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        GoodsExample example = new GoodsExample();
        example.setWebSite(webSite);
        example.setGoodsNameLike(goodsName);
        example.setStoreNameLike(storeName);
        example.setCreateTimeAfter(startTime);
        example.setCreateTimeBefore(endTime);
        example.setIsVirtualGoods(isVirtualGoods);
        if(state == GoodsConst.GOODS_STATE_6){
            example.setUpdateTimeAfter(updateStartTime);
            example.setUpdateTimeBefore(updateEndTime);
        }
        if (!StringUtil.isNullOrZero(state)) {
            if (state == GoodsConst.GOODS_STATE_2) {
                if (!StringUtil.isNullOrZero(auditState)) {
                    if (auditState == GoodsConst.GOODS_STATE_2) {
                        example.setStateIn(GoodsConst.GOODS_STATE_SELL_NOW_TO_AUDIT + ", " + GoodsConst.GOODS_STATE_WAREHOUSE_TO_AUDIT);
                    } else {
                        example.setState(GoodsConst.GOODS_STATE_REJECT);
                    }
                } else {
                    example.setStateIn(GoodsConst.GOODS_STATE_SELL_NOW_TO_AUDIT + ", " + GoodsConst.GOODS_STATE_WAREHOUSE_TO_AUDIT + ", " + GoodsConst.GOODS_STATE_REJECT);
                }
            } else if (state == GoodsConst.GOODS_STATE_4) {
                example.setStateIn(GoodsConst.GOODS_STATE_WAREHOUSE_NO_AUDIT + ", " + GoodsConst.GOODS_STATE_WAREHOUSE_AUDIT_PASS + ", " + GoodsConst.GOODS_STATE_LOWER_BY_STORE);
            } else {
                example.setState(state);
            }
        } else {
            //默认显示在售商品
            example.setState(GoodsConst.GOODS_STATE_UPPER);
        }
        example.setIsDelete(GoodsConst.GOODS_IS_DELETE_NO);
        //先查询该分类分类级别
        if(goodsCategoryId != null){
            Integer grade = goodsModel.getGoodsCategoryId(goodsCategoryId);
            if (grade == GoodsCategoryConst.CATEGORY_GRADE_1) {
                example.setCategoryId1(goodsCategoryId);
            } else if (grade == GoodsCategoryConst.CATEGORY_GRADE_2) {
                example.setCategoryId2(goodsCategoryId);
            } else {
                example.setCategoryId3(goodsCategoryId);
            }
        }
        example.setOrderBy("update_time desc");
        List<Goods> goodsList = goodsModel.getGoodsList(example, pager);
        List<GoodsVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(goodsList)) {
            goodsList.forEach(goods -> {
                GoodsExtend goodsExtend = goodsExtendModel.getGoodsExtendByGoodsId(goods.getGoodsId());
                //查询货品列表
                ProductExample productExample = new ProductExample();
                productExample.setGoodsId(goods.getGoodsId());
                productExample.setStateIn(GoodsConst.PRODUCT_STATE_1 + "," + GoodsConst.PRODUCT_STATE_3);
                List<Product> productList = productModel.getProductList(productExample, null);
                AssertUtil.notEmpty(productList, "商品不存在");
                List<ProductVO> productVOS = new ArrayList<>();
                for (Product product : productList) {
                    productVOS.add(new ProductVO(product));
                }
                GoodsVO vo = new GoodsVO(goods, goodsExtend);
                vo.setProductList(productVOS);
                vos.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品Id", paramType = "query", required = true),
    })
    @GetMapping("detail")
    public JsonResult<SellerGoodsDetailVO> detail(HttpServletRequest request, @RequestParam(value = "goodsId") Long goodsId) {
        //查询商品信息
        Goods goods = goodsModel.getGoodsByGoodsId(goodsId);
        AssertUtil.notNull(goods, "商品不存在，请重试！");
        //查询商品扩展信息
        GoodsExtend goodsExtend = goodsExtendModel.getGoodsExtendByGoodsId(goodsId);
        AssertUtil.notNull(goodsExtend, "商品不存在，请重试！");

        //商品绑定标签
        GoodsBindLabelExample goodsBindLabelExample = new GoodsBindLabelExample();
        goodsBindLabelExample.setGoodsId(goodsId);
        goodsBindLabelExample.setOrderBy("bind_id asc");
        List<GoodsBindLabel> goodsBindLabelList = goodsBindLabelModel.getGoodsBindLabelList(goodsBindLabelExample, null);

        //商品绑定店铺内部分类
        StoreLabelBindGoodsExample storeLabelBindGoodsExample = new StoreLabelBindGoodsExample();
        storeLabelBindGoodsExample.setGoodsId(goodsId);
        storeLabelBindGoodsExample.setOrderBy("bind_id asc");
        List<StoreLabelBindGoods> storeLabelBindGoodsList = storeLabelBindGoodsModel.getStoreLabelBindGoodsList(storeLabelBindGoodsExample, null);

        //正常和禁用的货品
        ProductExample productExample = new ProductExample();
        productExample.setGoodsId(goodsId);
        productExample.setStateIn(GoodsConst.PRODUCT_STATE_1 + "," + GoodsConst.PRODUCT_STATE_3);
        productExample.setOrderBy("product_id asc");
        List<Product> productList = productModel.getProductList(productExample, null);

        //查询商品图片
        GoodsPictureExample goodsPictureExample = new GoodsPictureExample();
        goodsPictureExample.setGoodsId(goodsId);
        goodsPictureExample.setOrderBy("picture_id asc");
        List<GoodsPicture> goodsPictureList = goodsPictureModel.getGoodsPictureList(goodsPictureExample, null);

        //查询商品附件
        GoodsAnnexExample goodsAnnexExample = new GoodsAnnexExample();
        goodsAnnexExample.createCriteria().andGoodsIdEqualTo(goodsId).andStatusEqualTo(GoodsAnnexStatusConst.IS_STATUS);
        //只查状态为1的数据
//        goodsAnnexExample.createCriteria().andStatusEqualTo(GoodsAnnexStatusConst.IS_STATUS);
        List<GoodsAnnex> goodsAnnexList = goodsAnnexModel.goodsAnnexList(goodsAnnexExample);

        SellerGoodsDetailVO detailVO = new SellerGoodsDetailVO(goods, goodsExtend, goodsBindLabelList, storeLabelBindGoodsList, goodsPictureList, productList,goodsAnnexList);
        //顶部模版内容
        detailVO.setTopTemplateContent(getRelatedTemplateContent(goodsExtend.getRelatedTemplateIdTop()));
        //底部模版内容
        detailVO.setBottomTemplateContent(getRelatedTemplateContent(goodsExtend.getRelatedTemplateIdBottom()));

        //查询虚拟商品用户预留信息
        GoodsBindReserveNameExample example = new GoodsBindReserveNameExample();
        example.setGoodsId(goodsId);
        example.setOrderBy("reserve_name_id asc");
        List<GoodsBindReserveName> reserveNameList = goodsBindReserveNameModel.getGoodsBindReserveNameList(example, null);
        detailVO.setReserveList(reserveNameList);
        return SldResponse.success(detailVO);
    }

    /**
     * 获取关联版式内容
     *
     * @param templateId 模板id
     * @return
     */
    private String getRelatedTemplateContent(Integer templateId) {
        String templateContent = "";
        if (!StringUtil.isNullOrZero(templateId)) {
            GoodsRelatedTemplate goodsRelatedTemplate = goodsRelatedTemplateModel.getGoodsRelatedTemplateByTemplateId(templateId);
            if (goodsRelatedTemplate != null) {
                templateContent = goodsRelatedTemplate.getTemplateContent();
            }
        }
        return templateContent;
    }

    @ApiOperation("商品下架")
    @OperationLogger(option = "商品下架")
    @PostMapping("lockup")
    public JsonResult<Integer> lockup(HttpServletRequest request, GoodsLookUpDTO goodsLookUpDTO) {
        // 验证参数是否为空
        AssertUtil.notNull(goodsLookUpDTO, "下架信息不能为空，请重试！");
        AssertUtil.notEmpty(goodsLookUpDTO.getGoodsIds(), "下架信息不能为空，请重试！");
        AssertUtil.notEmpty(goodsLookUpDTO.getOfflineReason(), "下架原因不能为空，请重试！");
        AssertUtil.notFormatIds(goodsLookUpDTO.getGoodsIds(), "商品id格式错误,请重试");

        //校验商品锁定状态
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setGoodsIdIn(goodsLookUpDTO.getGoodsIds());
        List<Goods> goodsList = goodsModel.getGoodsList(goodsExample, null);
        goodsList.forEach(goods -> {
            AssertUtil.isTrue(goods.getIsLock() == GoodsConst.IS_LOCK_YES,
                    "商品名称为：" + goods.getGoodsName() + "的商品已锁定，不能下架");
        });

        String goodsIds = goodsLookUpDTO.getGoodsIds();
        String logMsg = "下架商品ID" + goodsIds;
        int number = goodsModel.goodsLockup(goodsLookUpDTO);

        goodsList.forEach(goods -> {
            VendorExample vendorExample = new VendorExample();
            vendorExample.setStoreId(goods.getStoreId());
            vendorExample.setIsStoreAdmin(VendorConst.IS_STORE_ADMIN_1);
            List<Vendor> vendorList = vendorModel.getVendorList(vendorExample, null);
            AssertUtil.isTrue(CollectionUtils.isEmpty(vendorList), "获取店铺信息失败");
            //设置状态为下架
            goods.setState(GoodsConst.GOODS_STATE_LOWER_BY_SYSTEM);
            productModel.upsertProduct(goods, vendorList.get(0));
        });

        //删除商品缓存信息
        for (String goodsId : goodsIds.split(",")) {
            objectRedisTemplate.opsForHash().delete(RedisConst.GOODS_DETAIL, String.valueOf(goodsId));
        }
        return SldResponse.success(number + "件商品下架成功", logMsg);
    }

    @ApiOperation("商品审核")
    @OperationLogger(option = "商品审核")
    @PostMapping("audit")
    public JsonResult<Integer> audit(HttpServletRequest request, GoodsAuditDTO goodsAuditDTO) {
        // 验证参数是否为空
        AssertUtil.notNull(goodsAuditDTO, "审核信息不能为空，请重试！");
        AssertUtil.notEmpty(goodsAuditDTO.getGoodsIds(), "审核商品不能为空，请重试！");
        AssertUtil.notEmpty(goodsAuditDTO.getState(), "审核状态不能为空，请重试！");
        AssertUtil.notFormatIds(goodsAuditDTO.getGoodsIds(), "商品id格式错误,请重试");

        String logMsg = "审核商品ID" + goodsAuditDTO.getGoodsIds();
        //审核拒绝参数判断
        if (goodsAuditDTO.getState().equals(GoodsConst.GOODS_AUDIT_REJECT)) {
            AssertUtil.notEmpty(goodsAuditDTO.getAuditReason(), "审核拒绝原因不能为空，请重试！");
        }
        goodsModel.audit(goodsAuditDTO);
        return SldResponse.success(goodsAuditDTO.getState().equals(GoodsConst.GOODS_AUDIT_AGREE) ? "审核通过" : "审核拒绝", logMsg);
    }
}
