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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
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.material.manage.WebsitGoodsPriceVO;
import com.gree.mall.manager.bean.material.manage.WebsitPriceUpdBean;
import com.gree.mall.manager.bean.material.manage.WebsitPriceUpdItemBean;
import com.gree.mall.manager.bean.material.manage.WebsitPriceUpdVO;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.enums.material.MaterialFlagEnum;
import com.gree.mall.manager.enums.material.WebsitGoodsTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.WebsitGoodsPrice;
import com.gree.mall.manager.plus.entity.WebsitPriceUpd;
import com.gree.mall.manager.plus.entity.WebsitPriceUpdItem;
import com.gree.mall.manager.plus.service.WebsitGoodsPriceService;
import com.gree.mall.manager.plus.service.WebsitPriceUpdItemService;
import com.gree.mall.manager.plus.service.WebsitPriceUpdService;
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.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.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class WebsitGoodsPriceLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WebsitGoodsPriceService websitGoodsPriceService;
    private final WebsitPriceUpdService websitPriceUpdService;
    private final WebsitPriceUpdItemService websitPriceUpdItemService;

    public IPage<WebsitGoodsPriceVO> page(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, WebsitGoodsPriceVO.class, adminUser);

        return materialMapper.websitGoodsPricePage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public IPage<WebsitPriceUpdVO> updPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, WebsitPriceUpdVO.class, adminUser);

        return materialMapper.websitPriceUpdPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public WebsitPriceUpdBean detail(String sheetId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPriceUpdBean bean = new WebsitPriceUpdBean();
        WebsitPriceUpd priceUpd = websitPriceUpdService.getById(sheetId);
        BeanUtils.copyProperties(priceUpd, bean);
        List<WebsitPriceUpdItemBean> list = websitPriceUpdItemService.lambdaQuery()
                .eq(WebsitPriceUpdItem::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(WebsitPriceUpdItem::getSheetId, sheetId)
                .list()
                .stream()
                .map(v -> {
                    WebsitPriceUpdItemBean item = new WebsitPriceUpdItemBean();
                    BeanUtils.copyProperties(v, item);
                    return item;
                }).collect(Collectors.toList());
        bean.setItems(list);
        return bean;
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(WebsitPriceUpdBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        }

        bean.setFlag(MaterialFlagEnum.SAVE.getKey());
        WebsitPriceUpd priceUpd = new WebsitPriceUpd();
        BeanUtils.copyProperties(bean, priceUpd);
        priceUpd.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
        priceUpd.insert();

        if (CollectionUtil.isNotEmpty(bean.getItems())) {
            List<WebsitPriceUpdItem> itemList = new ArrayList<>();
            for (WebsitPriceUpdItemBean itemBean : bean.getItems()) {
                WebsitPriceUpdItem item = new WebsitPriceUpdItem();
                BeanUtils.copyProperties(itemBean, item);
                item.setCompanyWechatId(priceUpd.getCompanyWechatId())
                        .setSheetId(priceUpd.getSheetId())
                        .setWebsitId(priceUpd.getWebsitId())
                        .setWebsitName(priceUpd.getWebsitName());
                itemList.add(item);
            }
            websitPriceUpdItemService.saveBatch(itemList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(WebsitPriceUpdBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPriceUpd websitPriceUpd = websitPriceUpdService.getById(bean.getSheetId());
        if (!websitPriceUpd.getFlag().equals(MaterialFlagEnum.SAVE.getKey())) {
            throw new RemoteServiceException("调价单非\"保存\"状态，不能再编辑");
        }

        bean.setCompanyWechatId(websitPriceUpd.getCompanyWechatId());
        bean.setCompanyWechatName(websitPriceUpd.getCompanyWechatName());
        bean.setFlag(MaterialFlagEnum.SAVE.getKey());

        WebsitPriceUpd priceUpd = new WebsitPriceUpd();
        BeanUtils.copyProperties(bean, priceUpd);
        priceUpd.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
        priceUpd.updateById();

        if (CollectionUtil.isNotEmpty(bean.getItems())) {
            websitPriceUpdItemService.lambdaUpdate()
                    .eq(WebsitPriceUpdItem::getCompanyWechatId, bean.getCompanyWechatId())
                    .eq(WebsitPriceUpdItem::getSheetId, bean.getSheetId())
                    .remove();
            List<WebsitPriceUpdItem> itemList = new ArrayList<>();
            for (WebsitPriceUpdItemBean itemBean : bean.getItems()) {
                WebsitPriceUpdItem item = new WebsitPriceUpdItem();
                BeanUtils.copyProperties(itemBean, item);
                item.setCompanyWechatId(priceUpd.getCompanyWechatId())
                        .setSheetId(priceUpd.getSheetId())
                        .setWebsitId(priceUpd.getWebsitId())
                        .setWebsitName(priceUpd.getWebsitName());
                itemList.add(item);
            }
            websitPriceUpdItemService.saveBatch(itemList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void confirm(String sheetId, MaterialFlagEnum flag) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPriceUpd priceUpd = websitPriceUpdService.getById(sheetId);
        if (!priceUpd.getCompanyWechatId().equals(adminUser.getCompanyWechatId())) {
            throw new RuntimeException("关键信息错误");
        }

        websitPriceUpdService.lambdaUpdate()
                .set(WebsitPriceUpd::getFlag, flag.getKey())
                .set(WebsitPriceUpd::getConfirmBy, adminUser.getNickName())
                .set(WebsitPriceUpd::getConfirmTime, DateUtil.date())
                .eq(WebsitPriceUpd::getSheetId, sheetId)
                .update();

        if (flag.getKey().equals(MaterialFlagEnum.OK.getKey())) {
            List<WebsitPriceUpdItem> updItems = websitPriceUpdItemService.lambdaQuery()
                    .eq(WebsitPriceUpdItem::getCompanyWechatId, priceUpd.getCompanyWechatId())
                    .eq(WebsitPriceUpdItem::getSheetId, sheetId)
                    .list();

            // 删除价格表记录
            websitGoodsPriceService.lambdaUpdate()
                    .eq(WebsitGoodsPrice::getCompanyWechatId, priceUpd.getCompanyWechatId())
                    .eq(WebsitGoodsPrice::getWebsitId, priceUpd.getWebsitId())
                    .in(WebsitGoodsPrice::getGoodsId, updItems.stream()
                            .map(WebsitPriceUpdItem::getGoodsId)
                            .collect(Collectors.toList()))
                    .remove();

            List<WebsitGoodsPrice> priceList = new ArrayList<>();
            for (WebsitPriceUpdItem updItem : updItems) {
                WebsitGoodsPrice price = new WebsitGoodsPrice();
                price.setCompanyWechatId(priceUpd.getCompanyWechatId());
                price.setCompanyWechatName(priceUpd.getCompanyWechatName());
                price.setWebsitId(updItem.getWebsitId());
                price.setWebsitName(updItem.getWebsitName());
                price.setGoodsType(priceUpd.getGoodsType());
                price.setGoodsId(updItem.getGoodsId());
                price.setPrice(updItem.getNewPrice());
                price.setSheetId(priceUpd.getSheetId());
                price.setRemark(priceUpd.getRemark());
                priceList.add(price);
            }
            websitGoodsPriceService.saveBatch(priceList);
        }
    }
}
