package cn.com.countrygarden.bi.main.service.resident.impl;

import cn.com.countrygarden.bi.main.dao.resident.ResidentQuotaMapper;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.resident.ResidentQuota;
import cn.com.countrygarden.bi.main.service.common.CommService;
import cn.com.countrygarden.bi.main.service.resident.ResidentQuotaService;
import cn.com.countrygarden.bi.main.service.resident.model.QuotaData;
import com.github.pagehelper.PageRowBounds;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;

import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional(readOnly = true)
public class ResidentQuotaServiceImpl implements ResidentQuotaService {

    @Autowired
    private CommService commService;

    @Autowired
    private ResidentQuotaMapper mapper;

    @Transactional(readOnly = false)
    @Override
    public void parseUploadFile(List<QuotaData> dataList, int year, String userCode) {
        if (dataList.size() == 0) {
            return;
        }

        //verify data
        Map<String, Object> organNameMap = commService.findOrganNameMapCache();
        //检证：项目类型、项目性质、合作类型、接管区域
        for (QuotaData data : dataList) {
            if (!StringUtils.isEmpty(data.getOrganName())) {
                String organCode = (String) organNameMap.get(data.getOrganName());
                if (organCode == null) {
                    throw new ServiceException("数据不正确, '" + data.getOrganName() + "'非系统可区域，请填入ERP系统现有区域");
                }
                data.setOrganId(organCode);
            }
        }

        List<ResidentQuota> newData = new ArrayList<>();
        List<ResidentQuota> updateData = new ArrayList<>();

        Date current = new Date();
        for (QuotaData data : dataList) {
            String organId = data.getOrganId();
            BigDecimal total = new BigDecimal(data.getTotal());
            BigDecimal gross = new BigDecimal(data.getGross());
            BigDecimal house = new BigDecimal(data.getHouse());
            BigDecimal arena = new BigDecimal(data.getArena());
            BigDecimal groupBuying = new BigDecimal(data.getGroupBuying());
            BigDecimal tourism = new BigDecimal(data.getTourism());
            BigDecimal carService = new BigDecimal(data.getCarService());
            BigDecimal shortRent = new BigDecimal(data.getShortRent());
            BigDecimal insurance = new BigDecimal(data.getInsurance());
            BigDecimal media = new BigDecimal(data.getMedia());
            BigDecimal other = new BigDecimal(data.getOther());

            ResidentQuota query = new ResidentQuota();
            query.setYear(year);
            query.setOrganId(organId);
            query.setIsDeleted(false);
            ResidentQuota duplicatedQuota = mapper.selectOne(query);
            if (duplicatedQuota != null && duplicatedQuota.getId() != null) {
                duplicatedQuota.setTotal(total);
                duplicatedQuota.setGross(gross);
                duplicatedQuota.setHouse(house);
                duplicatedQuota.setArena(arena);
                duplicatedQuota.setGroupBuying(groupBuying);
                duplicatedQuota.setTourism(tourism);
                duplicatedQuota.setCarService(carService);
                duplicatedQuota.setShortRent(shortRent);
                duplicatedQuota.setInsurance(insurance);
                duplicatedQuota.setMedia(media);
                duplicatedQuota.setOther(other);
                duplicatedQuota.setGmtModified(current);
                duplicatedQuota.setModifiedBy(userCode);

                updateData.add(duplicatedQuota);
            } else {
                ResidentQuota residentQuota = new ResidentQuota();
                residentQuota.setYear(year);
                residentQuota.setOrganId(organId);
                residentQuota.setOrganName(data.getOrganName());
                residentQuota.setTotal(total);
                residentQuota.setGross(gross);
                residentQuota.setHouse(house);
                residentQuota.setArena(arena);
                residentQuota.setGroupBuying(groupBuying);
                residentQuota.setTourism(tourism);
                residentQuota.setCarService(carService);
                residentQuota.setShortRent(shortRent);
                residentQuota.setInsurance(insurance);
                residentQuota.setMedia(media);
                residentQuota.setOther(other);
                residentQuota.setIsDeleted(false);
                residentQuota.setGmtCreate(current);
                residentQuota.setCreatedBy(userCode);
                residentQuota.setGmtModified(current);
                residentQuota.setModifiedBy(userCode);
                newData.add(residentQuota);
            }
        }

        if (!newData.isEmpty()) {
            try {
                mapper.insertList(newData);
            } catch (Exception e) {
                throw new ServiceException("数据导入失败：服务器异常");
            }

        }

        if (!updateData.isEmpty()) {
            for (ResidentQuota residentQuota : updateData) {
                mapper.updateByPrimaryKey(residentQuota);
            }
        }
    }

    public PageData search(String userCode, int year, int page, int size) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("year", year);
        PageRowBounds pageRowBounds = new PageRowBounds(page, size);
        List<ResidentQuota> quotas = mapper.search(params, pageRowBounds);
        PageData result = new PageData(quotas, pageRowBounds);
        return result;
    }

    @Transactional(readOnly = false)
    @Override
    public void delete(int quotaId, String userCode) {
        Condition condition = new Condition(ResidentQuota.class);

        ResidentQuota quota = mapper.selectByPrimaryKey(quotaId);
        if (quota == null) {
            throw new ServiceException("删除失败：指标不存在");
        }
        condition.createCriteria().andEqualTo("id", quotaId);
        quota.setIsDeleted(true);
        quota.setModifiedBy(userCode);
        quota.setGmtModified(new Date());
        int count = mapper.updateByCondition(quota, condition);
        if (count == 0) {
            throw new ServiceException("删除失败, 请重试");
        }
    }
}
