package com.prolog.rdc.tms.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.prolog.framework.core.pojo.Page;
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.dao.util.PageUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.product.core.tools.util.JsonMapper;
import com.prolog.rdc.tms.constant.BmsConstant;
import com.prolog.rdc.tms.dao.mapper.MergeBillStrategyMapper;
import com.prolog.rdc.tms.model.dto.BmsMergeStrategyDTO;
import com.prolog.rdc.tms.model.entity.BmsMergeBillStrategyModel;
import com.prolog.rdc.tms.model.entity.SysRefdatadModel;
import com.prolog.rdc.tms.model.vo.BmsMergeStrategyQueryVO;
import com.prolog.rdc.tms.model.vo.BmsMergeStrategyVO;
import com.prolog.rdc.tms.model.vo.StatusUpdate;
import com.prolog.rdc.tms.service.MergeBillStrategyService;
import com.prolog.rdc.tms.util.ConvertorUtil;
import org.apache.ibatis.plugin.PluginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MergeBillStrategyServiceImpl implements MergeBillStrategyService {

    private final Logger logger = LoggerFactory.getLogger(MergeBillStrategyServiceImpl.class);

    @Autowired
    private MergeBillStrategyMapper mapper;
    @Autowired
    private ConvertorUtil convertorUtil;

    @Override
    public Page<BmsMergeStrategyDTO> findList(BmsMergeStrategyQueryVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Criteria criteria = Criteria.forClass(BmsMergeBillStrategyModel.class);
        Restriction r1 = ObjectUtil.isEmpty(vo.getStrategyName()) ? null : Restrictions.like("strategyName", "%" + vo.getStrategyName() + "%");
        Restriction r2 = ObjectUtil.isEmpty(vo.getStatus()) ? null : Restrictions.eq("status", vo.getStatus());
        Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2,r3));
        criteria.setOrder(Order.newInstance().desc("updatetime").asc("createtime"));
        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        List<BmsMergeBillStrategyModel> models = mapper.findByCriteria(criteria);
        List<BmsMergeStrategyDTO> list = Lists.newArrayList();
        for (BmsMergeBillStrategyModel model : models) {
            BmsMergeStrategyDTO dto = new BmsMergeStrategyDTO();
            BeanUtils.copyProperties(model, dto);
            dto.setStatusName(model.getStatus() == 1 ? "启用":"停用");

            List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[] {
                    BmsConstant.FEE_RULE
            });
            dto.setFeeRuleName(ConvertorUtil.getName(dicData, BmsConstant.FEE_RULE, String.valueOf(model.getFeeRule())));
            String mergeRule = this.buildMergeRule(model);
            dto.setMergeRule(mergeRule);
            list.add(dto);
        }
        // 分页设置
        Page<BmsMergeStrategyDTO> page = PageUtils.getPage(list);
        if (models instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<BmsMergeBillStrategyModel> p0 = (com.github.pagehelper.Page<BmsMergeBillStrategyModel>) models;
            page.setPageCount(p0.getPages());
            page.setPageNum(p0.getPageNum());
            page.setPageSize(p0.getPageSize());
            page.setTotalCount(p0.getTotal());
            page.setStartRow(p0.getStartRow());
            page.setEndRow(p0.getEndRow());
        }
        return page;
    }

    private String buildMergeRule(BmsMergeBillStrategyModel model) {
        List<String> list = Lists.newArrayList();
        String mergeRule = "";
        if (ObjectUtil.isNotEmpty(model.getIsSameStartDate())) {
            int isSameStartDate = model.getIsSameStartDate();
            if (isSameStartDate == 1) {
                list.add("相同实际启运日期");
            }
        }
        if (ObjectUtil.isNotEmpty(model.getIsSameCar())) {
            int isSameCar = model.getIsSameCar();
            if (isSameCar == 1) {
                list.add("相同运输车辆");
            }
        }
        if (ObjectUtil.isNotEmpty(model.getIsSameDriver())) {
            int isSameDriver = model.getIsSameDriver();
            if (isSameDriver == 1) {
                list.add("相同运输司机");
            }
        }
        if (ObjectUtil.isNotEmpty(model.getIsSameElectronicBackDate())) {
            int isSameElectronicBackDate = model.getIsSameElectronicBackDate();
            if (isSameElectronicBackDate == 1) {
                list.add("相同电子回单日期");
            }
        }
        if (ObjectUtil.isNotEmpty(model.getIsSameEndDate())) {
            int isSameEndDate = model.getIsSameEndDate();
            if (isSameEndDate == 1) {
                list.add("相同实际送达日期");
            }
        }
        if (ObjectUtil.isNotEmpty(model.getIsSameOriginalBackDate())) {
            int isSameOriginalBackDate = model.getIsSameOriginalBackDate();
            if (isSameOriginalBackDate == 1) {
                list.add("相同正本回单日期");
            }
        }
        if (ObjectUtil.isNotEmpty(model.getIsSameReceive())) {
            int isSameReceive = model.getIsSameReceive();
            if (isSameReceive == 1) {
                list.add("相同收货方");
            }
        }
        if (ObjectUtil.isNotEmpty(model.getIsSameSender())) {
            int isSameSender = model.getIsSameSender();
            if (isSameSender == 1) {
                list.add("相同发货方");
            }
        }
        if (ObjectUtil.isNotEmpty(model.getIsSameCarrier())) {
            int isSameSender = model.getIsSameCarrier();
            if (isSameSender == 1) {
                list.add("相同承运商");
            }
        }
        if (ObjectUtil.isNotNull(model.getIsSameDeliveryArea())) {
            if (model.getIsSameDeliveryArea() == 1) {
                list.add("相同配送区域");
            }
        }
        if (ObjectUtil.isNotNull(model.getIsSameDeliveryStation())) {
            if (model.getIsSameDeliveryStation() == 1) {
                list.add("相同送货站点");
            }
        }
        if (ObjectUtil.isNotNull(model.getIsSameLine())) {
            if (model.getIsSameLine() == 1) {
                list.add("相同线路");
            }
        }
        if (ObjectUtil.isNotNull(model.getIsSameCargoOwner())) {
            if (model.getIsSameCargoOwner() == 1) {
                list.add("相同货主");
            }
        }

        if (ObjectUtil.isNotEmpty(list)) {
            mergeRule = Joiner.on(",").join(list);
        }
        return mergeRule;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(BmsMergeStrategyVO vo) {
        logger.info("新增合并策略信息：" + JSONObject.toJSONString(vo));
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        //2 判断流程是否已配置
        Criteria criteria = Criteria.forClass(BmsMergeBillStrategyModel.class);
        Restriction r1 = Restrictions.eq("strategyName", vo.getStrategyName().trim());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        List<BmsMergeBillStrategyModel> list = mapper.findByCriteria(criteria);
        if (ObjectUtil.isNotEmpty(list) && list.size() > 0) {
            throw new RuntimeException(String.format("合并策略名称【%s】已经存在，请不要重复提交", vo.getStrategyName()));
        }
        BmsMergeBillStrategyModel model = new BmsMergeBillStrategyModel();
        BeanUtils.copyProperties(vo, model);
        model.setCreateperson(user.getNickname());
        model.setCreatetime(DateUtil.date());
        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(DateUtil.date());
        model.setEnterpriseId(user.getEnterpriseId());
        model.setEnterpriseName(user.getEnterpriseName());
        model.setStatus(1);
        mapper.save(model);
    }

    @Override
    public BmsMergeStrategyDTO detail(Long id) {
        if (ObjectUtil.isEmpty(id)) {
            throw new PluginException("查询条件不能为空");
        }
        BmsMergeStrategyDTO dto = new BmsMergeStrategyDTO();
        BmsMergeBillStrategyModel model = mapper.findById(id, BmsMergeBillStrategyModel.class);
        BeanUtils.copyProperties(model, dto);
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(BmsMergeStrategyVO vo) {
        if (ObjectUtil.isEmpty(vo.getId())) {
            throw new PluginException("修改参数不能为空");
        }
        BmsMergeBillStrategyModel model = mapper.findById(vo.getId(), BmsMergeBillStrategyModel.class);
        if (ObjectUtil.isEmpty(model)) {
            throw new PluginException("查询合并策略数据不存在");
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        BeanUtils.copyProperties(vo, model);
        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(DateUtil.date());

        mapper.update(model);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(List<StatusUpdate> vo) {
        logger.info("- > updateStatus vo={}", JsonMapper.toJsonString(vo));
        // 1 校验数据
        if (ObjectUtil.isEmpty(vo)) {
            throw new RuntimeException("请求参数不能为空");
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        for (StatusUpdate statusUpdate : vo) {
            BmsMergeBillStrategyModel model = mapper.findById(statusUpdate.getId(), BmsMergeBillStrategyModel.class);
            model.setStatus(statusUpdate.getStatus());
            model.setUpdateperson(user.getNickname());
            model.setUpdatetime(DateUtil.date());
            mapper.update(model);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String[] ids) {
        if (ObjectUtil.isEmpty(ids)) {
            throw new RuntimeException("请求参数不能为空");
        }
        // 判断是否启用
        for (String id : ids) {
            BmsMergeBillStrategyModel model = mapper.findById(id, BmsMergeBillStrategyModel.class);
            if (model.getStatus() == 1) {
                throw new PluginException(String.format("合并策略[%s],是启用状态不能删除", model.getStrategyName()));
            }

            mapper.deleteById(id, BmsMergeBillStrategyModel.class);
        }
    }
}