package cn.com.countrygarden.bi.main.service.advise.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.advise.*;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysOrganMapper;
import cn.com.countrygarden.bi.main.dto.advise.*;
import cn.com.countrygarden.bi.main.dto.advise.param.*;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.dto.PageDataVo;
import cn.com.countrygarden.bi.main.model.advise.AfAdviseBranchType;
import cn.com.countrygarden.bi.main.model.advise.AfAdviseFeedback;
import cn.com.countrygarden.bi.main.model.advise.AfAdviseNotice;
import cn.com.countrygarden.bi.main.model.advise.AfAdviseProcess;
import cn.com.countrygarden.bi.main.service.advise.IAfAdviseBranchTypeService;
import cn.com.countrygarden.bi.main.service.advise.IAfAdviseFeedbackService;
import cn.com.countrygarden.bi.main.service.advise.IAfAdviseResponsiblerService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.Comparator.comparing;

/**
 * 建言-业务逻辑层实现
 *
 * @author 木木子
 * @email 944528607@qq.com
 * @url
 * @date 2019-04-15
 */
@SuppressWarnings("ALL")
@Service
public class AfAdviseFeedbackServiceImpl implements IAfAdviseFeedbackService {
    @Autowired
    private AfAdviseFeedbackMapper afAdviseFeedbackMapper;
    @Autowired
    private AfAdviseProcessMapper afAdviseProcessMapper;

    @Autowired
    private TbSysOrganService tbSysOrganService;

    @Autowired
    private TbSysOrganMapper tbSysOrganMapper;

    @Autowired
    private AfAdviseResponsiblerMapper afAdviseResponsiblerMapper;

    @Autowired
    private IAfAdviseResponsiblerService afAdviseResponsiblerService;
    @Autowired
    private AfAdviseNoticeMapper afAdviseNoticeMapper;
    @Autowired
    private AfAdviseConfigMapper afAdviseConfigMapper;
    @Autowired
    private IAfAdviseBranchTypeService afAdviseBranchTypeService;

    @Autowired
    private IAfAdviseBranchTypeService adviseBranchTypeService;

    /**
     * 一。非秘密建言
     * 1，没有角色的只能查看到自己的建言
     * 2。有角色的只能已经回复此建言后才能有查看按钮
     * 3。总部管理员没有分配时有查看按钮
     * 二。秘密建言
     * 私密建言只有自己与超级管理员可以列表显示
     * 私密建言只有自己与超级管理员可查看
     * 私密建言只有自己与超级管理员可回复
     * 私密建议只有超级管理员可发布为公告
     * 秘密建议只有超级管理员可撤销公告
     *
     * @param adviseFeedbackParam
     * @param page
     * @param size
     * @return
     */

