package com.bonus.canteen.core.supply.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonus.canteen.core.menu.domain.MenuMaterialCategory;
import com.bonus.canteen.core.menu.mapper.MenuMaterialCategoryMapper;
import com.bonus.canteen.core.supply.api.DrpAuthorityApi;
import com.bonus.canteen.core.supply.constant.DrpInquiryStatusEnum;
import com.bonus.canteen.core.supply.constant.DrpQuoteStatusEnum;
import com.bonus.canteen.core.supply.constant.NoticeTemplateKeyEnum;
import com.bonus.canteen.core.supply.domain.DrpInquiry;
import com.bonus.canteen.core.supply.domain.DrpInquirySupplier;
import com.bonus.canteen.core.supply.domain.DrpQuote;
import com.bonus.canteen.core.supply.domain.DrpSupplierApprove;
import com.bonus.canteen.core.supply.dto.*;
import com.bonus.canteen.core.supply.mapper.*;
import com.bonus.canteen.core.supply.po.CategoryModel;
import com.bonus.canteen.core.supply.service.DrpOrderGoodsService;
import com.bonus.canteen.core.supply.service.DrpPurNoticeService;
import com.bonus.canteen.core.supply.service.DrpSupplierManagementService;
import com.bonus.canteen.core.supply.service.DrpSupplierService;
import com.bonus.canteen.core.supply.vo.*;
import com.bonus.canteen.core.utils.FlowBeanUtil;
import com.bonus.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author xliu
 * @date 2025/5/13 16:01
 */
@Service
public class DrpSupplierManagementServiceImpl implements DrpSupplierManagementService {

    @Resource
    private DrpAuthorityApi drpAuthorityApi;
    @Resource
    private DrpInquiryDetailMapper drpInquiryDetailMapper;
    @Resource
    private DrpQuoteInquiryPicMapper drpQuoteInquiryPicMapper;
    @Resource
    private DrpInquiryMapper drpInquiryMapper;
    @Resource
    private DrpOrderGoodsService drpOrderGoodsService;
    @Resource
    private DrpInquirySupplierMapper drpInquirySupplierMapper;
    @Resource
    private DrpQuoteMapper drpQuoteMapper;
    @Resource( name = "smartCanteenTaskExecutor" )
    private AsyncTaskExecutor asyncTaskExecutor;

    @Resource
    private DrpPurNoticeService drpPurNoticeService;

    @Resource
    private DrpSupplierService drpSupplierService;

//    @Autowired
//    private FlowApi flowApi;
    @Resource
    private DrpSupplierApproveMapper drpSupplierApproveMapper;

    @Resource
    private MenuMaterialCategoryMapper menuMaterialCategoryMapper;


    @Override
    public List<DrpQuotePageVO> queryInquiry(DrpQuotePageDTO content) {
        Long supplierAuthority = this.drpAuthorityApi.listSupplierAuthority();
        List<DrpQuotePageVO> records = new ArrayList<>();
        records = this.drpInquiryMapper.selectByQuoteDTO(content, supplierAuthority, DrpInquiryStatusEnum.listNotCommitStatus());
        Iterator var5 = records.iterator();
        while(var5.hasNext()) {
            DrpQuotePageVO drpQuotePageVO = (DrpQuotePageVO)var5.next();
            Long inquirySupplierId = drpQuotePageVO.getInquirySupplierId();
            List<DrpQuoteDetailPageVO> drpQuotePageModels = this.drpInquiryDetailMapper.selectByInquirySupplierId(inquirySupplierId);
            drpQuotePageVO.setDetailList(drpQuotePageModels);
            List<DrpQuoteInquiryPicVO> drpQuoteInquiryPics = this.drpQuoteInquiryPicMapper.selectByInquiryIdAndSupplierId(drpQuotePageVO.getInquiryId(), supplierAuthority);
            drpQuotePageVO.setDrpQuoteInquiryPics(drpQuoteInquiryPics);
        }
        return records;
    }

    @Override
    public List<DrpOrderGoodsPageVO> getDrpOrderGoodsSupplierList(DrpOrderGoodsPageDTO content) {
        return this.drpOrderGoodsService.getDrpOrderGoodsSupplierList(content);
    }

