package com.zfire.mall.manager.logic.k3;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.k3.KingDeeMaterialBean;
import com.zfire.mall.manager.bean.k3.RequestApiBean;
import com.zfire.mall.manager.bean.listV2.K3MaterialVO;
import com.zfire.mall.manager.commonmapper.K3Mapper;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.commonmapper.manage.material.ProductComposeReserveMapper;
import com.zfire.mall.manager.constant.KingDeeCons;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.manage.product.category.ProductCategoryLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.KingDeeMaterialService;
import com.zfire.mall.manager.plus.service.KingDeeWalletService;
import com.zfire.mall.manager.plus.service.SaleTypeService;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class K3MaterialLogic {


    @Autowired
    K3Logic k3Logic;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    ProductCategoryLogic productCategoryLogic;
    @Resource
    ProductComposeReserveMapper productComposeReserveMapper;
    @Resource
    KingDeeMaterialService kingDeeMaterialService;
    @Autowired
    KingDeeWalletService kingDeeWalletService;
    @Autowired
    SaleTypeService saleTypeService;
    @Autowired
    K3Mapper k3Mapper;
    @Autowired
    CommonCMapper commonCMapper;

    /**
     * 物料列表
     */
    public IPage<K3MaterialVO> listV2(ZfireParamBean zfireParamBean){
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<K3MaterialVO> k3MaterialVOIPage = commonCMapper.queryK3Material(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return k3MaterialVOIPage;
    }

    /**
     * 查询物料所有单位
     * @return
     */
    public List<KingDeeMaterial> allUnit(){
        List<KingDeeMaterial> kingDeeMaterials = k3Mapper.queryMaterialUnit();
        return kingDeeMaterials;
    }

    /**
     * 查询单位编号
     * @return
     */
    public String queryUnitCode(List<KingDeeMaterial> units,String unit){
//        Map<String, KingDeeMaterial> map = units.stream()
//                .collect(Collectors.toMap(KingDeeMaterial::getBaseUnitCode, v -> v));
        for(KingDeeMaterial material : units){
            if(material.getBaseUnitId().equals(unit)){
                return material.getBaseUnitCode();
            }else if(material.getBaseUnitCode().equals(unit)){
                //兼容旧数据
                return material.getBaseUnitCode();
            }
        }
        return "";
    }


    public List<KingDeeMaterial> allList(){
        return kingDeeMaterialService.list();
    }


    public IPage<KingDeeMaterialBean> list(String number, String oldNumber, String keyword, String specification, Boolean bindMain, Integer pageNum, Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //查询绑定了供应链品类的金蝶物料
        List<String> categoryIds = null;
        if(bindMain != null && bindMain){
            categoryIds = productCategoryLogic.queryCategoryIds();
            if(categoryIds == null){
                return new Page(1,10);
            }
        }
        IPage page = kingDeeMaterialService.lambdaQuery()
                .like(StringUtils.isNotEmpty(number), KingDeeMaterial::getNumber, number)
                .like(StringUtils.isNotEmpty(oldNumber), KingDeeMaterial::getOldNumber, oldNumber)
                .like(StringUtils.isNotEmpty(keyword), KingDeeMaterial::getName, keyword)
                .like(StringUtils.isNotEmpty(specification),KingDeeMaterial::getSpecification,specification)
//                .in(CollectionUtils.isNotEmpty(categoryIds),KingDeeMaterial::getCategoryId,categoryIds)
//                .in(CollectionUtils.isNotEmpty(adminUser.getUseOrgNumbers()), KingDeeMaterial::getUseOrgNumber, adminUser.getUseOrgNumbers())
                .orderByDesc(KingDeeMaterial::getCreateTime).page(new Page<>(pageNum, pageSize));

        List<KingDeeWallet> wallets = kingDeeWalletService.lambdaQuery().eq(KingDeeWallet::getForbidStatus, "A").list();
        List<SaleType> saleTypes = saleTypeService.lambdaQuery().eq(SaleType::getStatus, true).list();

        List<KingDeeMaterialBean> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            KingDeeMaterial kingDeeMaterial = (KingDeeMaterial)o;
            KingDeeMaterialBean bean = new KingDeeMaterialBean();
            BeanUtils.copyProperties(kingDeeMaterial,bean);

            //this.supplyData(kingDeeMaterial.getCategoryId(),bean,wallets,saleTypes);
            bean.setWallets(wallets);
            //可选的销售类型
            bean.setSaleTypes(saleTypes);
            list.add(bean);
        }
        page.setRecords(list);
        return page;
    }


    public KingDeeMaterialBean detail(String id) {
        KingDeeMaterial material = kingDeeMaterialService.getById(id);
        KingDeeMaterialBean bean = new KingDeeMaterialBean();
        BeanUtils.copyProperties(material, bean);
//        bean.setItems(productComposeReserveMapper.getMaterialDetail(id));

        List<KingDeeWallet> wallets = kingDeeWalletService.lambdaQuery().eq(KingDeeWallet::getForbidStatus, "A").list();
        List<SaleType> saleTypes = saleTypeService.lambdaQuery().eq(SaleType::getStatus, true).list();

        this.supplyData(material.getCategoryId(),bean,wallets,saleTypes);
        return bean;
    }

    //补充可选的现金钱包，可选的销售类型
    private KingDeeMaterialBean supplyData(String kingDeeCategoryId,KingDeeMaterialBean bean,List<KingDeeWallet> wallets,List<SaleType> saleTypes){
        ProductCategory productCategory = productComposeReserveMapper.queryOne(kingDeeCategoryId);
        if(productCategory != null) {
            bean.setMainId(productCategory.getProductCategoryId());
            bean.setMainName(productCategory.getProductCategoryName());

            //可选的现金钱包
            //bean.setWallets(wallets.stream().filter(v -> v.getMainId().equals(bean.getMainId())).collect(Collectors.toList()));
            bean.setWallets(wallets);
            //可选的销售类型
            bean.setSaleTypes(saleTypes);
        }
        return bean;
    }

    public void edit(KingDeeMaterialBean kingDeeMaterialBean) {
        if (kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber,kingDeeMaterialBean.getNumber())
                .ne(KingDeeMaterial::getId,kingDeeMaterialBean.getId())
                .count() > 0)
            throw new RemoteServiceException("物料编号存在重复");

        if (kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getOldNumber,kingDeeMaterialBean.getOldNumber())
                .ne(KingDeeMaterial::getId,kingDeeMaterialBean.getId())
                .count() > 0)
            throw new RemoteServiceException("产品编号存在重复");
        kingDeeMaterialBean.updateById();
    }

    public void add(KingDeeMaterial kingDeeMaterial) {
        if (kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber,kingDeeMaterial.getNumber()).count() > 0)
            throw new RemoteServiceException("物料编号存在重复");

        if (kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getOldNumber,kingDeeMaterial.getOldNumber()).count() > 0)
            throw new RemoteServiceException("产品编号存在重复");
        kingDeeMaterial.insert();
    }

    public void importData(List<Object> datas) {


        int index = 1;

        List<KingDeeMaterial> kingDeeMaterials = new ArrayList<>();

        for(Object o : datas) {

            index++;
            List<Object> row = (List<Object>) o;
            if (org.apache.commons.lang3.StringUtils.isEmpty((String) row.get(0)))
                continue;

            KingDeeMaterial kingDeeMaterial = new KingDeeMaterial();
            kingDeeMaterial.setNumber((String) row.get(0));
            kingDeeMaterial.setName((String)row.get(1));
            kingDeeMaterial.setId((String)row.get(0));

            if (com.aliyuncs.utils.StringUtils.isEmpty((String) row.get(0)) || com.aliyuncs.utils.StringUtils.isEmpty((String) row.get(1)))
                throw new RemoteServiceException("第"+index+"行,物料编号名称有误，请检查");

            kingDeeMaterial.setOldNumber((String)row.get(2));
            kingDeeMaterial.setSpecification((String)row.get(3));
            if (com.aliyuncs.utils.StringUtils.isEmpty((String)row.get(4)))
                throw new RemoteServiceException("第"+index+"行,状态填入有误");

            kingDeeMaterial.setForbidStatus(((String)row.get(4)).equals("启用")?"A":"B");

            kingDeeMaterial.setUseOrgId((String)row.get(5));
            kingDeeMaterial.setUseOrgNumber((String)row.get(6));
            kingDeeMaterial.setUseOrgName((String)row.get(7));
            kingDeeMaterial.setCategoryNumber((String)row.get(8));
            kingDeeMaterial.setCategoryName((String)row.get(9));
            kingDeeMaterial.setBaseUnitCode((String)row.get(10));
            kingDeeMaterial.setBaseUnitId((String)row.get(11));
            kingDeeMaterial.setStoreUnitId((String)row.get(12));
            kingDeeMaterial.setStoreUnitCode((String)row.get(13));
            kingDeeMaterial.setSalePriceUnitId((String)row.get(14));
            kingDeeMaterial.setSalePriceUnitCode((String)row.get(15));
            kingDeeMaterial.setPurchasePriceUnitId((String)row.get(16));
            kingDeeMaterial.setPurchasePriceUnitCode((String)row.get(17));

            kingDeeMaterial.setTaxRateId(Convert.toBigDecimal(row.get(18)));

            kingDeeMaterial.setMaterialGroupNumber((String)row.get(19));

            kingDeeMaterial.setMaterialGroupName((String)row.get(20));
            kingDeeMaterial.setLength((BigDecimal) row.get(21));
            kingDeeMaterial.setVolume((BigDecimal)row.get(22));
            kingDeeMaterial.setWidth((BigDecimal)row.get(23));
            kingDeeMaterial.setHeight((BigDecimal)row.get(24));
            kingDeeMaterial.setIsDisplace((StringUtils.isNotEmpty((String)row.get(25)) && ((String)row.get(25)).equals("是"))?true:false);
            kingDeeMaterial.setCostPrice((BigDecimal)row.get(26));
            kingDeeMaterial.setNjdmText((String)row.get(27));
            kingDeeMaterial.setNjxhText((String)row.get(28));
            kingDeeMaterial.setWjdmText((String)row.get(29));
            kingDeeMaterial.setWjxhText((String)row.get(30));
            kingDeeMaterial.setPjdmText((String)row.get(31));
            kingDeeMaterial.setPjxh1Text((String)row.get(32));
            kingDeeMaterial.setPjcspdmText((String)row.get(33));
            kingDeeMaterial.setPjxh2Text((String)row.get(34));

            kingDeeMaterials.add(kingDeeMaterial);

        }

        kingDeeMaterialService.saveOrUpdateBatch(kingDeeMaterials);

    }

    public void del(String id) {
        kingDeeMaterialService.removeById(id);
    }
}
