package com.gree.mall.manager.logic.goods;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.goods.GoodsLeaseBean;
import com.gree.mall.manager.bean.goods.GoodsLeaseCountBean;
import com.gree.mall.manager.bean.goods.GoodsSortBean;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.GoodsCategory;
import com.gree.mall.manager.plus.entity.GoodsLease;
import com.gree.mall.manager.plus.service.GoodsCategoryService;
import com.gree.mall.manager.plus.service.GoodsLeaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class GoodsLeaseLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final GoodsLeaseService goodsLeaseService;
    private final GoodsCategoryService goodsCategoryService;

    public IPage<GoodsLeaseBean> page(String keyword, BigDecimal startPrice, BigDecimal endPrice, BigDecimal startDeposit,
                                      BigDecimal endDeposit, String goodsSortJson, String categoryId, Boolean status,
                                      Integer pageNum, Integer pageSize, HttpServletRequest request) {

        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        String sortStr = null;
        if (goodsSortJson != null && !goodsSortJson.trim().equals("")) {
            JSONArray goodsSortBeanArray = JSON.parseArray(StringEscapeUtils.unescapeJava(goodsSortJson));
            sortStr = GoodsSortBean.convertColumn(goodsSortBeanArray);
        }
        List<String> categoryIds = new ArrayList<>();
        if (StringUtils.isNotBlank(categoryId)) {
            categoryIds.add(categoryId);
        }

        IPage<GoodsLeaseBean> page = commonMapper.goodsLeaseList(new Page<>(pageNum, pageSize), keyword, categoryIds, startPrice,
                endPrice, startDeposit, endDeposit, sortStr, status, companyWechatIds);

        return page;
    }

    public GoodsLease detail(String id) {
        return goodsLeaseService.getById(id);
    }

    public void save(GoodsLease goods) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
            throw new RemoteServiceException("平台账号不能新增");
        }

        String companyWechatId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        String companyWechatName = adminUser.getAdminCompanyWechat().getCompanyName();

        goods.setCompanyWechatId(companyWechatId)
                .setCompanyWechatName(companyWechatName);
        
        this.checkRequireParams(goods);

        final GoodsCategory category = goodsCategoryService.getById(goods.getCategoryId());
        goods.setCategoryName(category.getName())
                .setCategoryUrl(category.getImgUrl());

        goods.insertOrUpdate();
    }

    private void checkRequireParams(GoodsLease goods) {
        if (StringUtils.isBlank(goods.getName())) {
            throw new RemoteServiceException("商品名称不能为空");
        }
        if (StringUtils.isBlank(goods.getRepairRemark())) {
            throw new RemoteServiceException("保修描述不能为空");
        }
        if (StringUtils.isBlank(goods.getCategoryId())) {
            throw new RemoteServiceException("商品分类不能为空");
        }
        if (Objects.isNull(goods.getLeasePrice())) {
            throw new RemoteServiceException("请填写租赁价格");
        }
        if (Objects.isNull(goods.getOldPrice())) {
            throw new RemoteServiceException("请填写划线价格");
        }
        if (Objects.isNull(goods.getDepositPrice())) {
            throw new RemoteServiceException("请填写订金价格");
        }
        if (Objects.isNull(goods.getStatus())) {
            throw new RemoteServiceException("商品状态不能为空");
        }
        if (Objects.isNull(goods.getSort())) {
            throw new RemoteServiceException("商品排序不能为空");
        }
    }

    public void del(List<String> ids) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
            throw new RemoteServiceException("平台账号不能操作删除");
        }
        if (CollectionUtil.isNotEmpty(ids)) {
            final Integer count = goodsLeaseService.lambdaQuery()
                    .eq(GoodsLease::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                    .in(GoodsLease::getId, ids)
                    .eq(GoodsLease::getStatus, true)
                    .count();
            if (count > 0) {
                throw new RemoteServiceException("租赁商品未下架，删除失败");
            }
            goodsLeaseService.removeByIds(ids);
        }
    }

    public GoodsLeaseCountBean count() {
        GoodsLeaseCountBean bean = new GoodsLeaseCountBean();
        final Integer upCount = goodsLeaseService.lambdaQuery()
                .eq(GoodsLease::getDel, false)
                .eq(GoodsLease::getStatus, true)
                .count();
        final Integer downCount = goodsLeaseService.lambdaQuery()
                .eq(GoodsLease::getDel, false)
                .eq(GoodsLease::getStatus, false)
                .count();
        bean.setUpCount(upCount);
        bean.setDownCount(downCount);
        return bean;
    }
}