    @Override
    public Result queryPageList(AdviseFeedbackParam adviseFeedbackParam, int page, int size) {
        BranchTypeParam branchTypeParam = null;
        if (StringUtil.isNotBlank(adviseFeedbackParam.getBranchTypeCode())) {
            branchTypeParam = new BranchTypeParam();
            branchTypeParam.setCode(adviseFeedbackParam.getBranchTypeCode());
        }
        List<AfAdviseBranchType> adviseBranchTypeList = afAdviseBranchTypeService.getUserAdviseBranchRoleCode(branchTypeParam, adviseFeedbackParam.getUserCode());
        if (null == adviseBranchTypeList) {
            Result result = new Result();
            result.setResultMsg(branchTypeParam == null ? "你不属于建言系统的分支类型，无数据展示" : "你不属于建言系统的分支类型，无数据展示");
            result.setData("noRole");
            result.setResultCode(500);
            return result;
        }
        /**
         * 第一步，先得到此用户是什么角色
         * 第二步，根据角色判断显示列表
         */
        adviseFeedbackParam.setBranchTypeCode(StringUtil.isNotBlank(adviseFeedbackParam.getBranchTypeCode()) ? adviseFeedbackParam.getBranchTypeCode() : "advise_juzhele");
        adviseFeedbackParam = afAdviseResponsiblerService.getAdviseResponsiblerDTO(adviseFeedbackParam);
        Page<Object> pageList = PageHelper.startPage(page, size);

        List<AfAdviseFeedbackListVO> adviseFeedbackVOList = afAdviseFeedbackMapper
                .selectAdviseFeedbackList(adviseFeedbackParam);
        int sortNumber = 0;
        for (AfAdviseFeedbackListVO afAdviseFeedbackVO : adviseFeedbackVOList) {
            afAdviseFeedbackVO.setSubmitUserCode(adviseFeedbackParam.getUserCode());
            // 未发布的建言不进行下一步操作
            List<AfAdviseProcess> adviseProcessList = null;
            if (afAdviseFeedbackVO.getState() == 0) {
                afAdviseFeedbackVO = handleListButtonisShow(afAdviseFeedbackVO, adviseFeedbackParam, sortNumber);
                continue;
            }
            AfAdviseProcess adviseProcess = new AfAdviseProcess();
            adviseProcess.setAdviseFeedbackId(afAdviseFeedbackVO.getId());
            adviseProcess.setEnable(1);
            adviseProcess.setState(1);
            adviseProcessList = afAdviseProcessMapper.select(adviseProcess);
            //处理前端的按钮显示问题,只有建言進行中時才需要處理（  状态(0保存,1提交,2完成)）
            adviseFeedbackParam.setNoticeEndType(adviseProcessList.get(adviseProcessList.size() - 1).getProcessType());

            for (AfAdviseProcess afAdviseProcess : adviseProcessList) {
                if (afAdviseProcess.getProcessType() == 0) {
                    afAdviseFeedbackVO.setProcessType0(0);
                    afAdviseFeedbackVO.setUserCode0(afAdviseProcess.getUserCode());
                    afAdviseFeedbackVO.setUserName0(afAdviseProcess.getUserName());
                    afAdviseFeedbackVO.setDateTime0(afAdviseProcess.getAnswerTime());
                } else if (afAdviseProcess.getProcessType() == 1) {
                    afAdviseFeedbackVO.setProcessType1(1);
                    afAdviseFeedbackVO.setUserName1(afAdviseProcess.getUserName());
                    afAdviseFeedbackVO.setUserCode1(afAdviseProcess.getUserCode());
                    afAdviseFeedbackVO.setUserName1(afAdviseProcess.getUserName());
                    afAdviseFeedbackVO.setDateTime1(afAdviseProcess.getAnswerTime());
                } else if (afAdviseProcess.getProcessType() == 2) {
                    afAdviseFeedbackVO.setProcessType2(2);
                    afAdviseFeedbackVO.setDistributionAdviseTypeId(afAdviseProcess.getDistributionAdviseTypeId());
                    afAdviseFeedbackVO.setUserName2(afAdviseProcess.getUserName());
                    afAdviseFeedbackVO.setUserCode2(afAdviseProcess.getUserCode());
                    afAdviseFeedbackVO.setUserName2(afAdviseProcess.getUserName());
                    afAdviseFeedbackVO.setDateTime2(afAdviseProcess.getAnswerTime());
                }
            }
            afAdviseFeedbackVO = handleListButtonisShow(afAdviseFeedbackVO, adviseFeedbackParam, sortNumber);
            if (afAdviseFeedbackVO.getSortNumber() != 10) {
                sortNumber = afAdviseFeedbackVO.getSortNumber() + 1;
            }
        }
        adviseFeedbackVOList.sort(comparing(AfAdviseFeedbackListVO::getSortNumber)
                .thenComparing(AfAdviseFeedbackListVO::getFeedBackCreateBy));
        PageDataVo data = new PageDataVo(pageList);
        data.setData(pageList.getResult());
        AfAdviseFeedbackAddPreVO addProDate = handAddPreMultipleRoles(adviseFeedbackParam);
        Map<String, Object> map = new HashMap<>(2);
        map.put("data", data);
        map.put("addProDate", addProDate);

        return Response.response(map);
    }


