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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.manage.material.ProductComposeBean;
import com.zfire.mall.manager.bean.manage.material.ProductComposeListBean;
import com.zfire.mall.manager.commonmapper.manage.material.ProductComposeReserveMapper;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.KingDeeMaterial;
import com.zfire.mall.manager.plus.entity.ProductCompose;
import com.zfire.mall.manager.plus.entity.ProductComposeRela;
import com.zfire.mall.manager.plus.service.KingDeeMaterialService;
import com.zfire.mall.manager.plus.service.MachineConfigureRecordService;
import com.zfire.mall.manager.plus.service.ProductComposeRelaService;
import com.zfire.mall.manager.plus.service.ProductComposeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductComposeLogic {
    @Resource
    CommonLogic commonLogic;
    @Resource
    ProductComposeReserveMapper productComposeReserveMapper;
    @Resource
    ProductComposeService productComposeService;
    @Resource
    ProductComposeRelaService productComposeRelaService;
    @Resource
    KingDeeMaterialService kingDeeMaterialService;
    @Resource
    MachineConfigureRecordService machineConfigureRecordService;

    public IPage<ProductComposeListBean> listPage(String name, String type, String number, BigDecimal volume,
                                                  String machineType, String machineName, String machineModel,
                                                  String machineNumber, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String adminCompanyId = adminUser.getAdminCompanyId();
        return productComposeReserveMapper.listPage(new Page<>(pageNum, pageSize), name, type, number, volume,
                machineType, machineName, machineModel, machineNumber, adminCompanyId);
    }

    public ExcelData export(List<ProductComposeListBean> records) {
        String[] titles = new String[]{"产品名称","产品型号","套机编码","套机体积","类型", "名称", "编码", "型号","体积"};
        List<List<Object>> rows = new ArrayList<>();
        for (ProductComposeListBean bean : records) {
            List<Object> row = new ArrayList<>();
            row.add(bean.getMaterialName());
            row.add(bean.getProductModel());
            row.add(bean.getComposeNumber());
            row.add(bean.getProductVolume());
            row.add(bean.getType());
            row.add(bean.getName());
            row.add(bean.getNumber());
            row.add(bean.getModel());
            row.add(bean.getVolume());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public ProductComposeBean detail(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getAdminCompanyIds();
        return productComposeReserveMapper.detail(id, adminCompanyIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(ProductComposeBean productComposeBean) throws RemoteServiceException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        productComposeBean.setAdminCompanyId(adminUser.getAdminCompanyId());
        KingDeeMaterial material = this.findMaterialById(adminUser, productComposeBean.getMaterialId());
        if (Objects.isNull(material)) {
            throw new RemoteServiceException("产品不存在");
        }

        ProductCompose productCompose = new ProductCompose();
        BeanUtils.copyProperties(productComposeBean, productCompose);
        productCompose.setCreateName(adminUser.getNickName());
        productCompose.setUpdateName(adminUser.getNickName());
        productCompose.insert();
        productComposeBean.getItems().forEach(item -> item.setParentId(productCompose.getId()));
        productComposeRelaService.saveBatch(productComposeBean.getItems());

        material.setIsSheath(true)
                .updateById();
    }

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

        ProductCompose productCompose = productComposeService.lambdaQuery()
                .eq(ProductCompose::getAdminCompanyId, adminUser.getAdminCompanyId())
                .eq(ProductCompose::getId, productComposeBean.getId())
                .one();

        if (Objects.isNull(productCompose)) {
            throw new RemoteServiceException("产品关系不存在");
        }

        productCompose.setUpdateName(adminUser.getNickName())
                .updateById();

        productComposeBean.getItems().forEach(item -> item.setParentId(productCompose.getId()));
        productComposeRelaService.lambdaUpdate()
                .eq(ProductComposeRela::getParentId, productCompose.getId())
                .remove();
        productComposeRelaService.saveBatch(productComposeBean.getItems());

        commonLogic.saveLog(productComposeBean.getId());
    }

    private KingDeeMaterial findMaterialById(AdminUserCom adminUser, String id) {
        Integer count = productComposeService.lambdaQuery()
                .eq(ProductCompose::getAdminCompanyId, adminUser.getAdminCompanyId())
                .eq(ProductCompose::getMaterialId, id)
                .count();

        if (count > 0) {
            throw new RemoteServiceException("已存在产品关系，不能重复维护产品关系");
        }

        return kingDeeMaterialService.lambdaQuery()
                .eq(KingDeeMaterial::getUseOrgNumber, adminUser.getUseOrgNumber())
                .eq(KingDeeMaterial::getId, id)
                .one();
    }

    public void del(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        productComposeService.lambdaUpdate().in(ProductCompose::getAdminCompanyId, adminUser.getAdminCompanyIds())
                .in(ProductCompose::getId, ids.stream().distinct().collect(Collectors.toList()))
                .remove();
    }


}
