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

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.base.PartsBaseVO;
import com.gree.mall.manager.commonmapper.MaterialMapper;
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.MaterialConfig;
import com.gree.mall.manager.plus.entity.WebsitPartsBase;
import com.gree.mall.manager.plus.service.MaterialConfigService;
import com.gree.mall.manager.plus.service.WebsitGoodsService;
import com.gree.mall.manager.plus.service.WebsitPartsBaseService;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class PartsBaseLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WebsitPartsBaseService websitPartsBaseService;
    private final WebsitGoodsService websitGoodsService;
    private final MaterialConfigService materialConfigService;


    public IPage<PartsBaseVO> page(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, PartsBaseVO.class, adminUser);
        return materialMapper.partsBasePage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public WebsitPartsBase detail(String id) {
        return websitPartsBaseService.getById(id);
    }


    public void add(WebsitPartsBase websitPartsBase) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (StringUtils.isBlank(websitPartsBase.getType())) {
            throw new RemoteServiceException("类型不能为空");
        }
        if (StringUtils.isBlank(websitPartsBase.getValue())) {
            throw new RemoteServiceException("名称不能为空");
        }

        String val = websitPartsBase.getValue().trim().toUpperCase();
        WebsitPartsBase baseManage = websitPartsBaseService.lambdaQuery()
                .eq(WebsitPartsBase::getType, websitPartsBase.getType())
                .eq(WebsitPartsBase::getValue, val)
                .one();
        if (Objects.nonNull(baseManage)) {
            throw new RemoteServiceException("名称已存在,添加失败");
        }

        websitPartsBase.setId(null)
                .setCompanyWechatId(adminUser.getCompanyWechatId())
                .setValue(val);
        websitPartsBase.insert();
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(WebsitPartsBase websitPartsBase) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (StringUtils.isBlank(websitPartsBase.getType())) {
            throw new RemoteServiceException("类型不能为空");
        }
        if (StringUtils.isBlank(websitPartsBase.getValue())) {
            throw new RemoteServiceException("名称不能为空");
        }
        String val = websitPartsBase.getValue().trim().toUpperCase();
        WebsitPartsBase baseManage = websitPartsBaseService.lambdaQuery()
                .eq(WebsitPartsBase::getType, websitPartsBase.getType())
                .eq(WebsitPartsBase::getValue, val)
                .ne(WebsitPartsBase::getId, websitPartsBase.getId())
                .one();
        if (Objects.nonNull(baseManage)) {
            throw new RemoteServiceException("名称已存在,编辑失败");
        }

        // 查出历史记录
        baseManage = websitPartsBaseService.getById(websitPartsBase.getId());

        websitPartsBaseService.lambdaUpdate()
                .set(WebsitPartsBase::getValue, val)
                .set(WebsitPartsBase::getUpdateBy, adminUser.getNickName())
                .set(WebsitPartsBase::getUpdateTime, DateUtil.date())
                .eq(WebsitPartsBase::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(WebsitPartsBase::getId, websitPartsBase.getId())
                .update();

        // 对比历史记录不相同更新配件资料
        if (!baseManage.getValue().equals(websitPartsBase.getValue())) {
//            websitGoodsService.lambdaUpdate()
//                    .set(baseManage.getType().equals(PartBaseTypeEnum.UNIT.getKey()), WebsitGoods::getPartsUnitName, websitPartsBase.getValue())
//                    .eq(WebsitGoods::getCompanyWechatId, adminUser.getCompanyWechatId())
//                    .eq(baseManage.getType().equals(PartBaseTypeEnum.UNIT.getKey()), WebsitGoods::getPartsUnitId, websitPartsBase.getId())
//                    .update();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void importManage(List<Object> objects, String type) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Map<String, WebsitPartsBase> PartsBaseManageMap = new HashMap<>();
        for(Object o : objects) {
            List<Object> row = (List<Object>) o;
            String value = (String) row.get(0);
            String stateStr = (String) row.get(1);
            String state = stateStr.trim().equals("有效") ? StateEnum.ON.getKey() : StateEnum.OFF.getKey();
            if (StringUtils.isBlank(value)) {
                throw new RemoteServiceException("名称不能为空");
            }
            value = value.trim().toUpperCase();
            WebsitPartsBase partsBaseManage = new WebsitPartsBase();
            partsBaseManage.setId(null)
                    .setCompanyWechatId(adminUser.getCompanyWechatId())
                    .setType(type)
                    .setValue(value)
                    .setStatus(state);
            PartsBaseManageMap.put(type + value, partsBaseManage);
        }

        List<String> valList = PartsBaseManageMap.values().stream()
                .map(WebsitPartsBase::getValue)
                .collect(Collectors.toList());

        Integer count = websitPartsBaseService.lambdaQuery()
                .eq(WebsitPartsBase::getType, type)
                .eq(WebsitPartsBase::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(WebsitPartsBase::getValue, valList)
                .count();

        if (count > 0) {
            throw new RemoteServiceException("发现导入的名称中已存在相同记录");
        }

        websitPartsBaseService.saveBatch(PartsBaseManageMap.values());
    }

    public MaterialConfig config() {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        MaterialConfig config = materialConfigService.lambdaQuery()
                .eq(MaterialConfig::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .one();

        config.setWorkerGoodsIncrId(0);

        return config;
    }

    public void configEdit(MaterialConfig materialConfig) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        materialConfigService.lambdaUpdate()
                .set(Objects.nonNull(materialConfig.getPriceRate1()) && materialConfig.getPriceRate1().compareTo(BigDecimal.ONE) > 0, MaterialConfig::getPriceRate1, materialConfig.getPriceRate1())
                .set(Objects.nonNull(materialConfig.getPriceRate2()) && materialConfig.getPriceRate2().compareTo(BigDecimal.ONE) > 0, MaterialConfig::getPriceRate2, materialConfig.getPriceRate2())
                .set(Objects.nonNull(materialConfig.getPriceRate3()) && materialConfig.getPriceRate3().compareTo(BigDecimal.ONE) > 0, MaterialConfig::getPriceRate3, materialConfig.getPriceRate3())
                .set(MaterialConfig::getUpdateBy, adminUser.getNickName())
                .set(MaterialConfig::getUpdateTime, DateUtil.date())
                .eq(MaterialConfig::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .update();
    }
}