    @Override
    public AfAdviseFeedbackListVO handleListButtonisShow(AfAdviseFeedbackListVO afAdviseFeedbackVO, AdviseFeedbackParam adviseFeedbackParam, int sortNumber) {

        /**
         * 列表页的按钮类型：查看，删除，编辑，回复，分配
         * 查看：1.自己的建言自己可查看（条件不限）
         *           2.非自创非私密的建言管理员做了回复后可见
         *           3.非自创私密的建言超级管理员做了回复后可见
         *  删除、编辑：1.若建言为保存状态才可见，
         *                       2.若建言非自创则列表页只展示建言状态为提交的数据
         *                         所以不再做处理，只根据建言状态来判断是否显示按钮
         *
         */
        //自己的建言自己可查看，编辑，删除(若建言是保存状态才能被删除，所以不再做处理，只根据建言状态来判断是否显示删除按钮)
        //建言未提交或者当前登录人非某个角色，则不进行下一步处理
        afAdviseFeedbackVO.setCheck(true);
        //默认排序号为10（因为每次只显示10条数据）

        afAdviseFeedbackVO.setSortNumber(10);

        //保存的建言不做处理
        if (0 == afAdviseFeedbackVO.getState() || null == adviseFeedbackParam.getRole() || !adviseFeedbackParam.getRole()) {
            return afAdviseFeedbackVO;
            //已走完建言流程并且未被发布为公告的做是否显示驳回按钮的处理
        } else if (2 == afAdviseFeedbackVO.getState()) {
            if (null == afAdviseFeedbackVO.getNoticeState() || 1 != afAdviseFeedbackVO.getNoticeState()) {
                if (null != adviseFeedbackParam.getHeadquartersAdminRole() && adviseFeedbackParam.getHeadquartersAdminRole()) {
                    afAdviseFeedbackVO.setReject(true);
                } else if (null != adviseFeedbackParam.getSuperAdminRole() && adviseFeedbackParam.getSuperAdminRole()) {
                    afAdviseFeedbackVO.setReject(true);
                }
            }
            return afAdviseFeedbackVO;
        }
        //1==afAdviseFeedbackVO.getState()的做下面的处理
        //是否私密(0:否，1：是)
        if (0 == afAdviseFeedbackVO.getIsPrivate()) {
            // 得到应该流向的节点
            //节点类型（0项目1区域2总部3类型）
            Integer type = adviseFeedbackParam.getNoticeEndType() + 1;
            if (1 == type && null != adviseFeedbackParam.getRegionAdminRole() && adviseFeedbackParam.getRegionAdminRole()) {
                //是否显示回复按钮(节点1：区域管理员)
                afAdviseFeedbackVO.setIsAnswer(true);
                afAdviseFeedbackVO.setSortNumber(sortNumber);
                afAdviseFeedbackVO.setCheck(false);
            } else if (type == 2 && null != adviseFeedbackParam.getHeadquartersAdminRole() && adviseFeedbackParam.getHeadquartersAdminRole()) {
                //是否显示分配、查看按钮(节点2：总部管理员)
                afAdviseFeedbackVO.setIsDistribute(true);
                afAdviseFeedbackVO.setSortNumber(sortNumber);
                afAdviseFeedbackVO.setCheck(true);
            } else if (type == 3 && null != adviseFeedbackParam.getTypeAdminRole() && adviseFeedbackParam.getTypeAdminRole()) {
                //是否显示回复按钮(节点3：类型管理员)
                if (null != adviseFeedbackParam.getTypeAdminAdviseTypeId() && !adviseFeedbackParam.getTypeAdminAdviseTypeId().isEmpty()) {
                    List<Integer> types = adviseFeedbackParam.getTypeAdminAdviseTypeId();
                    int num = afAdviseFeedbackVO.getDistributionAdviseTypeId();
                    int count = (int) types.stream().filter(item -> item.equals(num)).count();
                    if (count > 0) {
                        afAdviseFeedbackVO.setIsAnswer(true);
                        afAdviseFeedbackVO.setSortNumber(sortNumber);
                        //如果建言是自己创建的可以查看
                        if (adviseFeedbackParam.getUserCode().equals(afAdviseFeedbackVO.getFeedBackCreateBy())) {
                            afAdviseFeedbackVO.setCheck(true);
                        } else {
                            afAdviseFeedbackVO.setCheck(false);
                        }
                    } else {
                        afAdviseFeedbackVO.setCheck(true);
                    }
                }
            }
        } else if (1 == afAdviseFeedbackVO.getIsPrivate()) {
            if (null != adviseFeedbackParam.getSuperAdminRole() && adviseFeedbackParam.getSuperAdminRole()) {
                //是否显示回复按钮,私密建言只能是超级管理员的角色才能回复查看
                afAdviseFeedbackVO.setIsAnswer(true);
                afAdviseFeedbackVO.setSortNumber(sortNumber);
                afAdviseFeedbackVO.setCheck(false);
            }
        }
        return afAdviseFeedbackVO;
    }
    @Override
    public AfAdviseFeedbackOneVO queryById(AdviseFeedbackOneParam adviseFeedbackOneParam, AccessToken accessToken) {
        AfAdviseFeedback afAdviseFeedback = new AfAdviseFeedback();
        afAdviseFeedback.setId(adviseFeedbackOneParam.getAdviseFeedbackId());
        afAdviseFeedback.setState(adviseFeedbackOneParam.getAdviseFeedbackState());
        AfAdviseFeedbackOneVO adviseFeedbackOneVO = afAdviseFeedbackMapper.selectAdviseFeedbackOne(afAdviseFeedback);
        AfAdviseProcessParam afAdviseProcessParam = new AfAdviseProcessParam();
        afAdviseProcessParam.setAdviseFeedbackId(adviseFeedbackOneParam.getAdviseFeedbackId());
        boolean ownCreateBy = adviseFeedbackOneVO.getCreateBy().equals(accessToken.getUserCode());
        // 如果非自己创建的建言与节点，则要求建言已经提交state==1
        afAdviseProcessParam.setState(adviseFeedbackOneParam.getAdviseProcessState());
        afAdviseProcessParam.setOwnCreateBy(ownCreateBy);
        if (ownCreateBy) {
            afAdviseProcessParam.setUserCode(accessToken.getUserCode());
        }
        List<AfAdviseProcessOneVO> adviseProcessOneVOList = afAdviseProcessMapper
                .selectAdviseProcessOneVOList(afAdviseProcessParam);
        if (adviseProcessOneVOList != null && !adviseProcessOneVOList.isEmpty()) {
            adviseFeedbackOneVO.setAdviseProcessOneVOList(adviseProcessOneVOList);
        }

        return adviseFeedbackOneVO;
    }