    @Override
    public void commitQuote(DrpQuoteAddDTO content) {
        DrpInquiry drpInquiry = (DrpInquiry)this.drpInquiryMapper.selectOne(Wrappers.lambdaQuery(DrpInquiry.class).eq(DrpInquiry::getInquiryId, content.getInquiryId()).select(DrpInquiry::getEndTime, DrpInquiry::getStartTime, DrpInquiry::getPhone, DrpInquiry::getInquiryId));
        if (LocalDateTime.now().isBefore(drpInquiry.getStartTime())) {
            throw new ServiceException("drp.not-allow-start-quote");
        } else if (LocalDateTime.now().isAfter(drpInquiry.getEndTime())) {
            throw new ServiceException("drp.not-allow-quote");
        } else {
            DrpInquirySupplier drpInquirySupplier = new DrpInquirySupplier();
            BeanUtil.copyProperties(content, drpInquirySupplier, new String[0]);
            drpInquirySupplier.setBidStatus(DrpQuoteStatusEnum.QUOTED.key());
            drpInquirySupplier.setQuoteTime(LocalDateTime.now());
            this.drpInquirySupplierMapper.update(drpInquirySupplier, Wrappers.lambdaQuery(DrpInquirySupplier.class).eq(DrpInquirySupplier::getInquirySupplierId, content.getInquirySupplierId()));
            List<DrpQuoteAddDetailDTO> quoteAddDetailDTOList = content.getDetailList();
            Iterator var5 = quoteAddDetailDTOList.iterator();

            while(var5.hasNext()) {
                DrpQuoteAddDetailDTO quoteAddDetailDTO = (DrpQuoteAddDetailDTO)var5.next();
                DrpQuote quote = new DrpQuote();
                BeanUtil.copyProperties(quoteAddDetailDTO, quote, new String[0]);
                this.drpQuoteMapper.update(quote, Wrappers.lambdaUpdate(DrpQuote.class).eq(DrpQuote::getQuoteId, quote.getQuoteId()));
            }

            this.asyncTaskExecutor.execute(() -> {
                List<DrpInquirySupplier> drpInquirySupplierList = this.drpInquirySupplierMapper.selectList(Wrappers.lambdaQuery(DrpInquirySupplier.class).eq(DrpInquirySupplier::getInquirySupplierId, content.getInquirySupplierId()));
                if (CollUtil.isNotEmpty(drpInquirySupplierList)) {
                    drpInquirySupplierList.forEach((d) -> {
                        this.drpPurNoticeService.sendSmsNoticeGeneral(d.getSupplierId(), drpInquiry.getPhone(), drpInquiry.getInquiryId(), NoticeTemplateKeyEnum.DRP_SUPPLIER_QUOTE.getKey());
                    });
                }

            });
        }
    }


