package com.gree.mall.manager.logic.material.vender;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.vender.WebsitVenderGoodsBean;
import com.gree.mall.manager.bean.material.vender.WebsitVenderGoodsRelaVO;
import com.gree.mall.manager.bean.material.vender.WebsitVenderGoodsVO;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.enums.ExamineStatusEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.WebsitVenderGoods;
import com.gree.mall.manager.plus.entity.WebsitVenderGoodsItem;
import com.gree.mall.manager.plus.entity.WebsitVenderGoodsRela;
import com.gree.mall.manager.plus.service.WebsitVenderGoodsItemService;
import com.gree.mall.manager.plus.service.WebsitVenderGoodsRelaService;
import com.gree.mall.manager.plus.service.WebsitVenderGoodsService;
import com.gree.mall.manager.zfire.bean.QueryParamBean;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class VenderGoodsLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WebsitVenderGoodsService websitVenderGoodsService;
    private final WebsitVenderGoodsItemService websitVenderGoodsItemService;
    private final WebsitVenderGoodsRelaService websitVenderGoodsRelaService;

    public IPage<WebsitVenderGoodsVO> page(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (CollectionUtil.isEmpty(zfireParamBean.getParams())) {
            zfireParamBean.setParams(new ArrayList<>());
        }

        if (adminUser.getIsVender()) {
            QueryParamBean paramBean = new QueryParamBean();
            paramBean.setParam("a.vender_id").setCompare("=").setValue(adminUser.getVenderId());
            zfireParamBean.getParams().add(paramBean);
        }
        FieldUtils.materialParam(zfireParamBean, WebsitVenderGoodsVO.class, adminUser);
        return materialMapper.websitVenderGoodsPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public WebsitVenderGoodsBean detail(String id) {
        WebsitVenderGoods goods = websitVenderGoodsService.getById(id);
        WebsitVenderGoodsBean bean = new WebsitVenderGoodsBean();

        BeanUtils.copyProperties(goods, bean);
        final List<WebsitVenderGoodsItem> items = websitVenderGoodsItemService.lambdaQuery()
                .eq(WebsitVenderGoodsItem::getSheetId, goods.getSheetId())
                .list();
        bean.setItems(items);

        return bean;
    }

    @Transactional
    public void add(WebsitVenderGoodsBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        bean.setSheetId(IdWorker.getIdStr());
        this.checkParams(bean);

        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        }

        bean.setStatus(ExamineStatusEnum.SAVE.getKey())
                .insert();
        if (CollectionUtil.isNotEmpty(bean.getItems())) {
            websitVenderGoodsItemService.saveBatch(bean.getItems());
        }
    }

    private void checkParams(WebsitVenderGoodsBean bean) {
        if (StringUtils.isBlank(bean.getVenderId())) {
            throw new RemoteServiceException("请选择供应商");
        }

        if (CollectionUtil.isNotEmpty(bean.getItems())) {
            for (int i = 0; i < bean.getItems().size(); i++) {
                final WebsitVenderGoodsItem item = bean.getItems().get(i);
                if (StringUtils.isBlank(item.getGoodsId())) {
                    throw new RemoteServiceException("第" + (i+1) + "行, 辅材编号不能为空");
                }
                item.setSheetId(bean.getSheetId());
            }
        }
    }

    @Transactional
    public void edit(WebsitVenderGoodsBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        this.checkParams(bean);

        bean.setStatus(ExamineStatusEnum.SAVE.getKey())
                .updateById();

        websitVenderGoodsItemService.lambdaUpdate()
                .eq(WebsitVenderGoodsItem::getSheetId, bean.getSheetId())
                .remove();
        if (CollectionUtil.isNotEmpty(bean.getItems())) {
            websitVenderGoodsItemService.saveBatch(bean.getItems());
        }
    }

    @Transactional
    public void confirm(WebsitVenderGoodsBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        bean = this.detail(bean.getSheetId());
        bean.setStatus(ExamineStatusEnum.OK.getKey())
                .setConfirmBy(adminUser.getNickName())
                .setConfirmTime(DateUtil.date())
                .updateById();

        if (CollectionUtil.isNotEmpty(bean.getItems())) {
            List<WebsitVenderGoodsRela> relaList = websitVenderGoodsRelaService.lambdaQuery()
                    .eq(WebsitVenderGoodsRela::getCompanyWechatId, bean.getCompanyWechatId())
                    .eq(WebsitVenderGoodsRela::getVenderId, bean.getVenderId())
                    .in(WebsitVenderGoodsRela::getGoodsId, bean.getItems().stream()
                            .map(WebsitVenderGoodsItem::getGoodsId)
                            .collect(Collectors.toList()))
                    .list();

            Map<String, WebsitVenderGoodsRela> relaMap = relaList.stream().collect(Collectors.toMap(WebsitVenderGoodsRela::getGoodsId, Function.identity()));

            List<WebsitVenderGoodsRela> goodsRelaList = new ArrayList<>();
            for (WebsitVenderGoodsItem item : bean.getItems()) {
                WebsitVenderGoodsRela goodsRela = relaMap.get(item.getGoodsId());
                if (Objects.isNull(goodsRela)) {
                    goodsRela = new WebsitVenderGoodsRela();
                    goodsRela.setCompanyWechatId(bean.getCompanyWechatId())
                            .setCompanyWechatName(bean.getCompanyWechatName())
                            .setVenderId(bean.getVenderId())
                            .setVenderName(bean.getVenderName())
                            .setGoodsId(item.getGoodsId())
                            .setGoodsName(item.getGoodsName())
                            .setCost(item.getCost())
                            .setRelaStatus(item.getStatus());
                } else {
                    goodsRela.setCost(item.getCost())
                            .setRelaStatus(item.getStatus());
                }

                goodsRelaList.add(goodsRela);
            }

            websitVenderGoodsRelaService.saveOrUpdateBatch(goodsRelaList);
        }
    }

    @Transactional
    public void del(List<String> ids) {
        websitVenderGoodsService.removeByIds(ids);
        websitVenderGoodsItemService.lambdaUpdate()
                .in(WebsitVenderGoodsItem::getSheetId, ids)
                .remove();
    }

    public IPage<WebsitVenderGoodsRelaVO> ralaPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (CollectionUtil.isEmpty(zfireParamBean.getParams())) {
            zfireParamBean.setParams(new ArrayList<>());
        }

        if (adminUser.getIsVender()) {
            QueryParamBean paramBean = new QueryParamBean();
            paramBean.setParam("a.vender_id").setCompare("=").setValue(adminUser.getVenderId());
            zfireParamBean.getParams().add(paramBean);
        }
        FieldUtils.materialParam(zfireParamBean, WebsitVenderGoodsRelaVO.class, adminUser);
        return materialMapper.websitVenderGoodsRalaPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }
}
