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

import cn.com.countrygarden.bi.main.dao.phoenix.PhoenixSalesProjectMapper;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.phoenix.PhoenixSalesProject;
import cn.com.countrygarden.bi.main.service.phoenix.PhoenixSalesHttpClientService;
import cn.com.countrygarden.bi.main.service.phoenix.PhoenixSalesProjectService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageRowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PhoenixSalesProjectServiceImpl implements PhoenixSalesProjectService {

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

    @Autowired
    private PhoenixSalesHttpClientService httpClientService;

    @Autowired
    private PhoenixSalesProjectMapper projectMapper;


    @Override
    public List<PhoenixSalesProject> sync() {
        Map<String, Object> params = new HashMap<String, Object>() {{
        }};
        String responsePackage = httpClientService.post("GetArea", params);
        List<PhoenixSalesProject> onSaleProjects = JSON.parseArray(responsePackage, PhoenixSalesProject.class);
        return onSaleProjects;
    }

    @Override
    public List<PhoenixSalesProject> persistence() {
        List<PhoenixSalesProject> projects = sync();

        if (projects.isEmpty()) {
            return null;
        }

        projectMapper.truncate();
        projectMapper.persistence(projects);

        return projects;
    }

    @Override
    public List<PhoenixSalesProject> findAll() {
        return projectMapper.selectAll();
    }

    @Override
    public PhoenixSalesProject findOne(String areaId) {
        PhoenixSalesProject project = new PhoenixSalesProject();
        project.setAreaid(areaId);
        return projectMapper.selectOne(project);
    }

    @Override
    public PageData search(int page, int pageSize) {
        PageRowBounds pageRowBounds = new PageRowBounds(page, pageSize);
        List<PhoenixSalesProject> projects = projectMapper.search(pageRowBounds);

        PageData pageData = new PageData(projects,pageRowBounds);

        return pageData;
    }
}
