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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.base.WorkerGoodsBean;
import com.gree.mall.manager.bean.material.base.WorkerGoodsRelaBean;
import com.gree.mall.manager.bean.material.base.WorkerGoodsRelaExportBean;
import com.gree.mall.manager.bean.material.base.WorkerGoodsVO;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.enums.base.BaseEnum;
import com.gree.mall.manager.enums.material.StateEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
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.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class WorkerGoodsLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WorkerGoodsService workerGoodsService;
    private final WorkerGoodsRelaService workerGoodsRelaService;
    private final MaterialConfigService materialConfigService;
    private final WebsitGoodsCategoryService websitGoodsCategoryService;
    private final WebsitGoodsService websitGoodsService;

    public IPage<WorkerGoodsVO> page(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean.setCompanyWechatId(adminUser.getCompanyWechatId());
        FieldUtils.supplyParam(zfireParamBean, WorkerGoodsVO.class);
        return materialMapper.workGoodsPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public WorkerGoodsBean detail(String id) {
        WorkerGoods workerGoods = workerGoodsService.getById(id);
        WorkerGoodsBean bean = new WorkerGoodsBean();
        BeanUtils.copyProperties(workerGoods, bean);
        List<WorkerGoodsRela> goodsRelas = workerGoodsRelaService.lambdaQuery()
                .eq(WorkerGoodsRela::getWorkerGoodsId, id)
                .list();
        List<WorkerGoodsRelaBean> beanList = new ArrayList<>();
        for (WorkerGoodsRela rela : goodsRelas) {
            WorkerGoodsRelaBean relaBean = new WorkerGoodsRelaBean();
            BeanUtils.copyProperties(rela, relaBean);
            final WebsitGoods goods = websitGoodsService.getById(rela.getWebsitGoodsId());
            relaBean.setManageWorkerStock(BaseEnum.keyToValue(IsYesNoEnum.class, goods.getManageWorkerStock()));
            beanList.add(relaBean);
        }
        bean.setItems(beanList);
        return bean;
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(WorkerGoodsBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        MaterialConfig config = materialConfigService.lambdaQuery()
                .eq(MaterialConfig::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .one();
        Integer incrId = config.getWorkerGoodsIncrId();
        bean.setGoodsId(null);
        bean.setCompanyWechatId(adminUser.getCompanyWechatId());
        bean.setCompanyWechatName(adminUser.getCompanyName());

        final WebsitGoodsCategory category = websitGoodsCategoryService.getById(bean.getGoodsCategoryId());

        WorkerGoods workerGoods = new WorkerGoods();
        BeanUtils.copyProperties(bean, workerGoods);
        workerGoods.setGoodsId("W" + incrId)
                .setParentCategoryId(category.getParentCategoryId())
                .setParentCategoryName(category.getParentCategoryName())
                .setGoodsCategoryId(category.getCategoryId())
                .setGoodsCategoryName(category.getCategoryName());
        workerGoods.insert();

        config.setWorkerGoodsIncrId(incrId + 1)
                .updateById();

        if (CollectionUtil.isNotEmpty(bean.getItems())) {
            List<WorkerGoodsRela> items = new ArrayList<>();
            // 检查是否已有绑定关系
            for (WorkerGoodsRelaBean item : bean.getItems()) {
                final Integer count = workerGoodsRelaService.lambdaQuery()
                        .eq(WorkerGoodsRela::getCompanyWechatId, workerGoods.getCompanyWechatId())
                        .eq(WorkerGoodsRela::getWebsitGoodsId, item.getWebsitGoodsId())
                        .count();
                if (count > 0) {
                    throw new RemoteServiceException("网点辅材: ”" + item.getWebsitGoodsName() + "“已有绑定关系");
                }
                item.setCompanyWechatId(workerGoods.getCompanyWechatId())
                    .setWorkerGoodsId(workerGoods.getGoodsId())
                    .setWorkerGoodsName(workerGoods.getGoodsName());
                items.add(item);
            }
            workerGoodsRelaService.saveBatch(items);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(WorkerGoodsBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        WorkerGoods workerGoods = new WorkerGoods();
        BeanUtils.copyProperties(bean, workerGoods);

        final WebsitGoodsCategory category = websitGoodsCategoryService.getById(bean.getGoodsCategoryId());
        workerGoods.setParentCategoryId(category.getParentCategoryId())
                .setParentCategoryName(category.getParentCategoryName())
                .setGoodsCategoryId(category.getCategoryId())
                .setGoodsCategoryName(category.getCategoryName());

        workerGoods.updateById();

        if (CollectionUtil.isNotEmpty(bean.getItems())) {
            workerGoodsRelaService.lambdaUpdate()
                    .eq(WorkerGoodsRela::getCompanyWechatId, workerGoods.getCompanyWechatId())
                    .eq(WorkerGoodsRela::getWorkerGoodsId, workerGoods.getGoodsId())
                    .remove();
            List<WorkerGoodsRela> items = new ArrayList<>();
            for (WorkerGoodsRela item : bean.getItems()) {
                final Integer count = workerGoodsRelaService.lambdaQuery()
                        .eq(WorkerGoodsRela::getCompanyWechatId, workerGoods.getCompanyWechatId())
                        .eq(WorkerGoodsRela::getWebsitGoodsId, item.getWebsitGoodsId())
                        .count();
                if (count > 0) {
                    throw new RemoteServiceException("网点辅材: ”" + item.getWebsitGoodsName() + "“已有绑定关系");
                }
                item.setCompanyWechatId(workerGoods.getCompanyWechatId())
                        .setWorkerGoodsId(workerGoods.getGoodsId())
                        .setWorkerGoodsName(workerGoods.getGoodsName());
                items.add(item);
            }
            workerGoodsRelaService.saveBatch(items);
        }
    }

    public ExcelData relaExport() throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        final List<WorkerGoodsRelaExportBean> beans = materialMapper.exportWorkerMaterialRela(adminUser.getCompanyWechatId());

        String[] titles = new String[]{"商户名称", "小类名称", "师傅辅材编号", "师傅辅材名称", "是否小件", "状态", "网点辅材小类"
                , "网点辅材编号", "网点辅材名称", "规格", "转换系数", "是否入师傅库存", "网点辅材状态"};
        List<List<Object>> rows = new ArrayList<>();

        final Map<String, List<WorkerGoodsRelaExportBean>> beanMap = beans.stream().collect(Collectors.groupingBy(v -> v.getCompanyWechatId() + v.getGoodsId()));


        for (Map.Entry<String, List<WorkerGoodsRelaExportBean>> entry : beanMap.entrySet()) {
            List<Object> row = new ArrayList<>();
            final List<WorkerGoodsRelaExportBean> entryValue = entry.getValue();
            final WorkerGoodsRelaExportBean exportBean = entryValue.get(0);

            row.add(exportBean.getCompanyWechatName());
            row.add(exportBean.getGoodsCategoryName());
            row.add(exportBean.getGoodsId());
            row.add(exportBean.getGoodsName());
            row.add(exportBean.getIsSmall() ? "是" : "否");
            row.add(StringUtils.isNotBlank(exportBean.getStatus()) ? BaseEnum.keyToValue(StateEnum.class, exportBean.getStatus()) : "");
            row.add(exportBean.getWebsitCategoryName());
            row.add(exportBean.getWebsitGoodsId());
            row.add(exportBean.getWebsitGoodsName());
            row.add(exportBean.getSpecification());
            row.add(exportBean.getGoodsSalesConvertQty());
            row.add(StringUtils.isNotBlank(exportBean.getManageWorkerStock()) ? BaseEnum.keyToValue(IsYesNoEnum.class, exportBean.getManageWorkerStock()) : "");
            row.add(StringUtils.isNotBlank(exportBean.getWebsitGoodsStatus()) ? BaseEnum.keyToValue(StateEnum.class, exportBean.getWebsitGoodsStatus()) : "");
            rows.add(row);

            if (entryValue.size() > 1) {
                for (int i = 1; i < entryValue.size(); i++) {
                    List<Object> row2 = new ArrayList<>();
                    final WorkerGoodsRelaExportBean exportBean2 = entryValue.get(i);
                    row2.add("");
                    row2.add("");
                    row2.add("");
                    row2.add("");
                    row2.add("");
                    row2.add("");
                    row2.add(exportBean2.getWebsitCategoryName());
                    row2.add(exportBean2.getWebsitGoodsId());
                    row2.add(exportBean2.getWebsitGoodsName());
                    row2.add(exportBean2.getSpecification());
                    row2.add(exportBean2.getGoodsSalesConvertQty());
                    row2.add(StringUtils.isNotBlank(exportBean2.getManageWorkerStock()) ? BaseEnum.keyToValue(IsYesNoEnum.class, exportBean2.getManageWorkerStock()) : "");
                    row2.add(StringUtils.isNotBlank(exportBean2.getWebsitGoodsStatus()) ? BaseEnum.keyToValue(StateEnum.class, exportBean2.getWebsitGoodsStatus()) : "");
                    rows.add(row2);
                }
            }
        }

        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }
}