    public DrpSupplierPageVO information(Long supplierId) {
        Long supplierAuthority = this.drpAuthorityApi.listSupplierAuthority();
        List<DrpSupplierPageVO> list = this.drpSupplierService.getDrpSupplierPage((new DrpSupplierPageDTO()).setSupplierId(supplierId != null ? supplierId : supplierAuthority));
//        if (list != null && list.size() >0)) {
//            DrpSupplierPageVO drpSupplierPageVO = list.get(0);
//            List<DrpSupplierApprove> drpSupplierApproveList = this.drpSupplierApproveMapper.selectList((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpSupplierApprove.class).eq(DrpSupplierApprove::getSupplierId, drpSupplierPageVO.getSupplierId())).in(DrpSupplierApprove::getApproveStatus, DrpApproveStatusEnum.getApproveWait()));
//            if (CollUtil.isNotEmpty(drpSupplierApproveList)) {
//                Instance instance = this.flowApi.getInstance(((DrpSupplierApprove)drpSupplierApproveList.get(0)).getProcessInstanceId());
//                Map<String, String> contextMap = instance.getContextMap();
//                Map<String, Object> map = Maps.newHashMap();
//                map.putAll(contextMap);
//                if (ObjectUtil.isNotNull(contextMap.get("categoryIdList"))) {
//                    map.put("categoryIdList", JSONObject.parseArray((String)contextMap.get("categoryIdList"), Long.class));
//                }
//
//                if (ObjectUtil.isNotNull(contextMap.get("mainQualificationList"))) {
//                    map.put("mainQualificationList", JSONObject.parseArray((String)contextMap.get("mainQualificationList"), DrpSupplierQualificationUpdateDTO.class));
//                }
//
//                if (ObjectUtil.isNotNull(contextMap.get("deliverVOList"))) {
//                    map.put("deliverVOList", JSONObject.parseArray((String)contextMap.get("deliverVOList"), DrpSupplierDeliverAddDTO.class));
//                }
//
//                if (ObjectUtil.isNotNull(contextMap.get("otherQualificationList"))) {
//                    map.put("otherQualificationList", JSONObject.parseArray((String)contextMap.get("otherQualificationList"), DrpSupplierQualificationSaveDTO.class));
//                }
//
//                if (ObjectUtil.isNotNull(contextMap.get("attachmentList"))) {
//                    map.put("attachmentList", JSONObject.parseArray((String)contextMap.get("attachmentList"), DrpContractAttachmentDTO.class));
//                }
//
//                DrpSupplierEditDTO drpSupplierEditDTO = (DrpSupplierEditDTO) FlowBeanUtil.convertMapToObject(map, DrpSupplierEditDTO.class);
//                BeanUtil.copyProperties(drpSupplierEditDTO, drpSupplierPageVO, new String[0]);
//                List<Long> categoryIdList = drpSupplierEditDTO.getCategoryIdList();
//                ArrayList deliverVOList = new ArrayList();
//                if (CollUtil.isNotEmpty(categoryIdList)) {
//                    deliverVOList = Lists.newArrayListWithCapacity(categoryIdList.size());
//                    this.menuMaterialCategoryMapper.selectList(Wrappers.lambdaQuery(MenuMaterialCategory.class).in(MenuMaterialCategory::getCategoryId, categoryIdList)).forEach((d) -> {
//                        CategoryModel categoryModel = new CategoryModel();
//                        categoryModel.setCategoryId(d.getCategoryId());
//                        categoryModel.setCategoryName(d.getCategoryName());
//                        deliverVOList.add(categoryModel);
//                    });
//                    drpSupplierPageVO.setCategoryModelList(deliverVOList);
//                }
//
//                if (CollUtil.isNotEmpty(drpSupplierEditDTO.getMainQualificationList())) {
//                    deliverVOList = Lists.newArrayList();
//                    drpSupplierEditDTO.getMainQualificationList().forEach((d) -> {
//                        DrpSupplierQualificationDetailPageVO drpSupplierQualificationDetailPageVO = new DrpSupplierQualificationDetailPageVO();
//                        BeanUtil.copyProperties(d, drpSupplierQualificationDetailPageVO, new String[0]);
//                        deliverVOList.add(drpSupplierQualificationDetailPageVO);
//                    });
//                    drpSupplierPageVO.setMainQualificationList(deliverVOList);
//                }
//
//                if (CollUtil.isNotEmpty(drpSupplierEditDTO.getAttachmentList())) {
//                    deliverVOList = Lists.newArrayList();
//                    drpSupplierEditDTO.getAttachmentList().forEach((d) -> {
//                        DrpContractAttachmentDTO drpContractAttachmentDTO = new DrpContractAttachmentDTO();
//                        BeanUtil.copyProperties(d, drpContractAttachmentDTO, new String[0]);
//                        deliverVOList.add(drpContractAttachmentDTO);
//                    });
//                    drpSupplierPageVO.setAttachmentList(deliverVOList);
//                }
//
//                if (CollUtil.isNotEmpty(drpSupplierEditDTO.getOtherQualificationList())) {
//                    deliverVOList = Lists.newArrayList();
//                    drpSupplierEditDTO.getOtherQualificationList().forEach((d) -> {
//                        DrpSupplierQualificationDetailPageVO drpSupplierQualificationDetailPageVO = new DrpSupplierQualificationDetailPageVO();
//                        BeanUtil.copyProperties(d, drpSupplierQualificationDetailPageVO, new String[0]);
//                        deliverVOList.add(drpSupplierQualificationDetailPageVO);
//                    });
//                    drpSupplierPageVO.setOtherQualificationList(deliverVOList);
//                }
//
//                if (CollUtil.isNotEmpty(drpSupplierEditDTO.getDeliverVOList())) {
//                    deliverVOList = Lists.newArrayList();
//                    drpSupplierEditDTO.getDeliverVOList().forEach((d) -> {
//                        DrpSupplierDeliverVO drpSupplierDeliverVO = new DrpSupplierDeliverVO();
//                        BeanUtil.copyProperties(d, drpSupplierDeliverVO, new String[0]);
//                        deliverVOList.add(drpSupplierDeliverVO);
//                    });
//                    drpSupplierPageVO.setDeliverVOList(deliverVOList);
//                }
//
//                return drpSupplierPageVO;
//            }
//        }

        return list != null && list.size()>0 ? list.get(0) : null;
    }

}
