package com.jwipc.sys.logic.impl;

import cn.hutool.core.util.ObjectUtil;
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.constant.FlagConst;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.sys.convert.SupplierEmailConvert;
import com.jwipc.sys.dto.SupplierEmailDTO;
import com.jwipc.sys.dto.SupplierEmailImportDTO;
import com.jwipc.sys.entity.SupplierEmail;
import com.jwipc.sys.logic.SupplierEmailLogic;
import com.jwipc.sys.model.po.DictByTypePO;
import com.jwipc.sys.model.po.SupplierEmailPO;
import com.jwipc.sys.model.query.SupplierEmailQuery;
import com.jwipc.sys.service.IDictService;
import com.jwipc.sys.service.ISupplierEmailService;
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 Al
 * @create 2024-03-19 17:02
 * 稽核整改
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SupplierEmailLogicImpl implements SupplierEmailLogic {


    private final IDictService dictService;
    private final ISupplierEmailService supplierEmailService;
    private final SupplierEmailConvert supplierEmailConvert;

    //列表页面数据
    @Override
    public PageView findByPage(SupplierEmailQuery query) {
        final Page<SupplierEmail> dbPage = PageUtil.toPage(query);

        List<SupplierEmailPO> supplierEmailPOS = supplierEmailService.findPageByQuery(dbPage, query);

        return PageUtil.getPV(supplierEmailConvert.po2PageListDTO(supplierEmailPOS), dbPage.getTotal());
    }

    //列表主数据
    @Override
    public List<SupplierEmailDTO> listAll(SupplierEmailQuery query) {
        List<SupplierEmailPO> supplierEmailPOS = supplierEmailService.findPageByQuery(null, query);
        return supplierEmailConvert.po2PageListDTO(supplierEmailPOS);
    }

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

        if(Objects.isNull(param.getId())){
            param.setCreateUser(LoginUtil.getUserId());
            param.setCreateTime(LocalDateTime.now());
            supplierEmailService.saveOrUpdate(supplierEmailConvert.dto2Entity(param));
        }
        List<SupplierEmailDTO> supplierEmailDTOS = supplierEmailConvert.po2PageListDTO(supplierEmailService.selectAllUser(param.getSupplierCode()));
        if (ObjectUtil.isNotNull(supplierEmailDTOS) && !supplierEmailDTOS.isEmpty()) {
            for (SupplierEmailDTO supplierEmailDTO : supplierEmailDTOS) {
                if (supplierEmailDTO.getSupplierCode().equals(param.getSupplierCode())) {
                    supplierEmailDTO.setPuserCode(param.getPuserCode());
                    supplierEmailDTO.setPuserName(param.getPuserName());
                    supplierEmailDTO.setSqe(param.getSqe());
                    supplierEmailDTO.setSqeName(param.getSqeName());
                    supplierEmailDTO.setCe(param.getCe());
                    supplierEmailDTO.setCeName(param.getCeName());
                    supplierEmailDTO.setPurchaseCategoryName(param.getPurchaseCategoryName());
                }
                supplierEmailService.saveOrUpdate(supplierEmailConvert.dto2Entity(supplierEmailDTO));
            }
        }
//        else {
//            supplierEmailService.saveOrUpdate(supplierEmailConvert.dto2Entity(param));
//        }


    }

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

        Map<String, String> mapReason = dictByTypePOS.stream()
                .collect(Collectors.toMap(DictByTypePO::getName, DictByTypePO::getCode));
        //可以通过name访问对应的code值
        //String codeValue2 = mapResult.get("不合格");
        try {
            EasyExcel.read(fileId.getInputStream(), SupplierEmailImportDTO.class, new ReadListener<SupplierEmailImportDTO>() {
                @Override
                public void invoke(SupplierEmailImportDTO data, AnalysisContext context) {
//                    String supplierType = String.valueOf(data.getSupplierType());
//                    boolean foundMatch = false;
//                    for (DictByTypePO dictByTypePO : dictByTypePOS) {
//                        System.out.println("dsdsdsdsdsd " + supplierType);
//                        if (supplierType.equals(dictByTypePO.getName())) {
//                            foundMatch = true;
//                            break;
//                        }
//                    }
//                    if (!foundMatch) {
//                        // 如果一次循环结束后没有值相等，则抛出异常或执行其他操作
//                        throw new RuntimeException("未找到匹配的值: " + supplierType);
//                    }
//                    String codeValue1 = mapReason.get(data.getSupplierType());
//                    data.setSupplierType(codeValue1);
                    //0：内部;1：外部
                    if (!data.getEmailType().equals("内部") &&
                            !data.getEmailType().equals("外部")) {
                        throw new DaoException("邮件类型填写错误，只能是 内部 或者 外部!");
                    }
//                    if (!data.getDefaultFlag().equals("默认") &&
//                            !data.getDefaultFlag().equals("不默认")) {
//                        throw new DaoException("是否默认填写错误，只能是 默认 或者 不默认!");
//                    }
                    //邮件类型0：内部1：外部
                    if (data.getEmailType().equals("外部")) {
                        data.setEmailType(String.valueOf(FlagConst.Y.getCode()));
                    } else if (data.getEmailType().equals("内部")) {
                        data.setEmailType(String.valueOf(FlagConst.N.getCode()));
                    }
//                    if (data.getDefaultFlag().equals("默认")) {
//                        data.setDefaultFlag(String.valueOf(FlagConst.Y.getCode()));
//                    } else if (data.getDefaultFlag().equals("不默认")) {
//                        data.setDefaultFlag(String.valueOf(FlagConst.N.getCode()));
//                    }
                    if (Strings.isNullOrEmpty(data.getSupplierName())) {
                        throw new DaoException("供应商名称不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getPuserCode())) {
                        throw new DaoException("采购用户名称不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getPuserName())) {
                        throw new DaoException("采购用户编码不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getSupplierCode())) {
                        throw new DaoException("供应商编码不能为空!");
                    }
//                    if (Strings.isNullOrEmpty(String.valueOf(data.getDefaultFlag()))) {
//                        throw new DaoException("是否默认不能为空!");
//                    }
                    //字典
                    if (Strings.isNullOrEmpty(data.getEmail())) {
                        throw new DaoException("邮箱不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getEmailType())) {
                        throw new DaoException("邮箱类型不能为空!");
                    }
//                    if (Strings.isNullOrEmpty(String.valueOf(data.getSupplierType()))) {
//                        throw new DaoException("供应商邮箱类型不能为空!");
//                    }

                    cachedDataList.add(data);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<SupplierEmail> supplierEmails = supplierEmailConvert.importDTOs2Entites(cachedDataList);
        List<SupplierEmail> supplierEmails1 = supplierEmailService.list();

        for (SupplierEmail supplierEmail : supplierEmails) {
            supplierEmail.setCreateUser(LoginUtil.getUserId());
            supplierEmail.setCreateTime(LocalDateTime.now());
            for (SupplierEmail supplierEmailDTO : supplierEmails1) {
                if (supplierEmailDTO.getSupplierCode().equals(supplierEmail.getSupplierCode())) {
                    supplierEmailDTO.setPuserCode(supplierEmail.getPuserCode());
                    supplierEmailDTO.setPuserName(supplierEmail.getPuserName());
                    supplierEmailDTO.setSqe(supplierEmail.getSqe());
                    supplierEmailDTO.setSqeName(supplierEmail.getSqeName());
                    supplierEmailDTO.setCe(supplierEmail.getCe());
                    supplierEmailDTO.setCeName(supplierEmail.getCeName());
                    supplierEmailDTO.setPurchaseCategoryName(supplierEmail.getPurchaseCategoryName());
                }
                supplierEmailService.saveOrUpdate(supplierEmailDTO);
            }
//            if (supplierEmail.getSupplierCode().equals(data.getSupplierCode())) {
//                supplierEmail.setPuserCode(data.getPuserCode());
//                supplierEmail.setPuserName(data.getPuserName());
//            }
        }
        supplierEmailService.saveBatch(supplierEmails);
    }


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

    //根据id查询数据
    @Override
    public SupplierEmailDTO getById(Long id) {
        if (id != null) {
            SupplierEmailPO qmAuditManagePO = supplierEmailService.getDataById(id);
            return supplierEmailConvert.po2DTO(qmAuditManagePO);
        } else {
            return new SupplierEmailDTO();
        }
    }
}
