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

import com.beust.jcommander.internal.Lists;
import com.google.common.base.Joiner;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.ReportChannelDepartRelEntity;
import com.house365.beans.entity.ReportChannelEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.ReportChannelVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.DepartmentListRequest;
import com.house365.ws.beans.request.ReportChannelDepartRelListRequest;
import com.house365.ws.beans.request.ReportChannelListRequest;
import com.house365.ws.beans.request.ReportChannelRequest;
import com.house365.ws.beans.response.*;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.IReportChannel;
import com.house365.ws.interfaces.server.IReportChannelDepartRel;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * ReportChannel控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-07-17
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/reportchannel")
public class ReportChannelController extends BaseController {
    Logger channelLogger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入ReportChannelWS实现
     */
    @Autowired
    private IReportChannel reportChannel;

    @Autowired
    private IReportChannelDepartRel reportChannelDepartRel;

    @Autowired
    private IDepartment department;


    /**
     * 去新增ReportChannel
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(
            Model model, HttpServletRequest request
    ) {
        String[] departmentPara = request.getParameterValues("department");
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        ReportChannelEntity entity = new ReportChannelEntity();
        entity.setCreateTime(new Date());
        entity.setCreater(userEntity.getName());

        List<DepartmentEntity> departmentEntities = new ArrayList<>();

        String cityId = dept.getCityID();

        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();

        String urlPath = city.getUrlPath();

        departmentEntities = getDepartmentEntities(departmentPara, urlPath);

        model.addAttribute("entity", entity);
        model.addAttribute("departmentList", departmentEntities);
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    private List<DepartmentEntity> getDepartmentEntities(String[] departmentPara, String urlPath) {
        List<DepartmentEntity> departmentEntities;
        DepartmentListRequest dlr = new DepartmentListRequest();
        Page dPage = new Page(Integer.MAX_VALUE);
        Map<String, Object> dmap = new HashMap<>();
        dmap.put("LIKE_urlPath", urlPath);
        dlr.setParamMap(dmap);
        dlr.setOrderColumn("id");
        dlr.setOrderMode("asc");
        dlr.setSearchParams(dmap);
        dlr.setPaging(dPage);
        departmentEntities = department.getDepartmentList(dlr).getObjectList();
        channelLogger.warn("===============[{}]", urlPath + "," + departmentEntities.size());
        // 设置页面多选框选中效果
        setPageSelectedFlag(departmentEntities, departmentPara);
        return departmentEntities;
    }

    private void setPageSelectedFlag(
            List<DepartmentEntity> departmentEntities, String[] department
    ) {
        if (department != null) {
            // 页面选中效果
            for (DepartmentEntity departmentEntity : departmentEntities) {
                departmentEntity.setType("0");
                for (String deptm : Lists.newArrayList(department)) {
                    if (deptm.equals(departmentEntity.getId().toString())) {
                        departmentEntity.setType("1");
                        break;
                    } else {
                        departmentEntity.setType("0");
                    }
                }
            }
        }

    }

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

                DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                        SessionConstants.SESSION_CURRNET_DEPT_KEY);
                String[] department = request.getParameterValues("department");
                if ("1".equalsIgnoreCase(String.valueOf(
                        vo.getEntity().getChannelType())) && (null == department || department.length <= 0)) {
                    model.addAttribute("action", "create");
                    addErrorMessage(model, "请选择部门");
                    return getAutoUrl("form");
                }
                entity.setCity(dept.getDescripition());
                entity.setCreateTime(new Date());
                entity.setCreater(userEntity.getName());
                entity.setUpateTime(new Date());
                entity.setLastModifier(userEntity.getName());

                ReportChannelRequest reportChannelRequest = new ReportChannelRequest();
                reportChannelRequest.setEntity(entity);
                ReportChannelResponse response = reportChannel.addReportChannels(reportChannelRequest, department);
                Integer id = response.getEntity().getId();

                return "redirect:/reportchannel/" + id;

            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除ReportChannel
     *
     * @param id      ReportChannel页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id, HttpServletRequest request) {
        if (!StringUtils.isEmpty(id)) {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            channelLogger.info("user [{}] remove channels[{}]", userEntity.getName(), id);

            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    reportChannel.deleteReportChannelById(Integer.valueOf(ids[i]));
                }
            } else {
                reportChannel.deleteReportChannelById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看ReportChannel
     *
     * @param id ReportChannel页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        ReportChannelResponse response = reportChannel.getReportChannelById(id);
        Map<String, Object> search = new HashMap<>();
        search.put("EQ_channelId", id);

        ReportChannelDepartRelListRequest reportChannelDepartRelListRequest = new ReportChannelDepartRelListRequest();
        reportChannelDepartRelListRequest.setSearchParams(search);
        reportChannelDepartRelListRequest.setPaging(new Page(Integer.MAX_VALUE));

        ReportChannelDepartRelListResponse listResponse = reportChannelDepartRel.getReportChannelDepartRelList(
                reportChannelDepartRelListRequest);

        List<String> deptNames = new ArrayList<>();

        List<Integer> depts = new ArrayList<>();
        if (null != listResponse.getObjectList() && !listResponse.getObjectList().isEmpty()) {
            for (ReportChannelDepartRelEntity rel : listResponse.getObjectList()) {
                depts.add(rel.getDepartId());
            }

            Map<String, Object> deptSearch = new HashMap<>();
            deptSearch.put("EQ_ids", depts);
            DepartmentListRequest departmentListRequest = new DepartmentListRequest();
            departmentListRequest.setSearchParams(deptSearch);
            departmentListRequest.setPaging(new Page(Integer.MAX_VALUE));

            DepartmentListResponse departmentListResponse = department.getDepartmentList(departmentListRequest);

            if (null != departmentListResponse.getObjectList() && !departmentListResponse.getObjectList().isEmpty()) {
                for (DepartmentEntity rel : departmentListResponse.getObjectList()) {
                    deptNames.add(rel.getName());
                }
            }

        }

        model.addAttribute("depts", Joiner.on(",").join(deptNames));
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改ReportChannel
     *
     * @param id      ReportChannel页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model, HttpServletRequest request) {

        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        ReportChannelEntity entity = new ReportChannelEntity();
        entity.setCreateTime(new Date());
        entity.setCreater(userEntity.getName());

        List<DepartmentEntity> departmentEntities = new ArrayList<>();

        DepartmentEntity city = null;
        String cityId = dept.getCityID();

        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        city = departmentResponse.getEntity();

        String urlPath = city.getUrlPath();
        Map<String, Object> search = new HashMap<>();
        search.put("EQ_channelId", id);

        ReportChannelDepartRelListRequest reportChannelDepartRelListRequest = new ReportChannelDepartRelListRequest();
        reportChannelDepartRelListRequest.setSearchParams(search);
        reportChannelDepartRelListRequest.setPaging(new Page(Integer.MAX_VALUE));

        ReportChannelDepartRelListResponse listResponse = reportChannelDepartRel.getReportChannelDepartRelList(
                reportChannelDepartRelListRequest);

        List<String> depts = new ArrayList<>();
        if (null != listResponse.getObjectList() && !listResponse.getObjectList().isEmpty()) {
            for (ReportChannelDepartRelEntity rel : listResponse.getObjectList()) {
                depts.add(String.valueOf(rel.getDepartId()));
            }
        }

        departmentEntities = getDepartmentEntities(depts.toArray(new String[depts.size()]), urlPath);

        ReportChannelResponse response = reportChannel.getReportChannelById(id);

        model.addAttribute("departmentList", departmentEntities);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改ReportChannel
     *
     * @param vo      ReportChannel页面表单对象
     * @param result  表单验证数据
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateReportChannel(
            @Valid ReportChannelVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model, HttpServletRequest request
    ) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        ReportChannelEntity 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 {
                String[] department = request.getParameterValues("department");
                if ("1".equalsIgnoreCase(String.valueOf(
                        vo.getEntity().getChannelType())) && (null == department || department.length <= 0)) {
                    model.addAttribute("action", "create");
                    addErrorMessage(model, "请选择部门");
                    return getAutoUrl("form");
                }

                entity.setUpateTime(new Date());
                entity.setLastModifier(userEntity.getName());

                ReportChannelRequest reportChannelRequest = new ReportChannelRequest();
                reportChannelRequest.setEntity(entity);

                ReportChannelRequest request1 = new ReportChannelRequest();
                request1.setEntity(entity);
                ReportChannelResponse reportChannelResponse = reportChannel.updateReportChannels(request1, department);

                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/reportchannel/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询ReportChannel
     *
     * @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);
        }
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        searchParams.put("EQ_city", dept.getDescripition());
        searchParams.put("NOTEQ_status", "3");
        ReportChannelListRequest listRequest = new ReportChannelListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        ReportChannelListResponse response = reportChannel.getReportChannelList(listRequest);

        if (response.getObjectList() != null && !response.getObjectList().isEmpty()) {
            for (ReportChannelEntity channelEntity : response.getObjectList()) {
                channelEntity.setLastModifier("");

                Map<String, Object> search = new HashMap<>();
                search.put("EQ_channelId", channelEntity.getId());

                ReportChannelDepartRelListRequest reportChannelDepartRelListRequest = new ReportChannelDepartRelListRequest();
                reportChannelDepartRelListRequest.setSearchParams(search);
                reportChannelDepartRelListRequest.setPaging(new Page(Integer.MAX_VALUE));

                ReportChannelDepartRelListResponse listResponse = reportChannelDepartRel.getReportChannelDepartRelList(
                        reportChannelDepartRelListRequest);

                List<String> deptNames = new ArrayList<>();

                if (null != listResponse.getObjectList() && !listResponse.getObjectList().isEmpty()) {
                    for (ReportChannelDepartRelEntity rcd : listResponse.getObjectList()) {
                        DepartmentResponse response1 = department.getDepartmentById(rcd.getDepartId());
                        if (response1.getEntity() != null) {
                            deptNames.add(response1.getEntity().getName());
                        }
                    }
                }

                channelEntity.setLastModifier(Joiner.on(",").join(deptNames));
            }
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("reportChannels", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }


}
