package com.prolog.cs.biz.outbound.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.prolog.cs.basic.common.model.BaseCommonDict;
import com.prolog.cs.biz.outbound.dao.BillSortRuleMapper;
import com.prolog.cs.biz.outbound.model.BillSortRuleVO;
import com.prolog.cs.biz.outbound.model.dto.BillSortRuleDto;
import com.prolog.cs.biz.outbound.resource.CommonClient;
import com.prolog.cs.biz.outbound.service.BillSortRuleService;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.authority.user.UserTemplate;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.utils.SnowFlakeUtils;
import com.prolog.framework.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @date 2022/7/22   19:33
 */
@Service
public class BillSortRuleServiceImpl implements BillSortRuleService {

    @Autowired
    private BillSortRuleMapper billSortRuleMapper;

    @Autowired
    private UserTemplate userTemplate;

    @Autowired
    private CommonClient commonClient;

    @Override
    public List<BillSortRuleVO> queryBillSortRuleList(BillSortRuleVO billSortRuleVO) {
        Criteria crt = Criteria.forClass(BillSortRuleVO.class);
        Restriction r1 = StringUtils.isBlank(billSortRuleVO.getBillType())? null : Restrictions.eq("billType", billSortRuleVO.getBillType());
        Restriction r2 = StringUtils.isBlank(billSortRuleVO.getDeliverType())? null : Restrictions.eq("deliverType", billSortRuleVO.getDeliverType());
        Restriction r3 = StringUtils.isBlank(billSortRuleVO.getPriorityLevel())? null : Restrictions.eq("priorityLevel", billSortRuleVO.getPriorityLevel());
        crt.setRestriction(Restrictions.and(r1,r2,r3));
        crt.setOrder(Order.newInstance().asc("priority"));
        List<BillSortRuleVO> rsList = billSortRuleMapper.findByCriteria(crt);
        processList(rsList);
        return rsList;
    }

    public void processList(List<BillSortRuleVO> rsList) {
        RestMessage<List<BaseCommonDict>> billTypeList = commonClient.getDictBasicListByCodes("do_bill_type", null);
        Map<String, String> billTypes = new HashMap<>();
        billTypeList.getData().forEach(baseCommonDict -> billTypes.put(baseCommonDict.getDictCode(), baseCommonDict.getDictName()));

        RestMessage<List<BaseCommonDict>> deliverTypeList = commonClient.getDictBasicListByCodes("pub_workstage_delivertype", null);
        Map<String, String> deliverTypes = new HashMap<>();
        deliverTypeList.getData().forEach(baseCommonDict -> deliverTypes.put(baseCommonDict.getDictCode(), baseCommonDict.getDictName()));

        rsList.forEach(x->{
            if (null != x.getBillType()) {
                x.setBillTypeName(billTypes.get(x.getBillType()));
            }
            if (null != x.getDeliverType()) {
                x.setDeliverTypeName(deliverTypes.get(x.getDeliverType()));
            }
            if (null != x.getPriorityLevel()) {
                if (x.getPriorityLevel().equals("1")) {
                    x.setPriorityLevelName("紧急");
                } else if (x.getPriorityLevel().equals("2")) {
                    x.setPriorityLevelName("普通");
                }
            }
        });
    }

    @Override
    public Boolean saveBillSortRule(BillSortRuleDto billSortRuleDto) {
        UserDTO userDTO = userTemplate.getUserDTO();
        List<BillSortRuleVO> insertItems = billSortRuleDto.getInsertItems();
        List<BillSortRuleVO> updateItems = billSortRuleDto.getUpdateItems();
        List<BillSortRuleVO> deleteItems = billSortRuleDto.getDeleteItems();
        List<String> validateList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(insertItems)) {
            for (BillSortRuleVO billSortRuleVO : insertItems) {
                // 重复校验
                List<BillSortRuleVO> rsList = this.queryBillSortRuleList(billSortRuleVO);
                String billTypeName = getValue(billSortRuleVO,"billType");
                if (rsList.size()>0) {
                    throw new ParameterException("保存的数据单据类型:"+billTypeName+"与配送方式:"+billSortRuleVO.getDeliverType()+"的组合重复");
                }
                String key = billSortRuleVO.getBillType()+billSortRuleVO.getDeliverType()+billSortRuleVO.getPriorityLevel();
                if (validateList.size()>0) {
                    if (validateList.contains(key)) {
                        throw new ParameterException("保存的数据单据类型:"+billTypeName+"与配送方式:"+billSortRuleVO.getDeliverType()+"的组合重复");
                    } else {
                        validateList.add(key);
                    }
                } else {
                    validateList.add(key);
                }

                // 保存校验
                billSortRuleVO.setBillSortRuleId(SnowFlakeUtils.getId());
                billSortRuleVO.setGmtCreate(DateUtil.date());
                billSortRuleVO.setCreator(userDTO.getId());
                billSortRuleVO.setCreatorName(userDTO.getUsername());
                billSortRuleVO.setModifier(userDTO.getId());
                billSortRuleVO.setModifierName(userDTO.getUsername());
                billSortRuleVO.setGmtModified(DateUtil.date());
                if (null == billSortRuleVO.getIsEnabled()) {
                    billSortRuleVO.setIsEnabled("1");
                }
            }
            billSortRuleMapper.saveBatch(insertItems);
        }
        if (CollectionUtil.isNotEmpty(updateItems)) {
            for (BillSortRuleVO billSortRuleVO:updateItems) {
                billSortRuleVO.setModifier(userDTO.getId());
                billSortRuleVO.setModifierName(userDTO.getUsername());
                billSortRuleVO.setGmtModified(DateUtil.date());
                billSortRuleMapper.update(billSortRuleVO);
            }
        }
        if (CollectionUtil.isNotEmpty(deleteItems)) {
            for (BillSortRuleVO billSortRuleVO:deleteItems) {
                billSortRuleMapper.deleteById(billSortRuleVO.getBillSortRuleId(), BillSortRuleVO.class);
            }
        }
        return true;
    }

    public String getValue(BillSortRuleVO billSortRuleVO, String type) {
        if (type.equals("billType")) {
            if (null != billSortRuleVO.getBillType()) {
                if (billSortRuleVO.getBillType().equals("1")) {
                    return "销售出库";
                } else if (billSortRuleVO.getBillType().equals("2")) {
                    return "采购退货";
                } else if (billSortRuleVO.getBillType().equals("7")) {
                    return "直通出库";
                }
            }
        }
        return null;
    }
}
