/**
 * Description: 驻场日报控制器
 * 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.web.controller;

import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.po.ReportDailyPo;
import com.house365.beans.system.Page;
import com.house365.beans.vo.LocalReportFormVo;
import com.house365.beans.vo.LocalReportVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.LocalReportListRequest;
import com.house365.ws.beans.request.LocalReportRequest;
import com.house365.ws.beans.request.ReportChannelListRequest;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.beans.response.LocalReportListResponse;
import com.house365.ws.beans.response.LocalReportResponse;
import com.house365.ws.beans.response.ReportChannelListResponse;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.ILocalReport;
import com.house365.ws.interfaces.server.IProject;
import com.house365.ws.interfaces.server.IReportChannel;
import net.sf.json.JSONArray;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 驻场日报控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-07-17
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/localreport")
public class LocalReportController extends BaseController {

    private final Logger LOGGER = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入驻场日报WS实现
     */
    @Autowired
    private ILocalReport localReport;
    @Autowired
    private IProject project;
    @Autowired
    private IDepartment department;
    @Autowired
    private IReportChannel reportChannel;


    @RequestMapping(value = "getDailies")
    @ResponseBody
    public String getDaily(HttpSession session, String startTime, String endTime) {
        DepartmentEntity currentDepartment = (DepartmentEntity) session.getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        List<ReportDailyPo> daily = localReport.getDailies(startTime, endTime, currentDepartment.getDescripition());
        return JSONArray.fromObject(daily).toString();
    }

    @RequestMapping(value = "getTableData")
    @ResponseBody
    public Object getTableData(Model model, HttpServletRequest request) {
        String projectId = request.getParameter("projectId") == null ? "" : request.getParameter("projectId");
        String reportDateStr = request.getParameter("reportDateStr") == null ? "" : request.getParameter(
                "reportDateStr");

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        List<LocalReportFormVo> voList = new ArrayList<>();

        //not 365 channel
        Map<String, Object> channelMap = new HashedMap();
        channelMap.put("EQ_city", cityCode);
        channelMap.put("EQ_status", "1");
        channelMap.put("EQ_channelType", "2");
        ReportChannelListRequest channelListRequest = new ReportChannelListRequest();
        channelListRequest.setSearchParams(channelMap);
        channelListRequest.setPaging(new Page(Integer.MAX_VALUE));
        ReportChannelListResponse channelListResponse = reportChannel.getReportChannelList(channelListRequest);

        //是否填过
        voList = localReport.queryFormVORecord(cityCode, reportDateStr, Integer.valueOf(projectId));
        if (voList.isEmpty()) {
            voList = localReport.queryFormVO(cityCode);

            if (channelListResponse.getObjectList() != null && !channelListResponse.getObjectList().isEmpty()) {
                for (ReportChannelEntity channel : channelListResponse.getObjectList()) {
                    LocalReportFormVo vo = new LocalReportFormVo();
                    vo.setVisit(0);
                    vo.setScore(0);
                    vo.setRecord(0);
                    vo.setChannelId(channel.getId());
                    vo.setBuyorder(0);
                    vo.setBuy(0);
                    vo.setChannelName(channel.getName());
                    vo.setChannelType(String.valueOf(channel.getChannelType()));
                    vo.setDepartName(channel.getName());
                    vo.setName(channel.getName());
                    voList.add(vo);
                }
            }

        } else {
            //not in old record ,add new user .dept .project to list
            List<LocalReportFormVo> listNow = localReport.queryFormVO(cityCode);
            for (LocalReportFormVo lr : listNow) {
                if (!voList.contains(lr)) {
                    voList.add(lr);
                }
            }

            //add not 365 channel
            if (channelListResponse.getObjectList() != null && !channelListResponse.getObjectList().isEmpty()) {
                for (ReportChannelEntity channel : channelListResponse.getObjectList()) {
                    LocalReportFormVo vo = new LocalReportFormVo();
                    vo.setVisit(0);
                    vo.setScore(0);
                    vo.setRecord(0);
                    vo.setChannelId(channel.getId());
                    vo.setBuyorder(0);
                    vo.setBuy(0);
                    vo.setChannelName(channel.getName());
                    vo.setChannelType(String.valueOf(channel.getChannelType()));
                    vo.setDepartName(channel.getName());
                    vo.setName(channel.getName());
                    if (!voList.contains(vo)) {
                        voList.add(vo);
                    }
                }
            }
        }

        model.addAttribute("currentProject", projectId);
        return JSONArray.fromObject(voList).toString();
    }

    @RequestMapping(value = "saveReport")
    @ResponseBody
    public Object saveReport(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        String data = request.getParameter("data");
        String project = request.getParameter("project");
        String reportDateStr = request.getParameter("reportDateStr");

        if (!Strings.isNullOrEmpty(data) && !Strings.isNullOrEmpty(project) && !Strings.isNullOrEmpty(reportDateStr)) {
            try {
                localReport.saveReport(data, project, reportDateStr, cityCode, userEntity.getRealName());
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        return true;
    }

    /**
     * 去新增驻场日报
     *
     * @return 结果视图
     */
    @RequestMapping(value = "show")
    public String createForm(Model model, HttpServletRequest request, String time) {
        Date recordate = DateTimeUtils.parseDate(time, "yyyy-MM-dd");
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        List<ProjectEntity> projectList = project.getProjectListByUserId(userEntity.getId(), cityCode, "1");

        List<LocalReportFormVo> voList = new ArrayList<>();
        if (!projectList.isEmpty()) {
            model.addAttribute("currentProject", projectList.get(0).getId());
        }

        model.addAttribute("reportChannels", voList);
        model.addAttribute("projects", projectList);
        model.addAttribute("recordate", recordate);
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }


    /**
     * 新增驻场日报
     *
     * @param vo     驻场日报页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createLocalReport(
            @Valid LocalReportVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        LocalReportEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                LocalReportRequest request = new LocalReportRequest();
                request.setEntity(entity);
                LocalReportResponse response = localReport.addLocalReport(request);
                Integer id = response.getEntity().getId();
                return "redirect:/localreport/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除驻场日报
     *
     * @param id 驻场日报页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id) {
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    localReport.deleteLocalReportById(Integer.valueOf(ids[i]));
                }
            } else {
                localReport.deleteLocalReportById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看驻场日报
     *
     * @param id 驻场日报页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        LocalReportResponse response = localReport.getLocalReportById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改驻场日报
     *
     * @param id 驻场日报页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        LocalReportResponse response = localReport.getLocalReportById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改驻场日报
     *
     * @param vo     驻场日报页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateLocalReport(
            @Valid LocalReportVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            Model model
    ) {
        LocalReportEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                LocalReportRequest request = new LocalReportRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") LocalReportResponse rersponse = localReport.updateLocalReport(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/localreport/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询驻场日报
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page();
        if (null != number) {
            page.setCurrentPage(number);
        }
        LocalReportListRequest listRequest = new LocalReportListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        LocalReportListResponse response = localReport.getLocalReportList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("localReports", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

}
