/**
 * Description: 驻场日报WS接口
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-07-17 上午 10:14:22
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-07-17   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.LocalReportEntity;
import com.house365.beans.po.ReportDailyPo;
import com.house365.beans.system.QueryParams;
import com.house365.beans.vo.LocalReportFormVo;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.DateTimeUtils;
import com.house365.ws.beans.request.LocalReportListRequest;
import com.house365.ws.beans.request.LocalReportRequest;
import com.house365.ws.beans.response.LocalReportListResponse;
import com.house365.ws.beans.response.LocalReportResponse;
import com.house365.ws.interfaces.server.ILocalReport;
import com.house365.ws.service.interfaces.ILocalReportService;
import com.house365.ws.system.House365SearchResponse;
import com.house365.ws.system.ReturnResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

//import org.house365.core.support.QueryParams;

/**
 * 驻场日报WS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-07-17
 * @see
 * @since 1.0
 */
@Service("localReport")
public class LocalReportImpl implements ILocalReport {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LocalReportImpl.class);

    /**
     * 驻场日报服务对象
     */
    @Autowired
    ILocalReportService<LocalReportEntity> localReportService;

    @Override
    public List<LocalReportFormVo> queryFormVO(String city) {
        return localReportService.queryFormVO(city);
    }

    @Override
    public List<LocalReportFormVo> queryFormVORecord(String city, String reportDate, Integer projectId) {
        return localReportService.queryFormVORecord(city, reportDate, projectId);
    }

    /**
     * 驻场日报列表查询
     *
     * @param request 驻场日报列表查询请求
     * @return 驻场日报列表查询响应
     */
    @Override
    public LocalReportListResponse getLocalReportList(LocalReportListRequest request) {
        LocalReportListResponse response = new LocalReportListResponse();
        try {
            QueryParams<LocalReportEntity> queryParams = new QueryParams<LocalReportEntity>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<LocalReportEntity> localReports = localReportService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(localReports);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public LocalReportResponse saveReport(
            String data, String project, String reportDateStr, String city, String user
    ) throws Exception {
        LocalReportResponse response = new LocalReportResponse();
        try {
            JSONArray da = JSONArray.fromObject(data);
            Date reportDate = DateTimeUtils.parseDate(reportDateStr, DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
            Date now = new Date();
            localReportService.cleanDayReportByProject(project, reportDateStr);

            for (Object object : da) {
                JSONObject ob = (JSONObject) object;
                LocalReportEntity lr = new LocalReportEntity();
                lr.setBuyorder(Integer.parseInt(String.valueOf(ob.get("buyorder"))));
                lr.setChannelId(Integer.parseInt(String.valueOf(ob.get("channelId"))));
                lr.setProjectId(Integer.valueOf(project));
                lr.setCity(city);
                lr.setCreater(user);
                lr.setCreateTime(now);
                lr.setDepartId(Integer.parseInt(String.valueOf(ob.get("departId"))));
                lr.setLastModifier(user);
                lr.setName(String.valueOf(ob.get("name")));
                lr.setRecord(Integer.parseInt(String.valueOf(ob.get("record"))));
                lr.setBuy(Integer.parseInt(String.valueOf(ob.get("buy"))));
                lr.setScore(Integer.parseInt(String.valueOf(ob.get("score"))));
                lr.setStatus("1");
                lr.setUpdateTime(now);
                lr.setUserId(Integer.parseInt(String.valueOf(ob.get("userId"))));
                lr.setVisit(Integer.parseInt(String.valueOf(ob.get("visit"))));
                lr.setReportDate(reportDate);
                localReportService.save(lr);
            }
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
            throw ex;
        }
        return response;
    }

    /**
     * 保存驻场日报
     *
     * @param request 驻场日报请求
     * @return 保存驻场日报响应
     */
    @Override
    public LocalReportResponse addLocalReport(LocalReportRequest request) {
        LocalReportResponse response = new LocalReportResponse();
        try {
            LocalReportEntity entity = request.getEntity();
            localReportService.save(entity);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除驻场日报通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除驻场日报响应
     */
    @Override
    public LocalReportResponse deleteLocalReportById(Integer id) {
        LocalReportResponse response = new LocalReportResponse();
        try {
            localReportService.delete(id);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改驻场日报
     *
     * @param request 修改驻场日报请求
     * @return 修改驻场日报响应
     */
    @Override
    public LocalReportResponse updateLocalReport(LocalReportRequest request) {
        LocalReportResponse response = new LocalReportResponse();
        try {
            localReportService.update(request.getEntity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 通过ID获取驻场日报
     *
     * @param id 唯一标识
     * @return 通过ID获取驻场日报响应
     */
    @Override
    public LocalReportResponse getLocalReportById(Integer id) {
        LocalReportResponse response = new LocalReportResponse();
        try {
            LocalReportEntity entity = localReportService.getById(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    @Override
    public House365SearchResponse statistic(LocalReportListRequest request) {
        House365SearchResponse response = new House365SearchResponse();
        try {
            QueryParams queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<LocalReportFormVo> localReports = localReportService.statistic(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(localReports);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    @Override
    public List<ReportDailyPo> getDailies(String startTime, String endTime, String city) {
        return localReportService.getDailies(startTime, endTime, city);
    }

    /**
     * 以下均为自动生成
     */

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {
    }
}