    @Override
    public Result selectAdviseFeedbackOne(Integer id, AccessToken accessToken) {

        AdviseFeedbackOneParam adviseFeedbackOneParam = new AdviseFeedbackOneParam();
        adviseFeedbackOneParam.setAdviseFeedbackId(id);
        adviseFeedbackOneParam.setAdviseProcessState(1);
        AfAdviseFeedbackOneVO adviseFeedbackOneVO = queryById(adviseFeedbackOneParam, accessToken);

        if (adviseFeedbackOneVO.getAdviseProcessOneVOList() != null
                && !adviseFeedbackOneVO.getAdviseProcessOneVOList().isEmpty()) {

            // 是否查看自己的建言
            int num = adviseFeedbackOneVO.getAdviseProcessOneVOList().size();
            AfAdviseProcessOneVO afAdviseProcess = null;
            //私密建言处理
            for (int i = 0; i < 4; i++) {
                boolean flag = true;
                if (i < num) {
                    afAdviseProcess = adviseFeedbackOneVO.getAdviseProcessOneVOList().get(i);
                } else if (adviseFeedbackOneVO.getState() == 2) {
                    flag = false;
                } else {
                    //私密建言
                    if (null != adviseFeedbackOneVO.getIsPrivate() && 1 == adviseFeedbackOneVO.getIsPrivate()) {
                        afAdviseProcess = new AfAdviseProcessOneVO();
                        afAdviseProcess.setProcessType(4);
                        adviseFeedbackOneVO.getAdviseProcessOneVOList().add(afAdviseProcess);
                        flag = false;
                    } else {

                        //非私密建言
                        int endType = adviseFeedbackOneVO.getAdviseProcessOneVOList().get(adviseFeedbackOneVO.getAdviseProcessOneVOList().size() - 1).getProcessType();
                        //非秘密建言时最后一个节点endType=3（类型管理员）
                        if (3 > endType) {
                            afAdviseProcess = new AfAdviseProcessOneVO();
                            afAdviseProcess.setProcessType(endType + 1);
                            adviseFeedbackOneVO.getAdviseProcessOneVOList().add(afAdviseProcess);
                        }
                    }
                }
                if (afAdviseProcess.getProcessType() == 0) {
                    afAdviseProcess.setProcessTypeName("项目个人");
                } else if (afAdviseProcess.getProcessType() == 1) {
                    afAdviseProcess.setProcessTypeName("区域负责人");
                } else if (afAdviseProcess.getProcessType() == 2) {
                    afAdviseProcess.setProcessTypeName("总部管理员");
                    adviseFeedbackOneVO.setDistributionAdviseTypeId(afAdviseProcess.getDistributionAdviseTypeId());
                } else if (afAdviseProcess.getProcessType() == 3) {
                    afAdviseProcess.setProcessTypeName("类型管理员");

                } else if (afAdviseProcess.getProcessType() == 4) {
                    afAdviseProcess.setProcessTypeName("超級管理员");
                }
                if (!flag) {
                    break;
                }
            }
            if (adviseFeedbackOneVO.getState() == 0) {
                adviseFeedbackOneVO.setStateStr("未发布");
            } else if (adviseFeedbackOneVO.getState() == 2) {
                //如果建言流程已经完成，则处理前端按钮的显示问题
                adviseFeedbackOneVO = editNoticeState(adviseFeedbackOneVO, accessToken);
                adviseFeedbackOneVO.setStateStr("已处理");
            } else {
                adviseFeedbackOneVO.setStateStr("处理中");
            }

        }

        return Response.response(adviseFeedbackOneVO);
    }

    @Override
    public AfAdviseFeedbackOneVO editNoticeState(AfAdviseFeedbackOneVO adviseFeedbackOneVO, AccessToken accessToken) {
        /**
         * 是否前端页面显示发布/撤回按键
         * 显示条件：1.建言流程已经完成
         *           2.此登录账号是超级管理员或总部管理员(只有此两种角色才有发布、撤回公告权限)
         */
        //判断登录人角色是否是超级管理员或总部管理员（其他角色不考虑）
        AdviseFeedbackParam adviseFeedbackParam = new AdviseFeedbackParam();
        adviseFeedbackParam.setUserCode(accessToken.getUserCode());
        adviseFeedbackParam.setAdviseTypeId(adviseFeedbackOneVO.getDistributionAdviseTypeId());
        adviseFeedbackParam = afAdviseResponsiblerService.getAdviseResponsiblerDTO(adviseFeedbackParam);
        if (null == adviseFeedbackParam.getRole() || !adviseFeedbackParam.getRole() || 2 != adviseFeedbackOneVO.getState()) {
            return adviseFeedbackOneVO;
        }
        //此建言是否已经发布为公告
        Condition condition = new Condition(AfAdviseNotice.class);
        condition.createCriteria().andEqualTo("adviseFeedbackId", adviseFeedbackOneVO.getId()).andEqualTo("state", 1);
        int count = afAdviseNoticeMapper.selectCountByCondition(condition);
        if (count > 0) {
            //是否显示撤回按钮
            if (null != adviseFeedbackParam.getSuperAdminRole() && adviseFeedbackParam.getSuperAdminRole()) {
                adviseFeedbackOneVO.setRecall(true);
            } else if (null != adviseFeedbackParam.getHeadquartersAdminRole() && adviseFeedbackParam.getHeadquartersAdminRole()) {
                adviseFeedbackOneVO.setRecall(true);
            }
        } else {
            //是否显示发布按钮
            if (null != adviseFeedbackParam.getSuperAdminRole() && adviseFeedbackParam.getSuperAdminRole()) {

                adviseFeedbackOneVO.setPublish(true);
            } else if (null != adviseFeedbackParam.getHeadquartersAdminRole() && adviseFeedbackParam.getHeadquartersAdminRole()) {

                adviseFeedbackOneVO.setPublish(true);
            }
        }
        return adviseFeedbackOneVO;
    }

