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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.page.PageData;
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.CompaniesDao;
import io.renren.modules.sys.dao.ScopeCityCompanyDao;
import io.renren.modules.sys.dto.BudgetDTO;
import io.renren.modules.sys.entity.BudgetEntity;
import io.renren.modules.sys.entity.CompaniesEntity;
import io.renren.modules.sys.entity.ScopeCityCompanyEntity;
import io.renren.modules.sys.service.BudgetService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 公司预算表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-05-28
 */
@Service
public class BudgetServiceImpl extends CrudServiceImpl<BudgetDao, BudgetEntity, BudgetDTO> implements BudgetService {

    @Autowired
    private ScopeCityCompanyDao scopeCityCompanyDao;
    @Autowired
    private CompaniesDao companiesDao;
    @Override
    public QueryWrapper<BudgetEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String city = (String)params.get("city");
        String companyId = (String)params.get("companyId");
        String scheduledDate = (String)params.get("scheduledDate");

        QueryWrapper<BudgetEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id).eq("status",1)
                .eq(StringUtils.isNotBlank(city), "city", city)
                .eq(StringUtils.isNotBlank(companyId), "company_id", companyId)
                .eq(StringUtils.isNotBlank(scheduledDate), "scheduled_date", scheduledDate)
                .orderByDesc("id");

        return wrapper;
    }

    @Override
    public PageData<BudgetDTO> page(Map<String, Object> params) {
        IPage<BudgetEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                getWrapper(params)
        );
        List<BudgetDTO> budgetDTOList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(page.getRecords())){
            BudgetDTO budgetDTO = null;
            for (BudgetEntity budgetEntity:page.getRecords()){
                budgetDTO = new BudgetDTO();
                BeanUtils.copyProperties(budgetEntity,budgetDTO);
                if(budgetEntity.getCompanyId()!=null){
                    CompaniesEntity companiesEntity = companiesDao.selectById(budgetEntity.getCompanyId());
                    if (companiesEntity!=null && companiesEntity.getStatus()==1) {
                        budgetDTO.setCompanyName(companiesEntity.getName());
                    }
                    budgetDTOList.add(budgetDTO);
                }
            }
        }
        return new PageData<>(budgetDTOList, page.getTotal());
    }

    @Override
    @Transactional
    public void update(BudgetDTO dto) {
        BudgetEntity entity = ConvertUtils.sourceToTarget(dto, currentModelClass());
        if (dto.getStatus()!=0) {
            /**
             * 更新涉及到该公司的落地城市公司表的分配人数
             */
            //1.查询地城市公司（根据公司id查询）
            List<ScopeCityCompanyEntity> scopeCityCompanyEntityList = scopeCityCompanyDao.selectList(new QueryWrapper<ScopeCityCompanyEntity>().eq("status", 1)
                    .eq("company_id", dto.getCompanyId()));
            if (!CollectionUtils.isEmpty(scopeCityCompanyEntityList)) {
                for (ScopeCityCompanyEntity scopeCityCompanyEntity : scopeCityCompanyEntityList) {
                    //落地城市单价不为空且！=0，更新人数分配
                    if (scopeCityCompanyEntity.getAvgPrice() != null && scopeCityCompanyEntity.getAvgPrice().compareTo(BigDecimal.ZERO) != 0) {
                        scopeCityCompanyEntity.setAssignPersonCount(entity.getTopLimitMoney().divide(scopeCityCompanyEntity.getAvgPrice(), 0, BigDecimal.ROUND_HALF_UP).intValue());
                        scopeCityCompanyDao.updateById(scopeCityCompanyEntity);
                    }
                }
            }
        }
        baseDao.updateById(entity);
    }
}