package com.jwipc.sys.logic.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.SapResposeBody;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.sys.constant.ProductGroupSapClient;
import com.jwipc.sys.convert.ProductGroupConvert;
import com.jwipc.sys.dto.ProductGroupDTO;
import com.jwipc.sys.dto.ProductGroupImportDTO;
import com.jwipc.sys.dto.ProductGroupSapDTO;
import com.jwipc.sys.entity.ProductGroup;
import com.jwipc.sys.entity.PurchaseCategory;
import com.jwipc.sys.logic.FileLogic;
import com.jwipc.sys.logic.ProductGroupLogic;
import com.jwipc.sys.model.po.ProductGroupPO;
import com.jwipc.sys.model.query.ProductGroupQuery;
import com.jwipc.sys.service.IProductGroupService;
import com.jwipc.sys.service.IPurchaseCategoryService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Al
 * @create 2024-02-18 10:00
 * 物料组
 */
@Service
@RequiredArgsConstructor
public class ProductGroupLogicImpl implements ProductGroupLogic {
    private final IProductGroupService productGroupService;
    private final ProductGroupConvert productGroupConvert;
    private final ProductGroupSapClient productGroupSapClient;
    private final IPurchaseCategoryService purchaseCategoryService;
    //private final ProductGroupClient productGroupClient;
    private final FileLogic fileLogic;

    @Override
    public PageView findByPage(ProductGroupQuery query) {
        final Page<ProductGroup> dbPage = PageUtil.toPage(query);

        List<ProductGroupPO> productGroupPOS = productGroupService.findPageByQuery(dbPage, query);

        return PageUtil.getPV(productGroupConvert.po2PageListDTO(productGroupPOS), dbPage.getTotal());
    }

    //根据id查询数据
    @Override
    public ProductGroupDTO getById(Long id) {
        if (id != null) {
            ProductGroupPO qmNoticeOrderPO = productGroupService.getDataById(id);
            return productGroupConvert.po2DTO(qmNoticeOrderPO);
        }else{
            return new ProductGroupDTO();
        }
    }

    //供应商确认保存
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(ProductGroupDTO param) {
        param.setCreateTime(LocalDateTime.now());
        param.setDisable(1);
        if (param.getId()!=null){
            final LambdaQueryWrapper<ProductGroup> resourcesLambdaQueryWrapper = new LambdaQueryWrapper<ProductGroup>().eq(
                    ProductGroup::getMaterialGroup, param.getMaterialGroup()).ne(ProductGroup::getId,param.getId()).last(" limit 1");
            if (ObjectUtil.isNotNull(productGroupService.getOne(resourcesLambdaQueryWrapper))){
                throw new DaoException("物料组编码重复");
            }
            param.setErpStatus(0);
        }else {
            final LambdaQueryWrapper<ProductGroup> resourcesLambdaQueryWrapper = new LambdaQueryWrapper<ProductGroup>().eq(
                    ProductGroup::getMaterialGroup, param.getMaterialGroup()).last(" limit 1");
            if (ObjectUtil.isNotNull(productGroupService.getOne(resourcesLambdaQueryWrapper))){
                throw new DaoException("物料组编码重复");
            }
        }
        productGroupService.saveOrUpdate(productGroupConvert.dto2Entity(param));
    }