    @Override
    public Result addOrEdit(AfAdviseFeedbackAddParam afAdviseFeedbackAddParam, AccessToken accessToken) {
        //目前建言分支类型只考虑“居者乐分支类型”，如后续扩展需要传参进来，所以此处默认值为advise_juzhele
        afAdviseFeedbackAddParam.setBranchTypeCode(StringUtil.isNotBlank(afAdviseFeedbackAddParam.getBranchTypeCode()) ? afAdviseFeedbackAddParam.getBranchTypeCode() : "advise_juzhele");
        //建言一经发布便不能再编辑,删除
        AfAdviseFeedback afAdviseFeedback = new AfAdviseFeedback();
        BeanUtils.copyProperties(afAdviseFeedbackAddParam, afAdviseFeedback);
        afAdviseFeedback.setIsPrivate(afAdviseFeedbackAddParam.getIsPrivate() == null ? 0 : afAdviseFeedbackAddParam.getIsPrivate());
        afAdviseFeedback.setEnable(1);
        if (afAdviseFeedback.getState() == 1) {
            afAdviseFeedback.setReportTime(new Date());
        }
        int count = 0;
        if (afAdviseFeedback.getId() != null && afAdviseFeedback.getId() > 0) {

            afAdviseFeedback.setUpdateBy(accessToken.getUserCode());
            afAdviseFeedback.setUpdateTime(new Date());
            count = afAdviseFeedbackMapper.updateByPrimaryKeySelective(afAdviseFeedback);
        } else {

            afAdviseFeedback.setCreateBy(accessToken.getUserCode());
            afAdviseFeedback.setCreateTime(new Date());
            count = afAdviseFeedbackMapper.insertSelective(afAdviseFeedback);
        }
        // 个人发起建议时要相应在建议节点增加，方便后续查看模块的数据获取，节点内容为0：项目类型
        if (count > 0) {
            AfAdviseProcess afAdviseProcess = new AfAdviseProcess();
            AfAdviseProcess afAdviseProcessOld = new AfAdviseProcess();
            afAdviseProcess.setAdviseFeedbackId(afAdviseFeedback.getId());
            afAdviseProcess.setBranchTypeCode(afAdviseFeedback.getBranchTypeCode());
            afAdviseProcess.setUserCode(accessToken.getUserCode());
            afAdviseProcess.setEnable(1);
            afAdviseProcessOld = afAdviseProcessMapper.selectOne(afAdviseProcess);

            if (afAdviseProcessOld == null) {
                afAdviseProcess.setProcessType(afAdviseFeedbackAddParam.getProcessType() == null ? 0 : afAdviseFeedbackAddParam.getProcessType());
                afAdviseProcess.setState(afAdviseFeedback.getState());
                afAdviseProcess.setContent(afAdviseFeedback.getContent());
                afAdviseProcess.setUserName(afAdviseFeedbackAddParam.getUserName());
                afAdviseProcess.setBranchTypeCode(afAdviseFeedback.getBranchTypeCode());
                afAdviseProcess.setUserCode(afAdviseFeedback.getCreateBy());
                afAdviseProcess.setCreateBy(accessToken.getUserCode());
                afAdviseProcess.setAnswerTime(new Date());
                afAdviseProcess.setCreateTime(new Date());
                count += afAdviseProcessMapper.insertSelective(afAdviseProcess);
            } else {
                afAdviseProcessOld.setProcessType(afAdviseFeedbackAddParam.getProcessType());
                afAdviseProcessOld.setState(afAdviseFeedback.getState());
                afAdviseProcessOld.setContent(afAdviseFeedback.getContent());
                afAdviseProcessOld.setUpdateBy(accessToken.getUserCode());
                afAdviseProcessOld.setUpdateTime(new Date());
                count += afAdviseProcessMapper.updateByPrimaryKeySelective(afAdviseProcessOld);
            }

        }
        return Response.response(count);
    }

