package com.jwipc.spe.logic.impl;

import cn.hutool.core.util.StrUtil;
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.google.common.collect.Lists;
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.spe.convert.QmAuditManageConvert;
import com.jwipc.spe.dto.QmAuditManageDTO;
import com.jwipc.spe.dto.QmAuditManageImportDTO;
import com.jwipc.spe.entity.QmAuditManage;
import com.jwipc.spe.logic.QmAuditManageLogic;
import com.jwipc.spe.model.po.QmAuditManagePO;
import com.jwipc.spe.model.query.QmAuditManageQuery;
import com.jwipc.spe.service.IQmAuditManageService;
import com.jwipc.supplier.clent.dto.SupplierPurchaseCategoryDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.dto.DictDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
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 QmAuditManageLogicImpl implements QmAuditManageLogic {

    private final IQmAuditManageService qmAuditManageService;
    private final QmAuditManageConvert qmAuditManageConvert;
    private final DictClient dictClient;
    private final SupplierClient supplierClient;
    //列表页面数据
    @Override
    public PageView findByPage(QmAuditManageQuery query) {
        final Page<QmAuditManage> dbPage = PageUtil.toPage(query);

        List<QmAuditManagePO> qmAuditManagePOS = qmAuditManageService.findPageByQuery(dbPage, query);

        return PageUtil.getPV(qmAuditManageConvert.po2PageListDTO(qmAuditManagePOS), dbPage.getTotal());
    }
    //列表主数据
    @Override
    public List<QmAuditManageDTO> listAll(QmAuditManageQuery query) {
        List<QmAuditManagePO> qmAuditManagePOS = qmAuditManageService.findPageByQuery(null, query);
        return qmAuditManageConvert.po2PageListDTO(qmAuditManagePOS);
    }
    //供应商确认保存
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(QmAuditManageDTO param) {
        final String planAudit = param.getPlanAuditTimeStr();
        //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM"); // 指定日期格式
       // final LocalDate parse = LocalDate.parse(planAudit, LocalDateTimeUtil.yyyyMMDash); // 指定日期格式
        //final LocalDate localDate1 = LocalDate.parse(planAudit, formatter);
        //final YearMonth localDate2 = YearMonth.parse(planAudit, formatter);
        YearMonth yearMonth = YearMonth.parse(planAudit, DateTimeFormatter.ofPattern("yyyy-MM")); // 解析年份和月份
        LocalDate localDate = yearMonth.atDay(1);
       // LocalDate localDate = LocalDate.from(localDate1);
        param.setPlanAuditTime(localDate);
        param.setStatus(3);
        param.setUpdateUserId(LoginUtil.getUserId());
        param.setUpdateUserName(LoginUtil.getName());
        param.setUpdateTime(LocalDateTime.now());
//        if(ObjectUtil.isNotNull(param.getNcrAttachment())){
//            param.setStatus(3);
//        }
        qmAuditManageService.saveOrUpdate(qmAuditManageConvert.dto2Entity(param));

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(QmAuditManageDTO param) {
        final String planAudit = param.getPlanAuditTimeStr();
        //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM"); // 指定日期格式
        // final LocalDate parse = LocalDate.parse(planAudit, LocalDateTimeUtil.yyyyMMDash); // 指定日期格式
        //final LocalDate localDate1 = LocalDate.parse(planAudit, formatter);
        //final YearMonth localDate2 = YearMonth.parse(planAudit, formatter);
        YearMonth yearMonth = YearMonth.parse(planAudit, DateTimeFormatter.ofPattern("yyyy-MM")); // 解析年份和月份
        LocalDate localDate = yearMonth.atDay(1);
        // LocalDate localDate = LocalDate.from(localDate1);
        param.setPlanAuditTime(localDate);
        param.setStatus(0);
        param.setUpdateUserId(LoginUtil.getUserId());
        param.setUpdateUserName(LoginUtil.getName());
        param.setUpdateTime(LocalDateTime.now());
        qmAuditManageService.saveOrUpdate(qmAuditManageConvert.dto2Entity(param));

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate1(QmAuditManageDTO param) {
        param.setStatus(1);
        qmAuditManageService.saveOrUpdate(qmAuditManageConvert.dto2Entity(param));

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate2(QmAuditManageDTO param) {
        param.setStatus(2);
        qmAuditManageService.saveOrUpdate(qmAuditManageConvert.dto2Entity(param));

    }

/**
NCR附件上传
 */
    @Override
    public void saveOnFile(Long id, String fileIds) {
        //需要保存现场认证附件
        final List<String> fileIdList = StrUtil.split(fileIds, StrUtil.COMMA);
        //先取数据库中的附件
//        final LambdaQueryWrapper<QmAuditManage> eq =
//                new LambdaQueryWrapper<QmAuditManage>().eq(
//                                QmAuditManage::getNcrAttachment, id);
//        qmAuditManageService.remove(eq);
        List<QmAuditManage> insertLists = Lists.newArrayList();
        if (StrUtil.isEmpty(fileIds)) {
            return;
        }
        //for (String s : fileIdList) {
            QmAuditManage qmAuditManage = qmAuditManageService.getById(id);
            qmAuditManage.setNcrAttachment(fileIds);
            qmAuditManage.setStatus(4);
           // insertLists.add(qmAuditManage);
        //}
        //if (CollUtil.isNotEmpty(insertLists)) {
            qmAuditManageService.saveOrUpdate(qmAuditManage);
       // }
    }

    /**
     稽核附件上传
     */
    @Override
    public void saveOnFile1(Long id, String fileIds) {
//        final LambdaQueryWrapper<QmAuditManage> eq =
//                new LambdaQueryWrapper<QmAuditManage>().eq(
//                        QmAuditManage::getAuditAttachment, auditAtt);
//        qmAuditManageService.remove(eq);
        if (StrUtil.isEmpty(fileIds)) {
            return;
        }
        QmAuditManage qmAuditManage = qmAuditManageService.getById(id);
        qmAuditManage.setAuditAttachment(fileIds);
        qmAuditManageService.saveOrUpdate(qmAuditManage);
    }

//    @Override
//    public ResponseEntity<String> findPCode(String supplierCode, String companyCode) {
//        Pair<String, SupplierPurchaseCategoryDTO> supplierPurchaseCategory = supplierClient.getSupplierPurchaseCategory(supplierCode,null);
//        SupplierPurchaseCategoryDTO supplierPurchaseCategoryDTO = supplierPurchaseCategory.getValue();
//        String purchaseCategoryCode = supplierPurchaseCategoryDTO.getPurchaseCategoryCode();
//        return ResponseEntity.ok(purchaseCategoryCode);
//    }
@Override
public ResponseEntity<String> findPCode(String supplierId) {
    List<SupplierPurchaseCategoryDTO> supplierPurchaseCategoryDTOS =  supplierClient.getList(supplierId);
    // 使用流操作获取指定字段的值，并用逗号隔开
    String values = supplierPurchaseCategoryDTOS.stream()
            .map(SupplierPurchaseCategoryDTO::getPurchaseCategoryName) // 替换成您想要获取的字段的方法引用
            .collect(Collectors.joining(","));
    // 返回包含逗号隔开的字段值的 ResponseEntity
    return ResponseEntity.ok(values);
}
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void itemImportData (MultipartFile fileId) {
        //这个地方需要通过文件id获取文件，然后获取导入的数据
        //查询当前的所有稽核整改明细;
        List<QmAuditManageImportDTO> cachedDataList = ListUtils.newArrayList();
        final List<DictDTO> auditReasonDTO = dictClient.getDicByType(DictCode.AUDIT_REASON.getCode());
        final List<DictDTO> auditResultDTO = dictClient.getDicByType(DictCode.AUDIT_RESULT.getCode());
        //稽核原因
        Map<String, String> mapReason = auditReasonDTO.stream()
                .collect(Collectors.toMap(DictDTO::getName, DictDTO::getCode));
        //可以通过name访问对应的code值
        //String codeValue1 = mapReason.get(name);
        //稽核结果
        Map<String, String> mapResult = auditResultDTO.stream()
                .collect(Collectors.toMap(DictDTO::getName, DictDTO::getCode));
        //可以通过name访问对应的code值
        //String codeValue2 = mapResult.get("不合格");
        try {
//            for (DictDTO dictDTO : auditReasonDTO) {
//                String auditReasonName = dictDTO.getName();
//                if (!cachedDataList.get().equals(auditReasonName)) {
//                    throw new DaoException("稽核原因填写错误，只能是 AVL年度稽核 或者 异常稽核 或者 PCN稽核 或者 新供应商导入稽核！");
//                }
//            }
//            for (DictDTO dictDTO : auditResultDTO) {
//                String auditResultName = dictDTO.getName();
////                if (!cachedDataList.getIsRiskSupplier().equals(auditResultName) ) {
////                    throw new DaoException("稽核结果填写错误，只能是 合格 或者 条件性合格 或者 不合格!");
////                }
//            }
            EasyExcel.read(fileId.getInputStream(), QmAuditManageImportDTO.class, new ReadListener<QmAuditManageImportDTO>() {
                @Override
                public void invoke(QmAuditManageImportDTO data, AnalysisContext context) {
                   // for (QmAuditManageImportDTO importDTO : cachedDataList){
                        //String auditReason = importDTO.getAuditReason();
                        String auditReason = data.getAuditReason();
                        boolean foundMatch = false;
                        for (DictDTO dictDTO : auditReasonDTO) {
                            System.out.println("dsdsdsdsdsd " + auditReason);
                            if(auditReason.equals(dictDTO.getName())) {
                                foundMatch = true;
                                break;
                            }
                        }
                        if (!foundMatch) {
                            // 如果一次循环结束后没有值相等，则抛出异常或执行其他操作
                            throw new RuntimeException("未找到匹配的值: " + auditReason);
                        }
                  //  }
                    final String supplierCode = data.getSupplierCode();

                    //实际稽核时间(LocalDateTime)
                    String actualAuditTime = data.getActualAuditTimeStr();
                    String replace1 = actualAuditTime.replace("/", "-") ;
                    //DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//                    DateTimeFormatter formatter1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                    DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate dateTime1 = LocalDate.parse(replace1, formatter1);
                    data.setActualAuditTime(dateTime1);
                    data.setActualAuditTimeStr(replace1);

                    //计划稽核时间(LocalDate)
                    String planAuditTimeStr = data.getPlanAuditTimeStr();
                    String replace2 = planAuditTimeStr.replace("/", "-") + "-01";
                    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    //DateTimeFormatter formatter2 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                    LocalDate dateTime2 = LocalDate.parse(replace2, formatter2);
                    data.setPlanAuditTime(dateTime2);
                    data.setPlanAuditTimeStr(replace2);

                    //下次稽核时间(LocalDateTime)
                    if(!Objects.isNull(data.getNextAuditTimeStr())){
                        String nextAuditTimeStr = data.getNextAuditTimeStr();
                        String replace3 = nextAuditTimeStr.replace("/", "-") + "T00:00:00";
                        //DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        DateTimeFormatter formatter3 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                        LocalDateTime dateTime3 = LocalDateTime.parse(replace3, formatter3);
                        data.setNextAuditTime(dateTime3);
                        data.setNextAuditTimeStr(replace3);
                    }
                    String codeValue1 = mapReason.get(data.getAuditReason());
                    data.setAuditReason(codeValue1);
                    String codeValue2 = mapResult.get(data.getAuditResult());
                    data.setAuditResult(codeValue2);

                    //是否为风险供应商
                    if(data.getIsRiskSupplierStr().equals("是")){
                        data.setIsRiskSupplier(FlagConst.Y.getCode());
                    }else if(data.getIsRiskSupplierStr().equals("否")){
                        data.setIsRiskSupplier(FlagConst.N.getCode());
                    }

                    if (Strings.isNullOrEmpty(supplierCode)) {
                        throw new DaoException("供应商编码不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getSupplierName())) {
                        throw new DaoException("供应商名称不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getSupplierCode())) {
                        throw new DaoException("供应商代码不能为空!");
                    }
                    //字典
                    if (Strings.isNullOrEmpty(data.getAuditReason())) {
                        throw new DaoException("稽核原因不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getAuditMasterName())) {
                        throw new DaoException("稽核组长不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getPolicyPurchaseName())) {
                        throw new DaoException("策略采购不能为空!");
                    }
                    if (Strings.isNullOrEmpty(data.getPurchaseMasterName())) {
                        throw new DaoException("采购主管不能为空!");
                    }
                    //字典
                    if (Strings.isNullOrEmpty(data.getAuditResult())) {
                        throw new DaoException("稽核结果不能为空!");
                    }
                    //0：是;1：否
                    if (!data.getIsRiskSupplierStr().equals("是") &&
                            !data.getIsRiskSupplierStr().equals("否")) {
                        throw new DaoException("是否为风险供应商填写错误，只能是 是 或者 否!");
                    }
                    if (Objects.isNull(data.getPlanAuditTimeStr())) {
                        throw new DaoException("计划日期未填写!");
                    }
                    //final QmAuditManageImportDTO itHead = createPurchaseOrderDTO.getIT_HEAD();
                    //final String auditReason = data.getAuditReason();

//                    if (Objects.isNull(auditReasonDTO)) {
//                        return ApiResult.builder().message(StrUtil.format("{},稽核原因不存在!", auditReason))
//                                .code(RestCode.SAP_ERROR.getCode()).build();
//                    }
                    cachedDataList.add(data);
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<QmAuditManage> qmAuditManages = qmAuditManageConvert.importDTOs2Entites(cachedDataList);
        for (QmAuditManage qmAuditManage : qmAuditManages) {

            qmAuditManage.setUpdateUserId(LoginUtil.getUserId());
            qmAuditManage.setStatus(3);
            qmAuditManage.setUpdateUserName(LoginUtil.getName());
            qmAuditManage.setUpdateTime(LocalDateTime.now());
            //qmAuditManage.setAuditReason(codeValue);
            //qmAuditManage.setAuditResult(codeValue);
        }
        qmAuditManageService.saveBatch(qmAuditManages);
    }

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

    //根据id查询数据
    @Override
    public QmAuditManageDTO getById(Long id) {
        if (id != null) {
            QmAuditManagePO qmAuditManagePO = qmAuditManageService.getDataById(id);
            return qmAuditManageConvert.po2DTO(qmAuditManagePO);
        }else{
            return new QmAuditManageDTO();
        }
    }
}
