/**
 * Description: 营销日报控制器
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-07-17 下午 13:27:32
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-07-17   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.ProjectEntity;
import com.house365.beans.entity.ReportMarketingEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.po.ReportDailyPo;
import com.house365.beans.po.ReportDepartmentPo;
import com.house365.beans.po.ReportMarketingPo;
import com.house365.beans.system.Page;
import com.house365.beans.vo.ReportMarketingVo;
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.ReportMarketingListRequest;
import com.house365.ws.beans.request.ReportMarketingRequest;
import com.house365.ws.beans.response.ReportMarketingListResponse;
import com.house365.ws.beans.response.ReportMarketingResponse;
import com.house365.ws.interfaces.server.IProject;
import com.house365.ws.interfaces.server.IReportMarketing;
import com.house365.ws.interfaces.server.IUser;
import net.sf.json.JSONArray;
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("/reportmarketing")
public class ReportMarketingController extends BaseController {

    /**
     * 自动注入营销日报WS实现
     */
    @Autowired
    private IReportMarketing reportMarketing;
    @Autowired
    private IProject project;
    @Autowired
    private IUser user;

    /**
     * 去新增营销日报
     *
     * @return 结果视图
     */
    @RequestMapping(value = "daily")
    public String daily(Model model, String type) {
        model.addAttribute("type", type);
        return getAutoUrl("daily");
    }

    @RequestMapping(value = "getDailies")
    @ResponseBody
    public String getDaily(HttpSession session, String startTime, String endTime) {
        UserEntity userEntity = (UserEntity) session.getAttribute(SessionConstants.THREAD_USER_KEY);
        //获取自己和所有下属id
        List<Integer> userIds = user.getUserIdOnPath(userEntity.getId());

        DepartmentEntity currentDepartment = (DepartmentEntity) session.getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        List<ReportDailyPo> daily = reportMarketing.getDailies(startTime, endTime, userIds,
                currentDepartment.getDescripition());
        return JSONArray.fromObject(daily).toString();
    }

    /**
     * 去新增营销日报
     *
     * @return 结果视图
     */
    @RequestMapping(value = "report")
    public String report(String startTime, String endTime, String type, String departmentIds, String userIds, Model model) {

        ReportMarketingPo reportMarketingPo = new ReportMarketingPo();

        List<ReportDepartmentPo> departments = new ArrayList<>();
        ReportDepartmentPo departmentPo1 = new ReportDepartmentPo();
        List<Integer> users1 = new ArrayList<>();
        users1.add(1);
        users1.add(3);
        departmentPo1.setId(11);
        departmentPo1.setUserIds(users1);

        ReportDepartmentPo departmentPo2 = new ReportDepartmentPo();
        List<Integer> users2 = new ArrayList<>();
        users2.add(2);
        users2.add(4);
        departmentPo2.setId(12);
        departmentPo2.setUserIds(users2);

        departments.add(departmentPo1);
        departments.add(departmentPo2);

        reportMarketingPo.setDepartments(departments);

        return getAutoUrl("report");
    }

    /**
     * 去新增营销日报
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(HttpSession session, Model model, String time) {
        UserEntity userEntity = (UserEntity) session.getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity departmentEntity = (DepartmentEntity) session.getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityCode = departmentEntity.getDescripition();

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

        model.addAttribute("projectList", projectList);
        model.addAttribute("time", time);
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增营销日报
     *
     * @param vo      营销日报页面表单对象
     * @param result  表单验证数据
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createReportMarketing(
            HttpServletRequest request, @Valid ReportMarketingVo vo, BindingResult result,
            RedirectAttributes redirectAttributes, Model model
    ) {
        ReportMarketingEntity 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 {
                DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                        SessionConstants.SESSION_CURRNET_DEPT_KEY);
                UserEntity userEntity = (UserEntity) request.getSession().getAttribute(
                        SessionConstants.THREAD_USER_KEY);

                String time = request.getParameter("time");

                entity.setDepartmentId(userEntity.getDeptId());
                entity.setDepartmentName(userEntity.getDeptName());
                entity.setUserId(userEntity.getId());
                entity.setUserName(userEntity.getRealName());
                entity.setCreateTime(new Date());
                entity.setReportTime(DateTimeUtils.parseDate(time, "yyyy-MM-dd"));
                entity.setCity(departmentEntity.getDescripition());

                ReportMarketingRequest reportMarketingRequest = new ReportMarketingRequest();
                reportMarketingRequest.setEntity(entity);
                ReportMarketingResponse response = reportMarketing.addReportMarketing(reportMarketingRequest);
                Integer id = response.getEntity().getId();
                return "redirect:/reportmarketing/" + id + "?time=" + time;
            } 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++) {
                    reportMarketing.deleteReportMarketingById(
                            Integer.valueOf(ids[i]));
                }
            } else {
                reportMarketing.deleteReportMarketingById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看营销日报
     *
     * @param id 营销日报页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model, String time) {
        ReportMarketingResponse response = reportMarketing.getReportMarketingById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("time", time);
        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, String time) {
        ReportMarketingResponse response = reportMarketing.getReportMarketingById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        model.addAttribute("time", time);
        return getAutoUrl("form");
    }

    /**
     * 修改营销日报
     *
     * @param vo     营销日报页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateReportMarketing(
            HttpServletRequest httpServletRequest, @Valid ReportMarketingVo vo, BindingResult result,
            @PathVariable Integer id, RedirectAttributes redirectAttributes, Model model
    ) {
        ReportMarketingEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        String time = httpServletRequest.getParameter("time");
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                ReportMarketingRequest request = new ReportMarketingRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") ReportMarketingResponse rersponse = reportMarketing.updateReportMarketing(
                        request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/reportmarketing/" + entity.getId() + "?time=" + time;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询营销日报
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "show", method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, String time) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        //获取自己和所有下属id
        List<Integer> userIds = user.getUserIdOnPath(userEntity.getId());
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityCode = departmentEntity.getDescripition();
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        searchParams.put("IN_userIds", userIds);
        searchParams.put("EQ_city", cityCode);
        searchParams.put("GTE_reportTime", time + " 00:00:00");
        searchParams.put("LTE_endReportTime", time + " 23:59:59");
        ReportMarketingListRequest listRequest = new ReportMarketingListRequest();
        listRequest.setSearchParams(searchParams);
        listRequest.setPaging(new Page(Integer.MAX_VALUE));
        ReportMarketingListResponse response = reportMarketing.getReportMarketingList(listRequest);
        model.addAttribute("reportMarketings", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        model.addAttribute("time", DateTimeUtils.parseDate(time, "yyyy-MM-dd"));
        return getAutoUrl();
    }
}