    @Override
    public Result del(Integer id) {
        // TODO 发布后不能删除建言
        AfAdviseFeedback afAdviseFeedback = new AfAdviseFeedback();
        afAdviseFeedback.setId(id);
        afAdviseFeedback.setEnable(0);
        int count = afAdviseFeedbackMapper.updateByPrimaryKeySelective(afAdviseFeedback);
        AfAdviseProcess afAdviseProcess = new AfAdviseProcess();
        afAdviseProcess.setId(id);
        afAdviseProcess.setEnable(0);
        Condition condition = new Condition(AfAdviseProcess.class);
        condition.createCriteria().andEqualTo("adviseFeedbackId", id);
        count += afAdviseProcessMapper.updateByConditionSelective(afAdviseProcess, condition);

        return Response.response(count);
    }


    @Override
    public Result getReplyAfAdviseInfo(ReplyAfAdviseParam replyAfAdviseParam, AccessToken accessToken) {
        AdviseFeedbackOneParam adviseFeedbackOneParam = new AdviseFeedbackOneParam();
        adviseFeedbackOneParam.setAdviseFeedbackId(replyAfAdviseParam.getId());
        adviseFeedbackOneParam.setAdviseFeedbackState(1);
        adviseFeedbackOneParam.setAdviseProcessState(1);
        AfAdviseFeedbackOneVO adviseFeedbackOneVO = queryById(adviseFeedbackOneParam, accessToken);
        if (adviseFeedbackOneVO != null && adviseFeedbackOneVO.getAdviseProcessOneVOList() != null
                && !adviseFeedbackOneVO.getAdviseProcessOneVOList().isEmpty()) {
            AfAdviseProcess adviseProcess = new AfAdviseProcess();
            adviseProcess.setAdviseFeedbackId(replyAfAdviseParam.getId());
            int type = 0;
            if (null != adviseFeedbackOneVO.getIsPrivate() && 1 == adviseFeedbackOneVO.getIsPrivate()) {
                type = 4;
            } else {
                type = adviseFeedbackOneVO.getAdviseProcessOneVOList().get(adviseFeedbackOneVO.getAdviseProcessOneVOList().size() - 1).getProcessType() + 1;
            }
            adviseProcess.setProcessType(type);
            adviseProcess.setEnable(1);
            adviseProcess.setState(1);
            int count = afAdviseProcessMapper.selectCount(adviseProcess);
            AfAdviseProcessOneVO afAdviseProcessAdd = null;
            if (count > 0) {
                // 此节点已被回复，不能重复回复建言
                return Response.response("exist");
            } else {
                /**
                 * 1.已经回复的内容不能编辑
                 * 2.当前节点如为保存状态并且是当前登录人处理的数据可以在原基本上编辑
                 */
                //查询此用户是否有保存状态的回复建言
                adviseProcess.setState(0);
                adviseProcess.setUserCode(accessToken.getUserCode());
                adviseProcess = afAdviseProcessMapper.selectOne(adviseProcess);
                if (null != adviseProcess) {
                    afAdviseProcessAdd = new AfAdviseProcessOneVO();
                    BeanUtils.copyProperties(adviseProcess, afAdviseProcessAdd);
                    afAdviseProcessAdd.setEdit(true);
                    afAdviseProcessAdd.setAdviseProcessId(adviseProcess.getId());
                    adviseFeedbackOneVO.getAdviseProcessOneVOList().add(afAdviseProcessAdd);
                }
            }
            for (AfAdviseProcessOneVO afAdviseProcess : adviseFeedbackOneVO.getAdviseProcessOneVOList()) {
                if (afAdviseProcess.getProcessType() == 0) {
                    afAdviseProcess.setProcessTypeName("项目个人");
                } else if (afAdviseProcess.getProcessType() == 1) {
                    afAdviseProcess.setProcessTypeName("区域负责人");
                } else if (afAdviseProcess.getProcessType() == 2) {
                    afAdviseProcess.setProcessTypeName("总部管理员");
                } else if (afAdviseProcess.getProcessType() == 3) {
                    afAdviseProcess.setProcessTypeName("类型管理员");
                } else if (afAdviseProcess.getProcessType() == 4) {
                    afAdviseProcess.setProcessTypeName("超级管理员");
                }
            }
            if (afAdviseProcessAdd == null || !afAdviseProcessAdd.getEdit()) {
                afAdviseProcessAdd = new AfAdviseProcessOneVO();
                afAdviseProcessAdd.setBranchTypeCode(adviseFeedbackOneVO.getBranchTypeCode());
                afAdviseProcessAdd.setProcessType(type);
                if (afAdviseProcessAdd.getProcessType() == 0) {
                    afAdviseProcessAdd.setProcessTypeName("项目个人");
                } else if (afAdviseProcessAdd.getProcessType() == 1) {
                    afAdviseProcessAdd.setProcessTypeName("区域负责人");
                } else if (afAdviseProcessAdd.getProcessType() == 2) {
                    afAdviseProcessAdd.setProcessTypeName("总部管理员");
                } else if (afAdviseProcessAdd.getProcessType() == 3) {
                    afAdviseProcessAdd.setProcessTypeName("类型管理员");
                } else if (afAdviseProcessAdd.getProcessType() == 4) {
                    afAdviseProcessAdd.setProcessTypeName("超级管理员");
                }
                afAdviseProcessAdd.setEdit(true);
                adviseFeedbackOneVO.getAdviseProcessOneVOList().add(afAdviseProcessAdd);
            }
        }
        return Response.response(adviseFeedbackOneVO);
    }

