package com.hai.service.impl;

import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.RedisUtil;
import com.hai.dao.HighGasOilPriceTaskMapper;
import com.hai.entity.HighGasOilPrice;
import com.hai.entity.HighGasOilPriceOfficial;
import com.hai.entity.HighGasOilPriceTask;
import com.hai.entity.HighGasOilPriceTaskExample;
import com.hai.enum_type.GasTaskExecutionTypeEnum;
import com.hai.enum_type.GasTaskPriceTypeEnum;
import com.hai.enum_type.GasTaskStatusEnum;
import com.hai.msg.entity.MsgTopic;
import com.hai.service.HighGasOilPriceOfficialService;
import com.hai.service.HighGasOilPriceService;
import com.hai.service.HighGasOilPriceTaskService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("gasOilPriceTaskService")
public class HighGasOilPriceTaskServiceImpl implements HighGasOilPriceTaskService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private HighGasOilPriceTaskMapper gasOilPriceTaskMapper;

    @Resource
    private HighGasOilPriceService gasOilPriceService;

    @Resource
    private HighGasOilPriceOfficialService gasOilPriceOfficialService;

    @Override
    public void editData(HighGasOilPriceTask gasOilPriceTask) {
        if (gasOilPriceTask.getId() == null) {
            gasOilPriceTask.setStatus(GasTaskStatusEnum.status1.getStatus());
            gasOilPriceTask.setCreateTime(new Date());
            gasOilPriceTask.setUpdateTime(new Date());
            gasOilPriceTaskMapper.insert(gasOilPriceTask);
        } else {
            gasOilPriceTaskMapper.updateByPrimaryKey(gasOilPriceTask);
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void batchAddTask(List<HighGasOilPriceTask> taskList) {
        for (HighGasOilPriceTask task : taskList) {
            addTask(task);
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void addTask(HighGasOilPriceTask gasOilPriceTask) {
        editData(gasOilPriceTask);
        // 立刻执行
        if (gasOilPriceTask.getExecutionType().equals(GasTaskExecutionTypeEnum.type1.getStatus())) {
            businessHandle(gasOilPriceTask);

        } else if (gasOilPriceTask.getExecutionType().equals(GasTaskExecutionTypeEnum.type2.getStatus())) {
            long time = DateUtil.getSecondDiff(new Date(), gasOilPriceTask.getStartTime());
            if (time >= 1) {
                redisUtil.set(MsgTopic.oilPriceTask.getName() + "-" + gasOilPriceTask.getId(), "", time);
            } else {
                businessHandle(gasOilPriceTask);
            }
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void businessHandle(HighGasOilPriceTask gasOilPriceTask) {
        // 立刻执行
        gasOilPriceTask.setStartTime(new Date());
        gasOilPriceTask.setStatus(GasTaskStatusEnum.status2.getStatus());
        editData(gasOilPriceTask);

        // 国标价
        if (gasOilPriceTask.getPriceType().equals(GasTaskPriceTypeEnum.type1.getStatus())) {
            // 查询国标价油品价格
            HighGasOilPriceOfficial price = gasOilPriceOfficialService.getPrice(gasOilPriceTask.getRegionId(), gasOilPriceTask.getOilNo());
            if (price == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油品价格");
            }
            gasOilPriceOfficialService.editPrice(gasOilPriceTask.getRegionId(), gasOilPriceTask.getOilNo(), gasOilPriceTask.getPrice());

            // 更新自建站的国标价
            gasOilPriceOfficialService.refreshGasPriceOfficial(gasOilPriceTask.getRegionId(), gasOilPriceTask.getOilNo());
        }

        // 油站价
        if (gasOilPriceTask.getPriceType().equals(GasTaskPriceTypeEnum.type2.getStatus())) {
            // 查询油品价格
            HighGasOilPrice price = gasOilPriceService.getGasOilPriceByStoreAndOilNo(gasOilPriceTask.getMerStoreId(), gasOilPriceTask.getOilNo());
            if (price == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油品价格");
            }
            price.setPriceGun(gasOilPriceTask.getPrice().subtract(price.getGasStationDrop()));
            price.setPriceVip(price.getPriceGun().subtract(price.getPreferentialMargin()));
            gasOilPriceService.editGasOilPrice(price);
        }

        // 平台优惠
        if (gasOilPriceTask.getPriceType().equals(GasTaskPriceTypeEnum.type3.getStatus())) {
            // 查询油品价格
            HighGasOilPrice price = gasOilPriceService.getGasOilPriceByStoreAndOilNo(gasOilPriceTask.getMerStoreId(), gasOilPriceTask.getOilNo());
            if (price == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油品价格");
            }
            price.setPreferentialMargin(gasOilPriceTask.getPrice());
            price.setPriceVip(price.getPriceGun().subtract(price.getPreferentialMargin()));
            gasOilPriceService.editGasOilPrice(price);
        }

        // 油站直降
        if (gasOilPriceTask.getPriceType().equals(GasTaskPriceTypeEnum.type4.getStatus())) {
            // 查询油品价格
            HighGasOilPrice price = gasOilPriceService.getGasOilPriceByStoreAndOilNo(gasOilPriceTask.getMerStoreId(), gasOilPriceTask.getOilNo());
            if (price == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油品价格");
            }
            price.setGasStationDrop(gasOilPriceTask.getPrice());
            price.setPriceGun(price.getPriceOfficial().subtract(price.getGasStationDrop()));
            price.setPriceVip(price.getPriceGun().subtract(price.getPreferentialMargin()));
            gasOilPriceService.editGasOilPrice(price);
        }

    }

    @Override
    public HighGasOilPriceTask getDetailById(Long taskId) {
        return gasOilPriceTaskMapper.selectByPrimaryKey(taskId);
    }

    @Override
    public void delTask(Long taskId) {
        // 查询价格任务
        HighGasOilPriceTask detail = getDetailById(taskId);
        if (detail == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "未找到任务");
        }
        detail.setStatus(GasTaskStatusEnum.status0.getStatus());
        editData(detail);

        // 从redis中删除任务
        redisUtil.del(MsgTopic.oilPriceTask.getName() + "-" + taskId);
    }

    @Override
    public List<HighGasOilPriceTask> getTaskList(Map<String, Object> param) {
        HighGasOilPriceTaskExample example = new HighGasOilPriceTaskExample();
        HighGasOilPriceTaskExample.Criteria criteria = example.createCriteria()
                .andStatusNotEqualTo(GasTaskStatusEnum.status0.getStatus());

        if (MapUtils.getLong(param, "regionId") != null) {
            criteria.andRegionIdEqualTo(MapUtils.getLong(param, "regionId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "regionName"))) {
            criteria.andRegionNameLike("%" + MapUtils.getString(param, "regionName") + "%");
        }

        if (MapUtils.getLong(param, "merStoreId") != null) {
            criteria.andMerStoreIdEqualTo(MapUtils.getLong(param, "merStoreId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "merStoreName"))) {
            criteria.andMerStoreNameLike("%" + MapUtils.getString(param, "merStoreName") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "merStoreKey"))) {
            criteria.andMerStoreKeyLike("%" + MapUtils.getString(param, "merStoreKey") + "%");
        }

        if (MapUtils.getInteger(param, "oilType") != null) {
            criteria.andOilTypeEqualTo(MapUtils.getInteger(param, "oilType"));
        }

        if (MapUtils.getInteger(param, "oilNo") != null) {
            criteria.andOilNoEqualTo(MapUtils.getInteger(param, "oilNo"));
        }

        if (MapUtils.getInteger(param, "priceType") != null) {
            criteria.andPriceTypeEqualTo(MapUtils.getInteger(param, "priceType"));
        }

        if (MapUtils.getInteger(param, "executionType") != null) {
            criteria.andExecutionTypeEqualTo(MapUtils.getInteger(param, "executionType"));
        }

        if (MapUtils.getInteger(param, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(param, "status"));
        }

        example.setOrderByClause("create_time desc");
        return gasOilPriceTaskMapper.selectByExample(example);
    }
}
