package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.sys.dao.BudgetDao;
import io.renren.modules.sys.dao.ScopeCityCompanyDao;
import io.renren.modules.sys.dao.ScopeCityCostDao;
import io.renren.modules.sys.dto.ScopeCityCostDTO;
import io.renren.modules.sys.entity.BudgetEntity;
import io.renren.modules.sys.entity.ScopeCityCompanyEntity;
import io.renren.modules.sys.entity.ScopeCityCostEntity;
import io.renren.modules.sys.service.ScopeCityCostService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 受众城市单价
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-05-28
 */
@Service
public class ScopeCityCostServiceImpl extends CrudServiceImpl<ScopeCityCostDao, ScopeCityCostEntity, ScopeCityCostDTO> implements ScopeCityCostService {

    @Autowired
    private ScopeCityCompanyDao scopeCityCompanyDao;
    @Autowired
    private BudgetDao budgetDao;
    @Override
    public QueryWrapper<ScopeCityCostEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String date = (String)params.get("date");
        String city = (String)params.get("city");
        String advertiserId = (String)params.get("advertiserId");

        QueryWrapper<ScopeCityCostEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id).eq("status",1)
                .eq(StringUtils.isNotBlank(city), "city", city)
                .eq(StringUtils.isNotBlank(advertiserId), "advertiser_id", advertiserId)
                .eq(StringUtils.isNotBlank(date), "date", date)
                .orderByDesc("id");

        return wrapper;
    }

    @Override
    @Transactional
    public void update(ScopeCityCostDTO dto) {
        ScopeCityCostEntity entity = ConvertUtils.sourceToTarget(dto, currentModelClass());
        if (dto.getStatus()!=0) {
            refreshCompanyAvgPriceAndAssignPersonCount(entity);
        }
        baseDao.updateById(entity);
    }

    /**
     * 刷新落地城市公司对应的单价以及 分配人数
     * @param entity
     */
    @Override
    @Transactional
    public void refreshCompanyAvgPriceAndAssignPersonCount(ScopeCityCostEntity entity){
        ScopeCityCostEntity scopeCityCostEntity = baseDao.selectOne(new QueryWrapper<ScopeCityCostEntity>().eq("status",1)
                .eq("advertiser_id",entity.getAdvertiserId())
                .eq("city",entity.getCity()).orderByDesc("date").last("limit 1"));
        if (scopeCityCostEntity!=null && scopeCityCostEntity.getId().longValue()==entity.getId().longValue()) {
            /**
             * 更新涉及到该账户+城市的落地城市公司表的分配人数(必须是最新一条)
             */
            //1.查询落地城市公司列表
            List<ScopeCityCompanyEntity> scopeCityCompanyEntityList = scopeCityCompanyDao.selectByAdvertiserIdAndCity(entity.getAdvertiserId(), entity.getCity());
            if (!CollectionUtils.isEmpty(scopeCityCompanyEntityList)) {
                for (ScopeCityCompanyEntity scopeCityCompanyEntity : scopeCityCompanyEntityList) {
                    scopeCityCompanyEntity.setAvgPrice(BigDecimal.ZERO);
                    scopeCityCompanyEntity.setAssignPersonCount(0);
                    //2.查询公司预算（公司+城市）
                    BudgetEntity budgetEntity = budgetDao.selectOne(new QueryWrapper<BudgetEntity>().eq("status", 1)
                            .eq("company_id", scopeCityCompanyEntity.getCompanyId())
                            .eq("city", entity.getCity()).orderByDesc("scheduled_date").last("limit 1"));
                    if (budgetEntity != null) {
                        //城市单价
                        scopeCityCompanyEntity.setAvgPrice(entity.getManuAvgCost() != null ? entity.getManuAvgCost() : entity.getAvgCost());
                        //人数分配
                        if (budgetEntity.getTopLimitMoney() != null && scopeCityCompanyEntity.getAvgPrice() != null && scopeCityCompanyEntity.getAvgPrice().compareTo(BigDecimal.ZERO) != 0) {
                            scopeCityCompanyEntity.setAssignPersonCount(budgetEntity.getTopLimitMoney().divide(scopeCityCompanyEntity.getAvgPrice(), 0, BigDecimal.ROUND_HALF_UP).intValue());
                        }
                    }
                    scopeCityCompanyDao.updateById(scopeCityCompanyEntity);
                }
            }
        }
    }
}