package com.sckw.product.service.operation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.model.vo.TableBottom;
import com.sckw.core.model.vo.TableStatisticRes;
import com.sckw.core.model.vo.TableTop;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.product.dao.KwpGoodsMapper;
import com.sckw.product.enums.GoodsStatusEnum;
import com.sckw.product.model.GoodsListExport;
import com.sckw.product.model.KwpGoods;
import com.sckw.product.model.OperationGoodsListExport;
import com.sckw.product.model.dto.OperatorGoodsListQueryDTO;
import com.sckw.product.model.vo.req.OperatorGoodsExportQueryVO;
import com.sckw.product.model.vo.req.OperatorGoodsListQueryVO;
import com.sckw.product.model.vo.req.OperatorGoodsStsQueryVO;
import com.sckw.product.model.vo.res.GoodsDetail;
import com.sckw.product.model.vo.res.GoodsList;
import com.sckw.product.model.vo.res.OperationGoodsDetail;
import com.sckw.product.model.vo.res.OperationGoodsList;
import com.sckw.product.service.KwpGoodsService;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.model.dto.res.KwsUserResDto;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @desc: 商品service
 * @author: yzc
 * @date: 2023-06-25 14:47
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GoodsManagerService {

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteUserService remoteUserService;


    private final KwpGoodsService kwpGoodsService;
    private final KwpGoodsMapper kwpGoodsMapper;


    /**
     * @desc: 分页查询
     * @author: yzc
     * @date: 2023-09-18 15:19
     * @Param params:
     * @return: com.sckw.core.model.page.PageResult
     */
    public PageResult select(OperatorGoodsListQueryVO params) {
        LambdaQueryWrapper<KwpGoods> wrapper = buildWrapper(BeanUtils.copyProperties(params, OperatorGoodsListQueryDTO.class));
        Page<KwpGoods> page = new Page<>(params.getPage(), params.getPageSize());
        IPage<KwpGoods> goodsIpage = kwpGoodsMapper.selectPage(page, wrapper);
        List<KwpGoods> list = goodsIpage.getRecords();
        if (CollectionUtils.isEmpty(list)) {
            return PageResult.build(params.getPage(), params.getPageSize(), goodsIpage.getTotal(), Collections.emptyList());
        }
        List<GoodsList> goodsLists = kwpGoodsService.buildGoodLists(list);
        List<OperationGoodsList> result = BeanUtils.copyToList(goodsLists, OperationGoodsList.class);
        return PageResult.build(params.getPage(), params.getPageSize(), goodsIpage.getTotal(), result);
    }


    /**
     * @desc: 构建查询条件
     * @author: lt
     * @date: 2023-09-14 10:14
     * @Param list:
     * @return: java.util.List<com.sckw.product.model.vo.res.GoodsList>
     */
    private LambdaQueryWrapper<KwpGoods> buildWrapper(OperatorGoodsListQueryDTO params) {
        LambdaQueryWrapper<KwpGoods> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(params.getIds())) {
            List<Long> ids = StringUtils.splitStrToList(params.getIds(), ",", Long.class);
            wrapper.in(KwpGoods::getId, ids);
        } else {
            if (Objects.nonNull(params.getStartCreateTime())) {
                wrapper.ge(KwpGoods::getCreateTime, params.getStartCreateTime());
            }
            if (Objects.nonNull(params.getEndCreateTime())) {
                wrapper.le(KwpGoods::getCreateTime, params.getEndCreateTime());
            }
            //运营端不需要显示草稿数据
            if (Objects.isNull(params.getStatus())) {
                wrapper.ne(KwpGoods::getStatus, 0);
            } else {
                wrapper.eq(KwpGoods::getStatus, params.getStatus());
            }
            String keywords = params.getKeywords();
            if (StringUtils.isNotBlank(keywords)) {
                //模糊匹配商品名称、仓储地址、客户经理
                List<KwsUserResDto> managers = remoteUserService.getUserByName(keywords);
                if (CollectionUtils.isNotEmpty(managers)) {
                    List<Long> managerIds = managers.stream().map(KwsUserResDto::getId).toList();
                    wrapper.and(e -> e.like(KwpGoods::getName, keywords).or().like(KwpGoods::getAddressName, keywords)
                            .or().in(KwpGoods::getManager, managerIds));
                } else {
                    wrapper.and(e -> e.like(KwpGoods::getName, keywords).or().like(KwpGoods::getAddressName, keywords));
                }
            }
        }
        if (StringUtils.isNotBlank(params.getGoodsType()) && StringUtils.isNotBlank(params.getGoodsTypeValue())) {
            List<SysDictResDto> goodsTypeList = remoteSystemService.queryDictBottom(params.getGoodsType(), params.getGoodsTypeValue());
            if (CollectionUtils.isNotEmpty(goodsTypeList)) {
                List<String> goodsTypes = goodsTypeList.stream().map(SysDictResDto::getValue).toList();
                wrapper.in(KwpGoods::getGoodsType, goodsTypes);
            }
        }
        wrapper.eq(KwpGoods::getDelFlag, Global.NO).orderByDesc(KwpGoods::getCreateTime);
        return wrapper;
    }

    /**
     * @desc: 获取商品详情
     * @author: lt
     * @date: 2023-09-14 14:20
     * @Param id:
     * @return: com.sckw.product.model.vo.res.GoodsDetail
     */
    public OperationGoodsDetail getDetail(Long id) {
        GoodsDetail goodsDetail = kwpGoodsService.detail(id);
        return BeanUtils.copyProperties(goodsDetail, OperationGoodsDetail.class);
    }

    /**
     * @desc: 统计查询
     * @author: lt
     * @date: 2023-09-14 14:44
     * @Param params:
     * @return: com.sckw.core.model.vo.TableStatisticRes
     */
    public TableStatisticRes statistic(OperatorGoodsStsQueryVO params) {
        TableStatisticRes res = new TableStatisticRes();
        LambdaQueryWrapper<KwpGoods> wrapper = buildWrapper(BeanUtils.copyProperties(params, OperatorGoodsListQueryDTO.class));
        List<KwpGoods> goodsList = kwpGoodsMapper.selectList(wrapper);
        Map<Integer, List<KwpGoods>> map = goodsList.stream().collect(Collectors.groupingBy(KwpGoods::getStatus));
        List<TableTop> tableTops = new ArrayList<>();
        TableTop all = new TableTop();
        all.setName("全部").setTotal(CollectionUtils.isEmpty(goodsList) ? 0 : goodsList.size());
        tableTops.add(all);
        List<GoodsStatusEnum> sortList = GoodsStatusEnum.getSortList();
        sortList.remove(0);
        sortList.forEach(e -> {
            List<KwpGoods> list = map.get(e.getCode());
            int total = CollectionUtils.isEmpty(list) ? 0 : list.size();
            TableTop tableTop = new TableTop();
            tableTop.setName(e.getMsg()).setValue(e.getCode()).setTotal(total);
            tableTops.add(tableTop);
        });
        TableBottom tableBottom = new TableBottom();
        tableBottom.setTotal(CollectionUtils.isEmpty(goodsList) ? 0 : goodsList.size());
        res.setTableTops(tableTops).setTableBottom(tableBottom);
        return res;
    }

    /**
     * @desc: 导出
     * @author: lt
     * @date: 2023-09-14 17:56
     * @Param params:
     * @return: void
     */
    public List<OperationGoodsListExport> export(OperatorGoodsExportQueryVO params) {
        LambdaQueryWrapper<KwpGoods> wrapper = buildWrapper(BeanUtils.copyProperties(params, OperatorGoodsListQueryDTO.class));
        List<KwpGoods> list = kwpGoodsMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<GoodsListExport> exportResults = kwpGoodsService.getExportResults(list);
        return BeanUtils.copyToList(exportResults, OperationGoodsListExport.class);
    }


}
