package com.jwipc.sys.logic.impl;

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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.jwipc.constant.DictCode;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.convert.SupplierOrderFileSettingConvert;
import com.jwipc.sys.dto.SupplierOrderFileSettingDTO;
import com.jwipc.sys.dto.SupplierOrderFileSettingImportDTO;
import com.jwipc.sys.entity.SupplierOrderFileSetting;
import com.jwipc.sys.logic.SupplierOrderFileSettingLogic;
import com.jwipc.sys.model.po.DictByTypePO;
import com.jwipc.sys.model.po.SupplierOrderFileSettingPO;
import com.jwipc.sys.model.query.SupplierOrderFileSettingQuery;
import com.jwipc.sys.service.IDictService;
import com.jwipc.sys.service.ISupplierOrderFileSettingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Chen Tianshi
 * @since 2025-08-06 09:34:18
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SupplierOrderFileSettingLogicImpl implements SupplierOrderFileSettingLogic {


    private final IDictService dictService;
    private final ISupplierOrderFileSettingService supplierOrderFileSettingService;
    private final SupplierOrderFileSettingConvert supplierOrderFileSettingConvert;
    private final SupplierClient supplierClient;

    // 搜索数据
    @Override
    public PageView findByPage(SupplierOrderFileSettingQuery query) {
        final Page<SupplierOrderFileSetting> dbPage = PageUtil.toPage(query);

        List<SupplierOrderFileSettingPO> SupplierOrderFileSettingPOS = supplierOrderFileSettingService.findPageByQuery(dbPage, query);

        return PageUtil.getPV(supplierOrderFileSettingConvert.po2PageListDTO(SupplierOrderFileSettingPOS), dbPage==null? 0 : dbPage.getTotal());
    }

    // 查找所有
    @Override
    public List<SupplierOrderFileSettingDTO> listAll(SupplierOrderFileSettingQuery query) {
        List<SupplierOrderFileSettingPO> SupplierOrderFileSettingPOS = supplierOrderFileSettingService.findPageByQuery(null, query);
        return supplierOrderFileSettingConvert.po2PageListDTO(SupplierOrderFileSettingPOS);
    }

    //根据id查询数据
    @Override
    public SupplierOrderFileSettingDTO getById(Long id) {
        if (id != null) {
            SupplierOrderFileSettingPO qmAuditManagePO = supplierOrderFileSettingService.getDataById(id);
            return supplierOrderFileSettingConvert.po2DTO(qmAuditManagePO);
        } else {
            return new SupplierOrderFileSettingDTO();
        }
    }

    //根据供应商编码查询数据
    @Override
    public SupplierOrderFileSettingDTO getBySupplierCode(String supplierCode) {
        if (supplierCode != null) {
            SupplierOrderFileSettingPO qmAuditManagePO = supplierOrderFileSettingService.getDataBySupplierCode(supplierCode);
            return supplierOrderFileSettingConvert.po2DTO(qmAuditManagePO);
        } else {
            return null;
        }
    }

    // 保存
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(SupplierOrderFileSettingDTO param) {

        //检验供应商是否有设置
        SupplierOrderFileSettingPO existCheck = supplierOrderFileSettingService.getDataBySupplierCode(param.getSupplierCode());
        if (existCheck != null && Objects.isNull(param.getId())) {
            throw new DaoException("该供应商已经有设置信息，请找到对应供应商修改");
        }

        SupplierOrderFileSetting supplierOrderFileSetting = supplierOrderFileSettingConvert.dto2Entity(param);
        supplierOrderFileSetting.setUpdateId(LoginUtil.getUserId());
        supplierOrderFileSetting.setUpdateTime(LocalDateTime.now());
        if(Objects.isNull(param.getId())){
            // 新增数据
            supplierOrderFileSetting.setCreateId(LoginUtil.getUserId());
            supplierOrderFileSetting.setCreateTime(LocalDateTime.now());
        }
        supplierOrderFileSettingService.saveOrUpdate(supplierOrderFileSetting);
    }

    // 导入数据
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void itemImportData(MultipartFile fileId) {
        //这个地方需要通过文件id获取文件，然后获取导入的数据
        //查询当前的所有明细;
        List<SupplierOrderFileSettingImportDTO> cachedDataList = ListUtils.newArrayList();
        final List<DictByTypePO> dictByTypePOS = dictService.findDictByType(DictCode.REQUIRED_FLAG.getCode());

        Map<String, String> mapReason = dictByTypePOS.stream()
                .collect(Collectors.toMap(DictByTypePO::getName, DictByTypePO::getCode));
        try {
            EasyExcel.read(fileId.getInputStream(), SupplierOrderFileSettingImportDTO.class, new ReadListener<SupplierOrderFileSettingImportDTO>() {
                @Override
                public void invoke(SupplierOrderFileSettingImportDTO data, AnalysisContext context) {
                    if (Strings.isNullOrEmpty(data.getSupplierCode())) {
                        throw new DaoException("供应商编码不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getRequiredFlag())) {
                        throw new DaoException("出货检验报告是否必填不能为空!");
                    }
                    SupplierDTO supplierDTO = supplierClient.getSupplierByCode(data.getSupplierCode());
                    if (supplierDTO == null) {
                        throw new DaoException("供应商编码为：" + data.getSupplierCode() + "的供应商不存在！");
                    }
                    //0：否;1：是
                    if (!data.getRequiredFlag().equals("是") &&
                            !data.getRequiredFlag().equals("否")) {
                        throw new DaoException("出货检验报告是否必填，请填写“是”或者“否”!");
                    }

                    cachedDataList.add(data);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<SupplierOrderFileSetting> importDataList = supplierOrderFileSettingConvert.importDTOs2Entities(cachedDataList);
        List<SupplierOrderFileSetting> insertDataList = ListUtils.newArrayList();
        for (SupplierOrderFileSetting importData : importDataList) {
            importData.setUpdateId(LoginUtil.getUserId());
            importData.setUpdateTime(LocalDateTime.now());
            SupplierDTO supplierDTO = supplierClient.getSupplierByCode(importData.getSupplierCode());
            importData.setSupplierId(supplierDTO.getId());
            importData.setSupplierName(supplierDTO.getSupplierName());
            // 通过字典转化为统一编码储存
            importData.setRequiredFlag(mapReason.get(importData.getRequiredFlag()));
            SupplierOrderFileSettingPO updateData = supplierOrderFileSettingService.getDataBySupplierCode(importData.getSupplierCode());
            if (updateData == null) {
                // 新数据插入
                importData.setCreateId(LoginUtil.getUserId());
                importData.setCreateTime(LocalDateTime.now());
                insertDataList.add(importData);
            } else {
                importData.setId(updateData.getId());
                supplierOrderFileSettingService.saveOrUpdate(importData);
            }
        }
        supplierOrderFileSettingService.saveBatch(insertDataList);
    }

    // 删除数据
    @Override
    public void remove(Long id) {
        //删除
        supplierOrderFileSettingService.remove(new LambdaQueryWrapper<SupplierOrderFileSetting>().eq(SupplierOrderFileSetting::getId, id));
    }
}
