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.AfAdviseFeedbackMapper;
import cn.com.countrygarden.bi.main.dao.advise.AfAdviseNoticeMapper;
import cn.com.countrygarden.bi.main.dao.advise.AfAdviseProcessMapper;
import cn.com.countrygarden.bi.main.dto.advise.AfAdviseFeedbackOneVO;
import cn.com.countrygarden.bi.main.dto.advise.AfAdviseProcessOneVO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
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.IAfAdviseProcessService;
import cn.com.countrygarden.bi.main.service.advise.util.AdviseUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * 建言处理节点-业务逻辑层实现
 *
 * @author 木木子
 * @email 944528607@qq.com
 * @url
 * @date 2019-04-15
 */
@Service
@Transactional
public class AfAdviseProcessServiceImpl implements IAfAdviseProcessService {
    @Autowired
    private AfAdviseProcessMapper afAdviseProcessMapper;
    @Autowired
    private AfAdviseFeedbackMapper afAdviseFeedbackMapper;
    @Autowired
    private AfAdviseNoticeMapper afAdviseNoticeMapper;
    @Autowired
    private AdviseUtil adviseUtil;

    @Override
    public Result queryPageList(AfAdviseProcess afAdviseProcess, int page, int size) {
        Page<Object> pageList = PageHelper.startPage(page, size);
        Condition condition = new Condition(AfAdviseProcess.class);
//		TODO 添加条件
        afAdviseProcessMapper.selectByCondition(condition);
        PageData data = new PageData(pageList);
        data.setData(pageList.getResult());
        return Response.response(data);
    }

    @Override
    public Result queryById(Integer id) {
        return Response.response(afAdviseProcessMapper.selectByPrimaryKey(id));
    }

    @Override
    public Result addOrEdit(String data, AccessToken accessToken) {
        int count = 0;
        AfAdviseFeedbackOneVO adviseFeedbackOneVO = JSON.parseObject(data, AfAdviseFeedbackOneVO.class);

        if (adviseFeedbackOneVO.getAdviseProcessOneVOList() != null
                && !adviseFeedbackOneVO.getAdviseProcessOneVOList().isEmpty()) {
            // 一次只会回复一条数据，所有只取第一条数据
            AfAdviseProcessOneVO adviseProcessOneVO = adviseFeedbackOneVO.getAdviseProcessOneVOList().get(0);
            if (adviseProcessOneVO.getProcessType().equals(1)) {
                //回复建言前先让定时器处理一波是否超时，因为超时只对区域管理员有限制所以只处理processType==1的
                adviseUtil.timeOutAdviseProcess();
            }
            AfAdviseProcess afAdviseProcessDel = null;
            if (adviseFeedbackOneVO.getState() != null && adviseFeedbackOneVO.getState() == 1) {
                afAdviseProcessDel = new AfAdviseProcess();
                afAdviseProcessDel.setState(1);
                afAdviseProcessDel.setEnable(1);
                afAdviseProcessDel.setProcessType(adviseProcessOneVO.getProcessType());
                afAdviseProcessDel.setAdviseFeedbackId(adviseFeedbackOneVO.getId());
                //保险起见，此处再检证是否已被回复
                if (afAdviseProcessMapper.selectCount(afAdviseProcessDel) > 0) {
                    return Response.response("exist");
                }
            }
            AfAdviseProcess afAdviseProcess = new AfAdviseProcess();
            afAdviseProcess.setProcessType(adviseProcessOneVO.getProcessType());
            afAdviseProcess.setState(adviseProcessOneVO.getState());
            afAdviseProcess.setContent(adviseProcessOneVO.getContent());
            afAdviseProcess.setBranchTypeCode(adviseProcessOneVO.getBranchTypeCode());
            afAdviseProcess.setAnswerTime(new Date());
            afAdviseProcess.setUserName(adviseProcessOneVO.getUserName());
            afAdviseProcess.setUserCode(accessToken.getUserCode());
            afAdviseProcess.setEnable(1);
            if (adviseProcessOneVO.getAdviseProcessId() != null) {

                afAdviseProcess.setId(adviseProcessOneVO.getAdviseProcessId());
                afAdviseProcess.setUpdateBy(accessToken.getUserCode());
                afAdviseProcess.setUpdateTime(new Date());
                count += afAdviseProcessMapper.updateByPrimaryKeySelective(afAdviseProcess);
            } else {
                afAdviseProcess.setAdviseFeedbackId(adviseFeedbackOneVO.getId());
                afAdviseProcess.setCreateBy(accessToken.getUserCode());
                afAdviseProcess.setCreateTime(new Date());
                count += afAdviseProcessMapper.insertSelective(afAdviseProcess);
            }
            // 如果是提交则把此建言回复狀態為保存的数据删除
            if (null != afAdviseProcessDel && adviseProcessOneVO.getState() == 1) {
                afAdviseProcessDel.setState(0);
                count += afAdviseProcessMapper.delete(afAdviseProcessDel);
            }
            if (null != adviseProcessOneVO.getState() && adviseProcessOneVO.getState() == 1) {

                //如果当前的类型节点回复完成，则此建言流程结束，更改建言状态为“完成”
                if (3 == adviseProcessOneVO.getProcessType() || 4 == adviseProcessOneVO.getProcessType()) {
                    AfAdviseFeedback afAdviseFeedback = new AfAdviseFeedback();
                    afAdviseFeedback.setId(adviseFeedbackOneVO.getId());
                    afAdviseFeedback.setState(2);
                    afAdviseFeedback.setEnable(1);
                    count += afAdviseFeedbackMapper.updateByPrimaryKeySelective(afAdviseFeedback);
                }
            }
        }

        return Response.response(count);
    }

    @Override
    public Result del(Integer id) {
        int count = afAdviseProcessMapper.deleteByPrimaryKey(id);
        return Response.response(count);
    }

    @Override
    public Result rejdectProcess(Integer feedbackId, Integer isPrivate) {
        //1.根据建言id删除类型管理员或超级管理员回复的节点
        Condition condition = null;
        condition = new Condition(AfAdviseProcess.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("adviseFeedbackId", feedbackId).andEqualTo("enable", 1);
        if (isPrivate.equals(0)) {
            criteria.andEqualTo("processType", 3);
        } else if (isPrivate.equals(1)) {
            criteria.andEqualTo("processType", 4);
        } else {
            throw new ServiceException("传递的数据有误，请检查");
        }
        int count = afAdviseProcessMapper.deleteByCondition(condition);
        //2.根据建言id删除公告中此建言的相关信息（公告状态为保存或撤回的）
        condition = new Condition(AfAdviseNotice.class);
        condition.createCriteria().andEqualTo("adviseFeedbackId", feedbackId);
        count += afAdviseNoticeMapper.deleteByCondition(condition);
        //3.节点与公告处理完成 后，更改建言的状态
        if (count > 0) {
            AfAdviseFeedback afAdviseFeedback = new AfAdviseFeedback();
            afAdviseFeedback.setId(feedbackId);
            afAdviseFeedback.setState(1);
            count += afAdviseFeedbackMapper.updateByPrimaryKeySelective(afAdviseFeedback);
        }
        return Response.response(count);
    }
}