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

import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.FileVo;
import com.house365.beans.vo.ProjectVo;
import com.house365.commons.system.FastDFSUtil;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.exception.ServiceException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.*;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
import com.house365.ws.beans.util.BaseDecodedMultipartFile;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.*;
import com.vdurmont.emoji.EmojiParser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Project控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-18
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/project")
public class ProjectController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ProjectController.class);

    @Autowired
    private ICustomerProject customerProject;

    @Autowired
    private IProject project;
    @Autowired
    private IUser user;
    @Autowired
    private IProjectUser projectUser;
    @Autowired
    private IDepartment department;
    @Autowired
    private IAttachmentInterface attachmentInterface;
    @Autowired
    private IProjectSaler projectSaler;
    @Autowired
    private IProjectDynamic projectdynamic;
    @Autowired
    private IProjectLogInterface logInterface;


    /**
     * 去新增Project
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model, HttpServletRequest httpRequest) {
        DepartmentEntity departmentEntity = (DepartmentEntity) httpRequest.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        model.addAttribute("city", departmentEntity.getDescripition());
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增Project
     *
     * @param vo     Project页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createProject(@Valid ProjectVo vo, BindingResult result, Model model, HttpServletRequest httpRequest) {

        ProjectEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);

        if (checkDupContractCode(entity.getContractCode(), entity.getCity())) {
            model.addAttribute("action", "create");
            addErrorMessage(model, "该项目已存在!");
            return getAutoUrl("form");
        }
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                DepartmentEntity dept = (DepartmentEntity) httpRequest.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
                entity.setCity(dept.getDescripition());
                entity.setCityName(dept.getName());

                UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
                entity.setCreateUserid(userEntity.getId());
                entity.setCreateUsername(userEntity.getName());
                entity.setUpdateUserid(userEntity.getId());
                entity.setUpdateUsername(userEntity.getName());
                Date now = new Date();
                entity.setCreateTime(now);
                entity.setUpdateTime(now);
                entity.setShowStatus(1);
                ProjectRequest request = new ProjectRequest();
                request.setEntity(entity);
                ProjectResponse response = project.addProject(request, userEntity.getId(), userEntity.getRealName());
                Integer id = response.getEntity().getId();
                return "redirect:/project/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    @RequestMapping(value = "checkDupContractCode/{ContractCode}/{city}", method = {RequestMethod.GET})
    @ResponseBody
    public String checkDupContractCode(@PathVariable(value = "ContractCode") String contractCode, @PathVariable(value = "city") String city,
                                       Model model) {
        if (checkDupContractCode(contractCode, city)) {
            return "true";
        }
        return "false";
    }

    private boolean checkDupContractCode(String contractCode, String city) {
        ProjectListRequest req = new ProjectListRequest();
        Map<String, Object> paraMap = new HashMap<>(10);
        paraMap.put("EQ_contractCode", contractCode);
        paraMap.put("EQ_city", city);
        req.setSearchParams(paraMap);
        req.setLimit(1);
        ProjectListResponse projectList = project.getProjectList(req);
        if (CollectionUtils.isNotEmpty(projectList.getObjectList())) {
            return true;
        }
        return false;
    }

    /**
     * 删除Project
     *
     * @param id Project页面表单对象唯一标识
     * @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++) {
                    project.deleteProjectById(Integer.valueOf(ids[i]));
                }
            } else {
                project.deleteProjectById(Integer.valueOf(id));
            }
        }
    }

    @RequestMapping(value = "detail/{id}", method = {RequestMethod.GET})
    public String detail(@PathVariable(value = "id") Integer id, Model model) {
        ProjectResponse response = project.getProjectById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl();
    }

    /**
     * 去查看Project
     *
     * @param id Project页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model, HttpServletRequest httpRequest) {
        if (httpRequest.getParameter("fromMyProjectsFlag") != null) {
            model.addAttribute("fromMyProjectsFlag", true);
        }
        ProjectResponse response = project.getProjectById(id);
        String business = response.getEntity().getBusiness();
        model.addAttribute("business", business);
        model.addAttribute("entity", response.getEntity());

        Map<String, Object> map = new HashMap<>(10);
        map.put("relateId", id);
        map.put("time", "1");
        List<ProjectLogEntity> list = logInterface.queryByConditions(map);
        List<String> logShowList = new ArrayList<>(15);
        if (CollectionUtils.isNotEmpty(list)) {
            for (ProjectLogEntity p : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //获取String类型的时间
                String showTime = sdf.format(p.getCreateTime());
                if (p.getType() == 1) {
                    String showWord = showTime + "  " + p.getCreateUserName() + " [新建项目]";
                    logShowList.add(showWord);
                } else if (p.getType() == 3) {
                    String showWord = showTime + "  " + p.getCreateUserName() + " [开启项目]";
                    logShowList.add(showWord);
                } else if (p.getType() == 4) {
                    String showWord = showTime + "  " + p.getCreateUserName() + " [关闭项目]";
                    logShowList.add(showWord);
                } else if (p.getType() == 2) {
                    map.put("time", "");
                    map.put("createTime", p.getCreateTime());
                    List<ProjectLogEntity> logList = logInterface.queryByConditions(map);
                    if (CollectionUtils.isNotEmpty(logList)) {
                        StringBuilder builder = new StringBuilder();
                        builder.append(showTime).append("   ").append(p.getCreateUserName()).append("  [编辑项目]  ");
                        for (ProjectLogEntity entity : logList) {
                            builder.append("将  '").append(entity.getModifyName()).append("'  由  '").append(entity.getOldValue())
                                    .append("'  修改为  '").append(entity.getNewValue()).append("' , ");
                        }
                        logShowList.add(builder.toString().substring(0, builder.toString().lastIndexOf(",")));

                    }
                } else {
                    String showWord = showTime + "  " + p.getCreateUserName() + " [无变动]";
                    logShowList.add(showWord);
                }

            }
        }
        model.addAttribute("logList", logShowList);
        return getAutoUrl("form");
    }

    /**
     * 去修改Project
     *
     * @param id Project页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model, HttpServletRequest httpRequest) {
        DepartmentEntity departmentEntity = (DepartmentEntity) httpRequest.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);

        model.addAttribute("city", departmentEntity.getDescripition());
        ProjectResponse response = project.getProjectById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        if (httpRequest.getParameter("fromMyProjectsFlag") != null) {
            model.addAttribute("fromMyProjectsFlag", true);
        }
        String business = response.getEntity().getBusiness();
        model.addAttribute("business", business);
        return getAutoUrl("form");
    }

    /**
     * 修改Project
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateProject(@Valid ProjectVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
                                Model model, HttpServletRequest httpRequest) {
        if (httpRequest.getParameter("fromMyProjectsFlag") != null) {
            model.addAttribute("fromMyProjectsFlag", true);
            redirectAttributes.addAttribute("fromMyProjectsFlag", true);
        }
        ProjectEntity entity = vo.getEntity();
        String selectpicker = vo.getSelectpicker();
        entity.setBusiness(selectpicker);
        entity.setId(id);
        model.addAttribute("entity", entity);
        UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                ProjectRequest request = new ProjectRequest();
                entity.setUpdateUserid(userEntity.getId());
                entity.setUpdateUsername(userEntity.getName());
                entity.setUpdateTime(new Date());
                request.setEntity(entity);
                if (Strings.isNullOrEmpty(entity.getUpdateIp())) {
                    String query = String.valueOf(entity.getBuildingId());
                    switch (entity.getType()) {
                        case "住宅":
                            query += ",1";
                            break;
                        case "写字楼":
                            query += ",2";
                            break;
                        case "别墅":
                            query += ",3";
                            break;
                        case "商业":
                            query += ",4";
                            break;
                        case "公寓":
                            query += ",5";
                            break;
                        default:
                    }

                    ProjectResponse projectEntity = project.getProjectById(id);

                    List<NameValuePair> params = new ArrayList<>();
                    params.add(new BasicNameValuePair("city", projectEntity.getEntity().getCity()));
                    params.add(new BasicNameValuePair("idtype", "listid"));
                    params.add(new BasicNameValuePair("projects", query));

                    try {
                        String houseInfo = HttpClientUtil.doGet("http://newapi.house365.com/projects/batch", params);
                        JSONObject obj = JSONObject.fromObject(houseInfo);

                        if (obj.containsKey("data") && ((JSONObject) obj.get("data")).containsKey(
                                "list") && !((JSONArray) ((JSONObject) obj.get("data")).get("list")).isEmpty()) {
                            String shorttel = String.valueOf(((JSONObject) ((JSONArray) ((JSONObject) obj.get(
                                    "data")).get("list")).get(0)).get("mobileshorttel"));
                            if (!Strings.isNullOrEmpty(shorttel)) {
                                logger.warn("update_hotline_" + shorttel + "_" + projectEntity.getEntity().getBuildingId());
                                project.updateHotline(String.valueOf(projectEntity.getEntity().getBuildingId()), shorttel);
                            }
                        }

                    } catch (IOException ex) {
                        logger.error("调用服务失败", ex);
                    } catch (Throwable ex) {
                        logger.error("调用服务失败", ex);
                    }
                }

                project.updateProject(request, userEntity.getId(), userEntity.getRealName());
                // 更新客户项目中数据
                customerProject.updateProjectNameAndCode(entity.getId(), entity.getProjectName(), entity.getContractCode());

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

    /**
     * 查询Project
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {

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

        String cityId = dept.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        searchParams.put("EQ_cityName", dept.getName());

        if (searchParams.get("GTE_createTimeStart") != null && !Strings.isNullOrEmpty(
                String.valueOf(searchParams.get("GTE_createTimeStart")))) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            try {
                searchParams.put("GTE_createTimeStart", sdf1.format(sdf.parse((String) searchParams.get("GTE_createTimeStart"))));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (searchParams.get("LTE_createTimeEnd") != null && !Strings.isNullOrEmpty(
                String.valueOf(searchParams.get("LTE_createTimeEnd")))) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            Date nextDay = null;
            try {
                nextDay = DateUtil.getNextDay(sdf.parse((String) searchParams.get("LTE_createTimeEnd")));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            searchParams.put("LTE_createTimeEnd", sdf1.format(nextDay));
        }

        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        ProjectListRequest listRequest = new ProjectListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        ProjectListResponse response = project.getProjectList(listRequest);
        if (null != response.getObjectList() && !response.getObjectList().isEmpty()) {
            for (ProjectEntity project : response.getObjectList()) {
                List<UserEntity> userList = projectSaler.queryUserByPrjId(project.getId(), cityCode);
                if (CollectionUtils.isNotEmpty(userList)) {
                    project.setUpdateUsername(userList.get(0).getRealName());
                } else {
                    project.setUpdateUsername("");
                }
            }
        }

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


    /**
     * 楼盘动态发布信息
     *
     * @param number
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "projectdynamic", method = RequestMethod.GET)
    public String projectdynamiclist(Integer number, Model model, HttpServletRequest request) {

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

        String cityId = dept.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        searchParams.put("EQ_dynamiccity", cityCode);
        if (searchParams.get("GTE_createTimeStart") != null && !Strings.isNullOrEmpty(
                String.valueOf(searchParams.get("GTE_createTimeStart")))) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            try {
                searchParams.put("GTE_createTimeStart", sdf1.format(sdf.parse((String) searchParams.get("GTE_createTimeStart"))));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (searchParams.get("LTE_createTimeEnd") != null && !Strings.isNullOrEmpty(
                String.valueOf(searchParams.get("LTE_createTimeEnd")))) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
            Date nextDay = null;
            try {
                nextDay = DateUtil.getNextDay(sdf.parse((String) searchParams.get("LTE_createTimeEnd")));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            searchParams.put("LTE_createTimeEnd", sdf1.format(nextDay));
        }


        ProjectDynamicRequest listRequest = new ProjectDynamicRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);

        List<BaseAttachment> attachments = new ArrayList<>();
        ProjectDynamicResponse response = projectdynamic.getDynamicList(listRequest);
        if (response != null && response.getObjectList() != null) {
            attachments = projectdynamic.queryDynamicPicByResouceType("wechatdynamic");//查询项目动态所有图片信息
            List<ProjectDynamicEntity> pdelist = response.getObjectList();
            for (int j = 0; j < pdelist.size(); j++) {
                List picListByDynamic = new ArrayList();
                String dynamicId = String.valueOf(pdelist.get(j).getDynamicId());
                for (int i = 0; i < attachments.size(); i++) {
                    BaseAttachment ba = attachments.get(i);
                    if (dynamicId.equals(String.valueOf(ba.getResourceId()))) {
                        picListByDynamic.add(ba.getRemotePath());
                    }
                }
                pdelist.get(j).setPicList(picListByDynamic);
                if (pdelist.get(j).getDynamicContent() != null) {
                    pdelist.get(j).setDynamicContent(EmojiParser.parseToUnicode(pdelist.get(j).getDynamicContent()));
                }
            }
        }


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

    @RequestMapping(value = "toJgAdd", method = RequestMethod.GET)
    public String toJgAdd() {
        return getAutoUrl("jgAdd");
    }

    @RequestMapping(value = "jgAdd", method = {RequestMethod.POST})
    public String jgAdd(@Valid ProjectVo vo, BindingResult result, Model model, HttpServletRequest httpRequest) {

        ProjectEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);

        if (checkDupContractCode(entity.getContractCode(), entity.getCity())) {
            addErrorMessage(model, "该项目已存在!");
            return getAutoUrl("jgAdd");
        }
        if (result.hasErrors()) {
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("jgAdd");
        } else {
            try {
                UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
                entity.setCreateUserid(userEntity.getId());
                entity.setCreateUsername(userEntity.getName());
                entity.setUpdateUserid(userEntity.getId());
                entity.setUpdateUsername(userEntity.getName());
                Date now = new Date();
                entity.setCreateTime(now);
                entity.setUpdateTime(now);
                entity.setShowStatus(1);
                ProjectRequest request = new ProjectRequest();
                request.setEntity(entity);
                ProjectResponse response = project.addProject(request, userEntity.getId(), userEntity.getRealName());
                Integer id = response.getEntity().getId();
                return "redirect:/project/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                return getAutoUrl("jgAdd");
            }
        }
    }

    @RequestMapping(value = "close/{id}", method = {RequestMethod.GET})
    public String close(@PathVariable Integer id, HttpServletRequest request) {
        try {
            ProjectResponse rsp = project.getProjectById(id);
            if (rsp.getEntity() != null) {
                ProjectEntity entity = new ProjectEntity();
                entity.setId(id);
                entity.setUpdateTime(new Date());
                entity.setShowStatus(0);

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

                entity.setUpdateUserid(userEntity.getId());
                entity.setUpdateUsername(userEntity.getName());
                entity.setUpdateTime(new Date());

                ProjectRequest projectRequest = new ProjectRequest();
                projectRequest.setEntity(entity);
                project.updateProject(projectRequest, userEntity.getId(), userEntity.getRealName());
                //记录项目操作日志
                ProjectLogEntity logEntity = new ProjectLogEntity();
                logEntity.setRelateId(id);
                logEntity.setType(4);
                logEntity.setModifyColumn("");
                logEntity.setModifyName("");
                logEntity.setOldValue("");
                logEntity.setNewValue("");
                logEntity.setCreateUserId(userEntity.getId());
                logEntity.setCreateUserName(userEntity.getRealName());
                logEntity.setCreateTime(new Date());
                logInterface.save(logEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("关闭项目失败", e);
        }
        return "redirect:/project";
    }

    @RequestMapping(value = "open/{id}", method = {RequestMethod.GET})
    public String open(@PathVariable Integer id, HttpServletRequest request) {
        try {
            ProjectResponse rsp = project.getProjectById(id);
            if (rsp.getEntity() != null) {
                ProjectEntity entity = new ProjectEntity();
                entity.setId(id);
                entity.setUpdateTime(new Date());
                entity.setShowStatus(1);

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

                entity.setUpdateUserid(userEntity.getId());
                entity.setUpdateUsername(userEntity.getName());
                entity.setUpdateTime(new Date());

                ProjectRequest projectRequest = new ProjectRequest();
                projectRequest.setEntity(entity);
                project.updateProject(projectRequest, userEntity.getId(), userEntity.getRealName());
                //记录项目操作日志
                ProjectLogEntity logEntity = new ProjectLogEntity();
                logEntity.setRelateId(id);
                logEntity.setType(3);
                logEntity.setModifyColumn("");
                logEntity.setModifyName("");
                logEntity.setOldValue("");
                logEntity.setNewValue("");
                logEntity.setCreateUserId(userEntity.getId());
                logEntity.setCreateUserName(userEntity.getRealName());
                logEntity.setCreateTime(new Date());
                logInterface.save(logEntity);
            }
        } catch (Exception e) {
            logger.error("开启项目失败", e);
        }
        return "redirect:/project";
    }

    @RequestMapping(value = "assignManager", method = RequestMethod.GET)
    public String assignManager(Model model, HttpServletRequest request, Integer projectId) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String urlLike = userEntity.getDeptUrlPath() + "/";
        userEntity.setProjectAuthorized(false);
        if (PathUtil.isAdminDept(userEntity.getDeptUrlPath())) {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
            urlLike = dept.getUrlPath();
        }

        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("LIKE_deptUrlPath", urlLike);
        Page page = new Page(Integer.MAX_VALUE);
        UserListRequest listRequest = new UserListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        UserListResponse response = user.getUserList(listRequest);
        List<UserEntity> userList = response.getObjectList();
        boolean flag = false;
        for (UserEntity u : userList) {
            if (u.getId().intValue() == userEntity.getId().intValue()) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            userList.add(userEntity);
        }

        if (projectId != null) {

            List<UserEntity> puList = projectUser.queryUserByPrjId(projectId);

            List<UserEntity> addList = new LinkedList<>();
            for (UserEntity pu : puList) {
                for (UserEntity user : userList) {
                    if (user.getId().intValue() == pu.getId().intValue()) {
                        user.setProjectAuthorized(true);
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    addList.add(pu);
                }
                flag = false;
            }

            model.addAttribute("addList", addList);
        }

        model.addAttribute("users", userList);
        return getAutoUrl("assignManager");
    }

    @RequestMapping(value = "assignSaler", method = RequestMethod.GET)
    public String assignSaler(Model model, HttpServletRequest request, Integer projectId) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

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

        String cityId = dept.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        String urlLike = userEntity.getDeptUrlPath();
        userEntity.setProjectAuthorized(false);
        if (PathUtil.isAdminDept(userEntity.getDeptUrlPath())) {
            urlLike = dept.getUrlPath();
        }

        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("REGEXP_deptUrlPath", "^" + urlLike + "$|^" + urlLike + "/");
        searchParams.put("EQ_enabled", "1");
        Page page = new Page(Integer.MAX_VALUE);
        UserListRequest listRequest = new UserListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        UserListResponse response = user.getUserList(listRequest);
        //左侧可指派列表
        List<UserEntity> userList = response.getObjectList();
        boolean flag = false;
        for (UserEntity u : userList) {
            if (u.getId().intValue() == userEntity.getId().intValue()) {
                flag = true;
                break;
            }
        }
        //add login user if not in list
        if (!flag) {
            userList.add(userEntity);
        }

        if (projectId != null) {
            //右侧已指派列表
            List<UserEntity> puList = projectSaler.queryUserByPrjId(projectId, cityCode);

            List<UserEntity> addList = new LinkedList<>();
            for (UserEntity pu : puList) {
                for (UserEntity user : userList) {
                    if (user.getId().intValue() == pu.getId().intValue()) {
                        user.setProjectAuthorized(true);
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    addList.add(pu);
                }
                flag = false;
            }

            model.addAttribute("addList", addList);
        }

        model.addAttribute("users", userList);
        return getAutoUrl("assignSaler");
    }

    @RequestMapping(value = "assign", method = RequestMethod.GET)
    @ResponseBody
    public String assign(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        String userIds = request.getParameter("userIds");
        String projectIds = request.getParameter("projectIds");
        String[] split = projectIds.split(",");

        Integer projectId;
        if (",".equals(userIds)) {
            for (String tmp : split) {
                projectId = Integer.valueOf(tmp);
                projectUser.deleteProjectUserById(projectId);
            }
        } else {
            userIds = userIds.substring(1, userIds.length() - 1);
            String[] userIdArray = userIds.split(",");
            List<String> userIdList = Arrays.asList(userIdArray);
            for (String tmp : split) {
                projectId = Integer.valueOf(tmp);
                projectUser.deleteProjectUserById(projectId);
                ProjectUserEntity entity = null;
                ProjectUserRequest req = new ProjectUserRequest();
                for (String userId : userIdList) {
                    entity = newProjectUserEntity(projectId, Integer.valueOf(userId), userEntity.getId());
                    req.setEntity(entity);
                    projectUser.addProjectUser(req);
                }
            }
        }

        return null;
    }

    @RequestMapping(value = "bindSaler", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse bindSaler(HttpServletRequest request) {
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        String userIds = request.getParameter("userIds");
        String projectIds = request.getParameter("projectIds");
        try {
            projectSaler.doBindSaler(userEntity, userIds, projectIds);
        } catch (ServiceException e) {
            restResponse.setResult("0");
            restResponse.setMsg(e.getMessage());
            logger.error(e.getMessage());
        }
        return restResponse;
    }

    private ProjectUserEntity newProjectUserEntity(Integer projectId, Integer userId, Integer createUserid) {
        ProjectUserEntity entity = new ProjectUserEntity();
        entity.setUserId(userId);
        entity.setProjectId(projectId);
        Date date = new Date();
        entity.setCreateTime(date);
        entity.setUpdateTime(date);
        entity.setCreateUserid(createUserid);
        entity.setUpdateUserid(createUserid);
        return entity;
    }

    @RequestMapping(value = "myProjects", method = RequestMethod.GET)
    public String myProjects(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();

        List<ProjectEntity> projectList = project.getProjectListByUserId(userEntity.getId(), cityCode);
        model.addAttribute("projects", projectList);
        return getAutoUrl();
    }

    @RequestMapping(value = "list/json", method = RequestMethod.GET)
    @ResponseBody
    public String listJson(HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        String limit = request.getParameter("limit");
        Page page = new Page(Integer.valueOf(limit));
        ProjectListRequest listRequest = new ProjectListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        ProjectListResponse response = project.getProjectList(listRequest);
        return JSONArray.fromObject(response.getObjectList()).toString();
    }

    @RequestMapping(value = "attachments", method = RequestMethod.GET)
    public String attachments(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        searchParams.put("EQ_resourceType", "hgs_project");
        String projectId = request.getParameter("projectId");
        if (Strings.isNullOrEmpty(projectId)) {
            return getAutoUrl();
        }
        searchParams.put("EQ_resourceId", projectId);
        AttachmentListRequest listRequest = new AttachmentListRequest();
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        listRequest.setSearchParams(searchParams);
        listRequest.setPaging(page);
        AttachmentListResponse response = attachmentInterface.getAttachments(listRequest);
        List<BaseAttachment> attachments = response.getObjectList();
        model.addAttribute("page", response.getPaging());
        model.addAttribute("attachments", attachments);
        model.addAttribute("projectId", projectId);
        return getAutoUrl();
    }

    /**
     * 添加项目图片
     *
     * @param model
     * @param request
     * @param projectId
     * @return
     */
    @RequestMapping(value = "addAttach/{projectId}", method = RequestMethod.GET)
    public String assignStatus(Model model, HttpServletRequest request, @PathVariable Integer projectId) {
        model.addAttribute("projectId", projectId);
        return getAutoUrl("addAttach");
    }

    @RequestMapping(value = "/addPic/{projectId}/{type}")
    @ResponseBody
    public HResult addPic(@RequestBody FileVo fileVo, @PathVariable int projectId, @PathVariable String type, HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            List<String> fileList = fileVo.getFileList();
            List<String> nameList = fileVo.getNameList();

            List<BaseAttachment> baseAttachments;
            int nextBizType = 0;
            Map<String, Object> searchParams = new HashMap<>(10);
            AttachmentListRequest attachmentListRequest = new AttachmentListRequest();
            Page page = new Page();
            page.setCurrentPage(1);
            page.setPageSize(Integer.MAX_VALUE);
            searchParams.put("EQ_resourceId", projectId);
            searchParams.put("EQ_resourceType", type);
            attachmentListRequest.setOrderColumn("bizType");
            attachmentListRequest.setOrderMode("desc");
            attachmentListRequest.setPaging(page);
            attachmentListRequest.setSearchParams(searchParams);
            AttachmentListResponse attachmentListResponse = attachmentInterface.getAttachments(attachmentListRequest);
            if (attachmentListResponse != null && CollectionUtils.isNotEmpty(attachmentListResponse.getObjectList())) {
                baseAttachments = attachmentListResponse.getObjectList();
                BaseAttachment attachment = baseAttachments.get(0);
                nextBizType = attachment.getBizType() + 1;
            }
            for (int i = 0; i < fileList.size(); i++) {
                String fileName = nameList.get(i);
                String msg = fileList.get(i);

                MultipartFile file = base64ToMultipart(msg);
                if (file == null) {
                    continue;
                }

                FileLocationAttribute fileLocationAttribute = new FileLocationAttribute(file);

                BaseAttachment attachment = new BaseAttachment();
                attachment.setSuffix(fileLocationAttribute.getSuffix());
                String remotePath = FastDFSUtil.uploadFileByStream(file.getInputStream(), file.getOriginalFilename());
                long fileSize = fileLocationAttribute.getSize();
                attachment.setSize(fileSize);
                attachment.setName(fileName);
                attachment.setRemotePath(remotePath);
                attachment.setResourceId(projectId);
                attachment.setResourceType(type);
                attachment.setBizType(nextBizType);
                attachment.setRemoteServerUrlid(userEntity.getId());
                attachment.setRemark(userEntity.getRealName());
                attachment.setCreateTime(new Date());
                AttachmentRequest req = new AttachmentRequest();
                req.setAttachment(attachment);
                nextBizType++;
                attachmentInterface.addAttachment(req);
            }

        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("上传图片出错");
            logger.error("上传图片出错", e);
        }
        return result;
    }

    @RequestMapping(value = "addAttach", method = RequestMethod.POST)
    public String addAttach(MultipartHttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        List<MultipartFile> files = request.getFiles("file");
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String projectId = request.getParameter("projectId");
        if (!Strings.isNullOrEmpty(projectId) && userEntity != null) {
            try {
                String remark = request.getParameter("remark");

                List<BaseAttachment> baseAttachments;
                int nextBizType = 0;

                Map<String, Object> searchParams = new HashMap<>(10);
                AttachmentListRequest attachmentListRequest = new AttachmentListRequest();
                Page page1 = new Page();
                page1.setCurrentPage(1);
                page1.setPageSize(Integer.MAX_VALUE);
                searchParams.put("EQ_resourceId", projectId);
                searchParams.put("EQ_resourceType", "hgs_project");
                attachmentListRequest.setOrderColumn("bizType");
                attachmentListRequest.setOrderMode("desc");
                attachmentListRequest.setPaging(page1);
                attachmentListRequest.setSearchParams(searchParams);
                AttachmentListResponse attachmentListResponse = attachmentInterface.getAttachments(attachmentListRequest);
                if (attachmentListResponse != null && CollectionUtils.isNotEmpty(attachmentListResponse.getObjectList())) {
                    baseAttachments = attachmentListResponse.getObjectList();
                    if (!baseAttachments.isEmpty()) {
                        BaseAttachment attachment = baseAttachments.get(0);
                        nextBizType = attachment.getBizType() + 1;
                    }
                }

                for (MultipartFile file : files) {
                    if (StringUtils.isBlank(file.getName())) {
                        continue;
                    }
                    BaseAttachment attachment = new BaseAttachment();
                    FileLocationAttribute fileLocationAttribute = new FileLocationAttribute(file);
                    long fileSize = fileLocationAttribute.getSize();
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(remark)) {
                        attachment.setName(remark);
                    }
                    attachment.setSize(fileSize);
                    attachment.setSuffix(fileLocationAttribute.getSuffix());
                    String remotePath = FastDFSUtil.uploadFileByStream(file.getInputStream(), file.getOriginalFilename());
                    attachment.setRemotePath(remotePath);
                    attachment.setResourceId(Integer.valueOf(projectId));
                    attachment.setResourceType("hgs_project");
                    attachment.setBizType(nextBizType);
                    attachment.setRemoteServerUrlid(userEntity.getId());
                    attachment.setRemark(userEntity.getRealName());
                    attachment.setCreateTime(new Date());
                    nextBizType++;
                    AttachmentRequest req = new AttachmentRequest();
                    req.setAttachment(attachment);
                    attachmentInterface.addAttachment(req);
                }
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return "redirect:/project/attachments?projectId=" + projectId + "&number=1";
    }

    /**
     * 调用接口同步全链条绑定人员接口至淘房汇
     *
     * @return
     */
    @RequestMapping(value = "/updateData", method = RequestMethod.POST)
    @ResponseBody
    public String updateData() {
        try {
            List<ProjectSalerEntity> list = projectSaler.queryAllList();
            projectSaler.syncData(list);
        } catch (Exception e) {
            logger.error("接口同步全链条绑定人员接口至淘房汇失败");
        }
        return null;
    }

    private static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b;
            b = decoder.decodeBuffer(baseStrs[1]);

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            return new BaseDecodedMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            return null;
        }
    }

    @RequestMapping(value = "/export")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            final String[] excelTitles = {"项目id", "项目名称", "合同号", "项目状态", "业务类型", "关联楼盘", "物业类型", "驻场人员", "创建时间", "状态"};
            List<List<Object>> recordList = new ArrayList<>();

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

            // 获取查询条件
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            searchParams.put("EQ_cityName", dept.getName());

            if (searchParams.get("GTE_createTimeStart") != null && org.apache.commons.lang.StringUtils.isNotBlank(searchParams.get("GTE_createTimeStart").toString())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                try {
                    searchParams.put("GTE_createTimeStart", sdf1.format(sdf.parse((String) searchParams.get("GTE_createTimeStart"))));
                } catch (ParseException e) {
                    logger.error("时间转化失败", e);
                }
            }

            if (searchParams.get("LTE_createTimeEnd") != null && org.apache.commons.lang.StringUtils.isNotBlank(searchParams.get("LTE_createTimeEnd").toString())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                Date nextDay = null;
                try {
                    nextDay = DateUtil.getNextDay(sdf.parse((String) searchParams.get("LTE_createTimeEnd")));
                } catch (ParseException e) {
                    logger.error("时间转化失败", e);
                }
                searchParams.put("LTE_createTimeEnd", sdf1.format(nextDay));
            }

            ProjectListRequest listRequest = new ProjectListRequest();
            listRequest.getPaging().setPageSize(Integer.MAX_VALUE);
            listRequest.getPaging().setCurrentPage(1);
            listRequest.setSearchParams(searchParams);
            ProjectListResponse projectList = project.getProjectList(listRequest);
            if (projectList != null && CollectionUtils.isNotEmpty(projectList.getObjectList())) {
                for (ProjectEntity p : projectList.getObjectList()) {
                    List<Object> record = new ArrayList<>();
                    record.add(p.getId());
                    record.add(p.getProjectName());
                    record.add(p.getContractCode());
                    if (p.getStatus() == 1) {
                        record.add("默认");
                    } else if (p.getStatus() == 2) {
                        record.add("执行中");
                    } else if (p.getStatus() == 3) {
                        record.add("办结");
                    } else if (p.getStatus() == 4) {
                        record.add("合同周期结束");
                    } else if (p.getStatus() == 5) {
                        record.add("终止");
                    } else if (p.getStatus() == 6) {
                        record.add("立项审核中");
                    } else if (p.getStatus() == 7) {
                        record.add("删除");
                    } else {
                        record.add("");
                    }
                    record.add(p.getBusiness());
                    record.add(p.getBuildingName());
                    record.add(p.getType());
                    record.add(p.getUserName());
                    record.add(p.getCreateTime());
                    if (p.getShowStatus() == 0) {
                        record.add("关闭");
                    } else {
                        record.add("开启");
                    }
                    recordList.add(record);
                }
            }
            ExcelUtil.exportExcel("项目数据导出.xlsx", "项目数据", excelTitles, recordList, response);
        } catch (Exception e) {
            logger.error("项目数据导出失败", e);
        }
    }

    /**
     * 同步经管数据至全链条
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateJgData", method = RequestMethod.POST)
    @ResponseBody
    public HResult updateJgData(HttpServletRequest request) {
        HResult result = new HResult();
        try {
            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();
            Map<String, Object> map = new HashMap<>(10);
            map.put("city",cityCode);
            map.put("showStatus",1);
            List<ProjectEntity> projectList = project.queryByCondition(map);
            List<Integer> list = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(projectList)) {
                for (ProjectEntity p : projectList) {
                    list.add(p.getId());
                }
            }
            if (CollectionUtils.isNotEmpty(list)) {
                result = customerProject.updateJgData(list,1,userEntity.getName());
            }
        } catch (Exception e) {
            result.setStatus(500);
            result.setErrorMessage("同步经管数据至全链条失败");
            logger.error("同步经管数据至全链条失败", e);
        }
        return result;
    }

}