    @Override
    public AfAdviseFeedbackOneVO handleAfAdviseFeedbackOneVODate(ReplyAfAdviseParam replyAfAdviseParam,
                                                                 AccessToken accessToken) {

        AdviseFeedbackOneParam adviseFeedbackOneParam = new AdviseFeedbackOneParam();
        adviseFeedbackOneParam.setAdviseFeedbackId(replyAfAdviseParam.getId());
        adviseFeedbackOneParam.setAdviseFeedbackState(1);
        AfAdviseFeedbackOneVO adviseFeedbackOneVO = queryById(adviseFeedbackOneParam, accessToken);
        if (adviseFeedbackOneVO != null && adviseFeedbackOneVO.getAdviseProcessOneVOList() != null
                && !adviseFeedbackOneVO.getAdviseProcessOneVOList().isEmpty()) {
            AfAdviseProcessOneVO afAdviseProcessAdd = null;
            for (AfAdviseProcessOneVO afAdviseProcess : adviseFeedbackOneVO.getAdviseProcessOneVOList()) {

                if (afAdviseProcess.getProcessType() == 0) {
                    afAdviseProcess.setProcessTypeName("项目个人");
                } else if (afAdviseProcess.getProcessType() == 1) {
                    afAdviseProcess.setProcessTypeName("区域负责人");
                } else if (afAdviseProcess.getProcessType() == 2) {
                    afAdviseProcess.setProcessTypeName("总部管理员");
                } else if (afAdviseProcess.getProcessType() == 3) {
                    afAdviseProcess.setProcessTypeName("类型管理员");
                }
                /**
                 * 1.已经回复的内容不能编辑
                 * 2.当前节点如为保存状态并且是当前登录人处理的数据可以在原基本上编辑
                 */
                if (afAdviseProcess.getState() != 1 && afAdviseProcess.getProcessType().equals(replyAfAdviseParam.getProcessType())
                        && afAdviseProcess.getUserCode().equals(accessToken.getUserCode())) {
                    afAdviseProcess.setEdit(true);

                    afAdviseProcessAdd = afAdviseProcess;
                } else {
                    afAdviseProcess.setEdit(false);
                }
            }
            if (afAdviseProcessAdd == null || !afAdviseProcessAdd.getEdit()) {
                afAdviseProcessAdd = new AfAdviseProcessOneVO();
                afAdviseProcessAdd.setProcessType(replyAfAdviseParam.getProcessType());
                if (afAdviseProcessAdd.getProcessType() == 0) {
                    afAdviseProcessAdd.setProcessTypeName("项目个人");
                } else if (afAdviseProcessAdd.getProcessType() == 1) {
                    afAdviseProcessAdd.setProcessTypeName("区域负责人");
                } else if (afAdviseProcessAdd.getProcessType() == 2) {
                    afAdviseProcessAdd.setProcessTypeName("总部管理员");
                } else if (afAdviseProcessAdd.getProcessType() == 3) {
                    afAdviseProcessAdd.setProcessTypeName("类型管理员");
                }
                afAdviseProcessAdd.setEdit(true);
                adviseFeedbackOneVO.getAdviseProcessOneVOList().add(afAdviseProcessAdd);
            }

        }
        return adviseFeedbackOneVO;
    }

    @Override
    public Result editDate(Integer id, AdviseFeedbackParam adviseFeedbackParam) {
        AfAdviseFeedback adviseFeedback = new AfAdviseFeedback();
        adviseFeedback.setId(id);
        // 只有保存状态的建言才能被编辑
        adviseFeedback.setState(0);
        adviseFeedback.setEnable(1);
        adviseFeedback = afAdviseFeedbackMapper.selectOne(adviseFeedback);
        if (null == adviseFeedback) {
            return Response.response();
        }
        adviseFeedbackParam.setBranchTypeCode(StringUtil.isNotBlank(adviseFeedbackParam.getBranchTypeCode()) ? adviseFeedbackParam.getBranchTypeCode() : "advise_juzhele");
        adviseFeedbackParam = afAdviseResponsiblerService.getAdviseResponsiblerDTO(adviseFeedbackParam);
        AfAdviseFeedbackAddPreVO addProDate = handAddPreMultipleRoles(adviseFeedbackParam);
        AdviseProcessEditVo adviseProcessEditVo = new AdviseProcessEditVo();
        BeanUtils.copyProperties(adviseFeedback, adviseProcessEditVo);
        adviseProcessEditVo.setShowPrivate(addProDate.getShowPrivate());
        //能编辑的建言说明当前节点类型为0，未提交的建言
        adviseProcessEditVo.setProcessType(addProDate.getProcessType());
        return Response.response(adviseProcessEditVo);
    }

