package com.scm.contract.service.purchase;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.scm.contract.dao.purchase.TagPurchaseDao;
import com.scm.contract.model.apply.DictionaryTagType;
import com.scm.contract.model.apply.LabelApplication;
import com.scm.contract.model.purchase.DictionaryTagPurchaseState;
import com.scm.contract.model.purchase.TagProvider;
import com.scm.contract.model.purchase.TagPurchase;
import com.scm.contract.model.purchase.TagPurchaseDetail;
import com.scm.contract.service.apply.DictionaryTagTypeService;
import com.scm.contract.service.management.TagDataService;
import com.scm.contract.tools.InSnowflakeIdGenerator;
import com.scm.contract.tools.OutSnowflakeIdGenerator;
import com.scm.contract.tools.Tools;
import com.set.direwolf.core.entity.User;
import com.set.direwolf.core.mybatis.CrudService;
import com.set.direwolf.core.mybatis.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zuo
 * @date 2024/6/4 17:46
 */
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class TagPurchaseService extends CrudService<TagPurchaseDao, TagPurchase, String> {

    @Autowired
    private DictionaryTagTypeService tagTypeService;

    @Autowired
    private TagProviderService tagProviderService;

    @Autowired
    private TagPurchaseDetailService detailService;

    @Autowired
    private DictionaryTagPurchaseStateService tagPurchaseStateService;

    @Autowired
    private InSnowflakeIdGenerator inSnowflakeIdGenerator;

    public void setName(List<TagPurchase> list, Boolean isHaveDetail) {
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> tagPurchaseIds = new ArrayList<>();
            Set<String> providerIdSet = new HashSet<>();
            Set<String> tagPurchaseStateSet = new HashSet<>();
            for (TagPurchase tagPurchase : list) {
                tagPurchaseIds.add(tagPurchase.getId());
                String providerId = tagPurchase.getProviderId();
                if (StringUtils.isNotBlank(providerId)) {
                    providerIdSet.add(providerId);
                }
                String tagPurchaseStateId = tagPurchase.getTagPurchaseStateId();
                if (StringUtils.isNotBlank(tagPurchaseStateId)) {
                    tagPurchaseStateSet.add(tagPurchaseStateId);
                }
            }

            //获取供应商信息Map
            Map<String, TagProvider> tagProviderMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(providerIdSet)) {
                List<TagProvider> tagProviders = tagProviderService.listByIds(new ArrayList<>(providerIdSet));
                if (CollectionUtils.isNotEmpty(tagProviders)) {
                    for (TagProvider tagProvider : tagProviders) {
                        tagProviderMap.put(tagProvider.getId(), tagProvider);
                    }
                }
            }

            //获取采购订单状态Map
            Map<String, DictionaryTagPurchaseState> tagPurchaseStateMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(tagPurchaseStateSet)) {
                List<DictionaryTagPurchaseState> tagPurchaseStates = tagPurchaseStateService.listByIds(new ArrayList<>(tagPurchaseStateSet));
                if (CollectionUtils.isNotEmpty(tagPurchaseStates)) {
                    for (DictionaryTagPurchaseState state : tagPurchaseStates) {
                        tagPurchaseStateMap.put(state.getId(), state);
                    }
                }
            }

            //获取从表信息Map
            Map<String, List<TagPurchaseDetail>> detailMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(tagPurchaseIds)) {
                List<TagPurchaseDetail> details = detailService.getListByTagPurchaseIds(tagPurchaseIds);
                if (CollectionUtils.isNotEmpty(details)) {
                    for (TagPurchaseDetail detail : details) {
                        String tagPurchaseId = detail.getTagPurchaseId();
                        if (!detailMap.containsKey(tagPurchaseId)) {
                            detailMap.put(tagPurchaseId, new ArrayList<>());
                        }
                        detailMap.get(tagPurchaseId).add(detail);
                    }
                }
            }

            for (TagPurchase tagPurchase : list) {
                //设置供应商名字
                String providerId = tagPurchase.getProviderId();
                if (StringUtils.isNotBlank(providerId)) {
                    TagProvider provider = tagProviderMap.getOrDefault(providerId, new TagProvider());
                    tagPurchase.setProviderName(provider.getName());
                }
                //设置采购订单状态
                String tagPurchaseStateId = tagPurchase.getTagPurchaseStateId();
                if (StringUtils.isNotBlank(tagPurchaseStateId)) {
                    DictionaryTagPurchaseState tagPurchaseState = tagPurchaseStateMap.getOrDefault(tagPurchaseStateId, new DictionaryTagPurchaseState());
                    tagPurchase.setTagPurchaseStateName(tagPurchaseState.getName());
                }
                //设置总额
                String id = tagPurchase.getId();
                List<TagPurchaseDetail> details = detailMap.get(id);
                if (CollectionUtils.isNotEmpty(details)) {
                    Double amountSum = null;
                    Long tagNumber = null;
                    for (TagPurchaseDetail detail : details) {
                        Double amount = detail.getAmount();
                        if (!Objects.isNull(amount)) {
                            if (Objects.isNull(amountSum)) {
                                amountSum = amount;
                            } else {
                                amountSum += amount;
                            }
                        }
                        Long number = detail.getNumber();
                        if (!Objects.isNull(number)) {
                            if (Objects.isNull(tagNumber)) {
                                tagNumber = number;
                            } else {
                                tagNumber += number;
                            }
                        }
                    }
                    if (!Objects.isNull(amountSum)) {
                        amountSum = Tools.digitHalfEven(amountSum, 2);
                    }
                    tagPurchase.setAmount(amountSum);
                    tagPurchase.setTagNumber(tagNumber);
                    if (isHaveDetail) {
                        tagPurchase.setDetails(details);
                    }
                }
            }
        }
    }


    @Override
    public Page<TagPurchase> findPage(Page<TagPurchase> page, TagPurchase entity) {
        entity.setPage(page);
        page.setList(this.dao.findList(entity));
        List<TagPurchase> list = page.getList();
        setName(list, false);
        return page;
    }

    @Transactional
    public synchronized void save(TagPurchase tagPurchase) {
        String providerId = tagPurchase.getProviderId();
        List<TagPurchaseDetail> details = tagPurchase.getDetails();
        if (StringUtils.isBlank(providerId)) throw new RuntimeException("标签供应商id不能为空");
        if (CollectionUtils.isEmpty(details)) throw new RuntimeException("订单至少需要设置一个标签");

        User user = Tools.getUser();
        Date date = new Date();


        String idStr = IdWorker.getIdStr();
        tagPurchase.setId(idStr);
        tagPurchase.setOrderNo(inSnowflakeIdGenerator.generateId());
        tagPurchase.setBuyerId(user.getId());
        tagPurchase.setBuyerName(user.getNickName());
        tagPurchase.setDataTime(date);
        tagPurchase.setTagPurchaseStateId("0");
//            tagPurchase.setReceiveDate("0");
//            tagPurchase.setProviderId("0");


        List<String> tagTypeIds = details.stream().map(TagPurchaseDetail::getTagTypeId).distinct().collect(Collectors.toList());
        List<DictionaryTagType> types = tagTypeService.listByIds(tagTypeIds);
        Map<String, DictionaryTagType> tagTypeMap = new HashMap<>();
        for (DictionaryTagType type : types) {
            tagTypeMap.put(type.getId(),type);
        }
        for (TagPurchaseDetail detail : details) {
            Long number = detail.getNumber();
            if (Objects.isNull(number)) throw new RuntimeException("标签里缺少需求数量");
            String tagTypeId = detail.getTagTypeId();
            DictionaryTagType tagType = tagTypeMap.get(tagTypeId);
            if (Objects.isNull(tagType)) throw new RuntimeException("标签里缺少标签类型id");
            detail.setUnitPrice(tagType.getPrice());
            detail.setTagPurchaseId(idStr);
        }
        this.dao.save(tagPurchase);
        detailService.saveList(details);
        tagDataService.saveOrUpdateBash(null, Collections.singletonList(tagPurchase),null, true);
    }

    @Transactional
    public synchronized Boolean update(TagPurchase entity) {
        String id = entity.getId();
        if (StringUtils.isBlank(id)) throw new RuntimeException("修改失败，没有传id");
        TagPurchase purchase = this.dao.getById(id);
        String tagPurchaseStateId = purchase.getTagPurchaseStateId();
        if ("1".equals(tagPurchaseStateId)) throw new RuntimeException("已完成订单无法修改");
        List<TagPurchaseDetail> details = entity.getDetails();
        tagDataService.saveOrUpdateBash(null, Collections.singletonList(entity),null, false);
        detailService.deleteListByTagPurchaseId(id);
        if (CollectionUtils.isEmpty(details)){
            this.dao.delete(id);
        }else {
            this.dao.update(entity);
            detailService.saveList(details);
        }
        return true;
    }

    @Autowired
    private TagDataService tagDataService;

    @Transactional
    public synchronized void inStorage(List<String> ids) {
        List<TagPurchase> tagPurchases = this.dao.getByIds(ids);
        for (TagPurchase tagPurchase : tagPurchases) {
            String tagPurchaseStateId = tagPurchase.getTagPurchaseStateId();
            if (!"0".equals(tagPurchaseStateId)){
                throw new RuntimeException("已經完成的订单不能再次完成");
            }
        }
        //修改状态为完成
        this.dao.tagPurchaseStateIdUpdate(ids, "1");
        //修改庫存，并检查修改告警状态
        tagDataService.saveOrUpdateBash(null, tagPurchases,null, true);
    }

    public List<TagPurchase> getListByIds(List<String> ids){
        return this.dao.getByIds(ids);
    }

    public TagPurchase getById(String id, Boolean isHaveDetail) {
        TagPurchase tagPurchase = this.dao.getById(id);
        if (!Objects.isNull(tagPurchase)){
            setName(Collections.singletonList(tagPurchase),isHaveDetail);
        }
        return tagPurchase;
    }

    public String getMaxOrderNo() {
        return this.dao.getMaxOrderNo();
    }

    @Transactional
    public synchronized Boolean deleteById(String id) {
        TagPurchase entity = getById(id, false);
        entity.setDetails(new ArrayList<>());
        return update(entity);
    }
}
