/**
 * Description: 项目日报-城市部门配置控制器
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-08-09 下午 14:31:30
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-08-09   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.entity.CityDepConfigEntity;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CityDepConfigVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.CityDepConfigListRequest;
import com.house365.ws.beans.request.CityDepConfigRequest;
import com.house365.ws.beans.request.DepartmentListRequest;
import com.house365.ws.beans.response.CityDepConfigListResponse;
import com.house365.ws.beans.response.CityDepConfigResponse;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.interfaces.server.ICityDepConfig;
import com.house365.ws.interfaces.server.IDepartment;
import org.apache.commons.collections.map.HashedMap;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目日报-城市部门配置控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2020-08-09
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/citydepconfig")
public class CityDepConfigController extends BaseController {

    /**
     * 自动注入项目日报-城市部门配置WS实现
     */
    @Autowired
    private ICityDepConfig cityDepConfig;

    @Autowired
    private IDepartment departmentService;

    /**
     * 去新增项目日报-城市部门配置
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model, HttpServletRequest request) {
        List<DepartmentEntity> departmentEntities = getDepartmentEntities();
        model.addAttribute("departmentList", departmentEntities);

        List<DepartmentEntity> cityList = new ArrayList<>();
        for (DepartmentEntity dep : departmentEntities) {
            if (null != dep.getParentId() && 1 == dep.getParentId()) {
                cityList.add(dep);
            }
        }
        model.addAttribute("cityList", cityList);

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

    private List<DepartmentEntity> getDepartmentEntities() {
        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);
        return departmentService.getDepartmentList(dlr).getObjectList();
    }

    /**
     * 新增项目日报-城市部门配置
     *
     * @param vo      项目日报-城市部门配置页面表单对象
     * @param result  表单验证数据
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCityDepConfig(
            @Valid CityDepConfigVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model,
            HttpServletRequest request
    ) {
        CityDepConfigEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);

        String[] city = request.getParameterValues("entity.city");
        String[] department = request.getParameterValues("entity.dept");

        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                if (city != null && city.length > 0) {
                    DepartmentResponse drp = departmentService.getDepartmentById(Integer.valueOf(city[0]));
                    Integer deptId = drp.getEntity().getId();
                    CityDepConfigListResponse cclr = getDepts(deptId);
                    if (cclr.getObjectList() != null && !cclr.getObjectList().isEmpty()) {
                        model.addAttribute("action", "create");
                        addErrorMessage(model, "选择的城市已经配置，请选择修改操作");
                        redirectAttributes.addAttribute("error", "选择的城市已经配置，请选择修改操作");
                        return "redirect:/citydepconfig/";
                    }

                    entity.setCity(city[0]);
                    if (department != null && department.length > 0) {
                        entity.setDept(Joiner.on(",").join(department));
                    }

                    CityDepConfigRequest cityDepConfigRequest = new CityDepConfigRequest();
                    cityDepConfigRequest.setEntity(entity);
                    CityDepConfigResponse response = cityDepConfig.addCityDepConfig(cityDepConfigRequest);
                    Integer id = response.getEntity().getId();
                    return "redirect:/citydepconfig/" + id;
                } else {
                    addErrorMessage(model, "请选择城市");
                    model.addAttribute("action", "create");
                    return getAutoUrl("form");
                }
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    private CityDepConfigListResponse getDepts(Integer id) {
        CityDepConfigListRequest cityDepConfigListRequest = new CityDepConfigListRequest();
        Map<String, Object> channelReq = new HashedMap();
        channelReq.put("EQ_city", id);
        cityDepConfigListRequest.setSearchParams(channelReq);
        return cityDepConfig.getCityDepConfigList(cityDepConfigListRequest);
    }

    /**
     * 删除项目日报-城市部门配置
     *
     * @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++) {
                    cityDepConfig.deleteCityDepConfigById(Integer.valueOf(ids[i]));
                }
            } else {
                cityDepConfig.deleteCityDepConfigById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看项目日报-城市部门配置
     *
     * @param id 项目日报-城市部门配置页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        CityDepConfigResponse response = cityDepConfig.getCityDepConfigById(id);
        CityDepConfigEntity entity = response.getEntity();
        DepartmentResponse city = departmentService.getDepartmentById(Integer.valueOf(entity.getCity()));
        entity.setCity(city.getEntity().getName());
        if (!Strings.isNullOrEmpty(entity.getDept())) {
            String dep = entity.getDept();
            String[] deps = dep.split(",");
            List<String> depname = new ArrayList<>();
            for (int i = 0; i < deps.length; i++) {
                DepartmentResponse depe = departmentService.getDepartmentById(Integer.valueOf(deps[i]));
                depname.add(depe.getEntity().getName());
            }
            entity.setDept(Joiner.on(",").join(depname));
        }

        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) {
        CityDepConfigResponse response = cityDepConfig.getCityDepConfigById(id);

        List<DepartmentEntity> departmentEntities = getDepartmentEntities();
        List<DepartmentEntity> cityList = new ArrayList<>();
        for (DepartmentEntity dep : departmentEntities) {
            if (null != dep.getParentId() && 1 == dep.getParentId()) {
                if (dep.getId() == Integer.parseInt(response.getEntity().getCity())) {
                    dep.setType("1");
                } else {
                    dep.setType("0");
                }
                cityList.add(dep);
            }
        }
        model.addAttribute("cityList", cityList);

        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 updateCityDepConfig(
            @Valid CityDepConfigVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model
    ) {
        CityDepConfigEntity 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 {
                CityDepConfigListResponse cclr = getDepts(Integer.valueOf(entity.getCity()));
                if (cclr.getObjectList() != null && !cclr.getObjectList().isEmpty() && !cclr.getObjectList().get(0).getId().equals(id)) {
                    model.addAttribute("action", "create");
                    addErrorMessage(model, "选择的城市已经配置，请选择修改操作");
                    redirectAttributes.addAttribute("error", "选择的城市已经配置，请选择修改操作");
                    return "redirect:/citydepconfig/";
                }

                CityDepConfigRequest request = new CityDepConfigRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") CityDepConfigResponse rersponse = cityDepConfig.updateCityDepConfig(
                        request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/citydepconfig/" + 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);
        }
        CityDepConfigListRequest listRequest = new CityDepConfigListRequest();

        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CityDepConfigListResponse response = cityDepConfig.getCityDepConfigList(listRequest);

        for (CityDepConfigEntity entity : response.getObjectList()) {

            DepartmentResponse city = departmentService.getDepartmentById(Integer.valueOf(entity.getCity()));
            entity.setCity(city.getEntity().getName());
            if (!Strings.isNullOrEmpty(entity.getDept())) {
                String dep = entity.getDept();
                String[] deps = dep.split(",");
                List<String> depname = new ArrayList<>();
                for (int i = 0; i < deps.length; i++) {
                    DepartmentResponse depe = departmentService.getDepartmentById(Integer.valueOf(deps[i]));
                    depname.add(depe.getEntity().getName());
                }
                entity.setDept(Joiner.on(",").join(depname));
            }
        }

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