    @Override
    public Result addOrEditDistribution(ProcessDistributionParam processDistributionParam, AccessToken accessToken) {

        int count = 0;

        // TODO 暂不知道建言表更新分配人等信息是否有意义，所以暂不处理
        AfAdviseProcess afAdviseProcess = new AfAdviseProcess();
        if (processDistributionParam.getAdviseFeedbackId() != null) {
            //再次校验是否已被分配
            afAdviseProcess.setEnable(1);
            afAdviseProcess.setState(1);
            afAdviseProcess.setProcessType(2);
            afAdviseProcess.setAdviseFeedbackId(processDistributionParam.getAdviseFeedbackId());
            count = afAdviseProcessMapper.selectCount(afAdviseProcess);
            if (count > 0) {

                return Response.response("exist");
            }
            afAdviseProcess.setDistributionAdviseTypeId(processDistributionParam.getDistributionAdviseTypeId());
            afAdviseProcess.setDistributionUserCode(accessToken.getUserCode());
            afAdviseProcess.setDistributionUserName(processDistributionParam.getUserName());
            afAdviseProcess.setDistributionTime(new Date());
            afAdviseProcess.setAnswerTime(new Date());
            afAdviseProcess.setContent("已分配给" + processDistributionParam.getDistributionAdviseTypeName() + "负责人");
            afAdviseProcess.setBranchTypeCode(StringUtils.isNotBlank(processDistributionParam.getBranchTypeCode()) ? processDistributionParam.getBranchTypeCode() : "advise_juzhele");
            afAdviseProcess.setUserCode(accessToken.getUserCode());
            afAdviseProcess.setUserName(processDistributionParam.getUserName());
            afAdviseProcess.setCreateBy(accessToken.getUserCode());
            afAdviseProcess.setCreateTime(new Date());
            count = afAdviseProcessMapper.insertSelective(afAdviseProcess);
        }

        return Response.response(count);
    }

    @Override
    public Result getRegionDate(String organCode, AdviseFeedbackParam adviseFeedbackParam) {
        List<RegionListVO> regionList = tbSysOrganMapper.findArea(null, adviseFeedbackParam.getUserCode());
        return Response.response(regionList);
    }

    @Override
    public AfAdviseFeedbackAddPreVO handAddPreMultipleRoles(AdviseFeedbackParam adviseFeedbackParam) {

        /**
         * 第一步，先得到此用户是什么角色
         * 第二步，根据角色判断显示列表
         */
        AfAdviseFeedbackAddPreVO adviseFeedbackAddPreVO = new AfAdviseFeedbackAddPreVO();
        adviseFeedbackAddPreVO.setIsPrivate(0);
        adviseFeedbackAddPreVO.setShowAddButton(true);
        adviseFeedbackAddPreVO.setShowPrivate(true);
        adviseFeedbackAddPreVO.setProcessType(0);
        //有管理相关角色时
        if (null != adviseFeedbackParam && null != adviseFeedbackParam.getRole() && adviseFeedbackParam.getRole()) {
            adviseFeedbackAddPreVO.setRole(true);
            /**
             * 1.只有是建言的相关管理员时才可以以区域的身份建言
             * 2.当用户不为区域管理员时，不会得到当前登录人所在的区域信息，此处再获取一次
             */
            if (null != adviseFeedbackParam.getRegionAdminRole() && adviseFeedbackParam.getRegionAdminRole()) {
                adviseFeedbackAddPreVO.setRegionAdminRole(true);
                adviseFeedbackAddPreVO.setShowPrivate(true);
                adviseFeedbackAddPreVO.setProcessType(1);
            } else if (null != adviseFeedbackParam.getHeadquartersAdminRole() && adviseFeedbackParam.getHeadquartersAdminRole()) {
                adviseFeedbackAddPreVO.setHeadquartersAdminRole(true);
                //总部管理员默认为私密,直接给超级管理员处理，没得选
                adviseFeedbackAddPreVO.setShowPrivate(false);
                adviseFeedbackAddPreVO.setProcessType(2);
                adviseFeedbackAddPreVO.setIsPrivate(1);
            } else if (null != adviseFeedbackParam.getTypeAdminRole() && adviseFeedbackParam.getTypeAdminRole()) {
                adviseFeedbackAddPreVO.setRegionAdminRole(true);
                //类型管理员默认为私密，直接给超级管理员处理，没得选
                adviseFeedbackAddPreVO.setShowPrivate(false);
                adviseFeedbackAddPreVO.setIsPrivate(1);
                adviseFeedbackAddPreVO.setProcessType(3);
            } else if (null != adviseFeedbackParam.getSuperAdminRole() && adviseFeedbackParam.getSuperAdminRole()) {
                adviseFeedbackAddPreVO.setSuperAdminRole(true);
                //总部管理员默认为私密,直接给超级管理员处理，没得选
                adviseFeedbackAddPreVO.setShowPrivate(true);
                adviseFeedbackAddPreVO.setShowAddButton(false);
            }


        }
        return adviseFeedbackAddPreVO;
    }
}