    /**
     * 同步到sap
     *
     * @param ids 参数
     */
    @Override
    public void syncSap(String ids,String deleteFlag) {
        final List<Long> idList = JSONArray.parseArray(ids, Long.class);
        List<ProductGroup> productGroups = productGroupService.listByIds(idList);
        final ProductGroupSapDTO.Item1 item1 = new ProductGroupSapDTO.Item1();
        item1.item = Lists.newArrayList();
        for (ProductGroup productGroup : productGroups){
            if (StringUtils.isEmpty(productGroup.getCategoryCode())){
                continue;
            }
            final ProductGroupSapDTO.Item item = new ProductGroupSapDTO.Item();
            item.ZZRPL = productGroup.getCategoryCode();
            PurchaseCategory purchaseCategory = purchaseCategoryService.getOne(Wrappers.lambdaQuery(PurchaseCategory.class).eq(PurchaseCategory::getFirstLevelPurchaseCode,productGroup.getCategoryCode()).last(" limit 1"));
            item.ZZRPLX = ObjectUtil.isNull(purchaseCategory)?"":purchaseCategory.getFirstLevelPurchaseName();
            item.MATKL = productGroup.getMaterialGroup();
            item.ZDEL = deleteFlag;
            item1.item.add(item);
            ProductGroupSapDTO productGroupSapDTO = new ProductGroupSapDTO();
            productGroupSapDTO.setIT_DATA(item1);
            SapResposeBody sapResposeBody = productGroupSapClient.syncProductGroupWithCategoryCode(productGroupSapDTO);
            if (sapResposeBody.getES_RET().getCODE().equals(RestCode.SAP_SUCCESS.getCode())) {
                productGroup.setErpStatus(1);
                productGroup.setErpResult(sapResposeBody.getES_RET().getMSG());
                productGroup.setErpTime(LocalDateTime.now());
            }else {
                productGroup.setErpStatus(2);
                productGroup.setErpResult(sapResposeBody.getES_RET().getMSG());
                productGroup.setErpTime(LocalDateTime.now());
            }
            productGroupService.updateById(productGroup);
        }
    }

    @Override
    public void disable(Long id, Integer disable) {
        ProductGroup productGroup = new ProductGroup();
        productGroup.setId(id);
        productGroup.setDisable(disable);
        productGroupService.updateById(productGroup);
        this.syncSap("["+id+"]",disable==1?"":"X");
    }
    //列表主数据
    @Override
    public List<ProductGroupDTO> listAll(ProductGroupQuery query) {
        List<ProductGroupPO> productGroupPOS = productGroupService.findPageByQuery(null, query);
        return productGroupConvert.po2PageListDTO(productGroupPOS);
    }
    //物料组文件导入
    @Override
    public void productGroupImportData(MultipartFile fileId) {
        List<ProductGroupImportDTO> cachedDataList = ListUtils.newArrayList();
        try {
            EasyExcel.read(fileId.getInputStream(), ProductGroupImportDTO.class,
                    new ReadListener<ProductGroupImportDTO>() {
                        @Override
                        public void invoke(ProductGroupImportDTO data, AnalysisContext context) {
                            final String code = data.getMaterialGroup();
                            final String desc = data.getMaterialDesc();
                            if (Strings.isNullOrEmpty(code)) {
                                throw new DaoException("物料组编码不能为空!");
                            }
                            if (Strings.isNullOrEmpty(desc)) {
                                throw new DaoException("物料组名称不能为空!");
                            }
                            if (Strings.isNullOrEmpty(data.getCategoryCode())) {
                                throw new DaoException("品类编码不能为空!");
                            }
                            PurchaseCategory purchaseCategory = purchaseCategoryService.getOne(Wrappers.lambdaQuery(PurchaseCategory.class).eq(PurchaseCategory::getFirstLevelPurchaseCode,data.getCategoryCode()).last(" limit 1"));
                            if (ObjectUtil.isNull(purchaseCategory)) {
                                throw new DaoException(StrUtil.format("品类编码：{}在系统中不存在",data.getCategoryCode()));
                            }
                            ProductGroup productGroup = productGroupService.getOne(Wrappers.lambdaQuery(ProductGroup.class)
                                    .eq(ProductGroup::getMaterialGroup,data.getMaterialGroup())
                                    .eq(ProductGroup::getCategoryCode,data.getCategoryCode()).last(" limit 1")
                            );
                            if (ObjectUtil.isNotEmpty(productGroup)) {
                                throw new DaoException(StrUtil.format("物料组编码：{}，采购品类编码：{}导入重复: ",code,data.getCategoryCode()));
                            }

//                            if (Strings.isNullOrEmpty(String.valueOf(data.getCategoryName()))) {
//                                throw new DaoException("品类名称不能为空!");
//                            }
                            cachedDataList.add(data);
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        }
                    }).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<ProductGroup> productGroups = productGroupConvert.importDTOs2Entites(cachedDataList);
        for (ProductGroup productGroup : productGroups) {
            productGroup.setCreateTime(LocalDateTime.now());
            productGroup.setDisable(1);
            productGroup.setErpStatus(0);
//            dict.setDisable(DelFlag.NORMAL.getStatus());
//            dict.setDisable(disable);
        }
        productGroupService.saveBatch(productGroups);
    }
}
