package com.chinaweal.aiccs.aiccs.annual.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.annual.entity.BizAnnualDissentInfo;
import com.chinaweal.aiccs.aiccs.annual.entity.EPubObjection;
import com.chinaweal.aiccs.aiccs.annual.service.BizAnnualDissentInfoService;
import com.chinaweal.aiccs.aiccs.annual.service.EPubObjectionService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkFlowUtil;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sh
 * @since 2021-10-17
 */
@RestController
@RequestMapping("/ePubObjection")
public class EPubObjectionController extends BaseController {

    @Autowired
    private EPubObjectionService ePubObjectionService;
    @Autowired
    private BizAnnualDissentInfoService bizAnnualDissentInfoService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSTwfProcessNodeService tsTwfProcessNodeService;
    @Autowired
    private TSOpinionService opinionService;

    @RequestMapping("/selectEPubObjectionPage")
    public RestResult<?> selectEPubObjectionPage(@ApiParam("分页参数") @RequestBody PageRequestDto pageParam) {
        AssertUtils.isNotNull(pageParam);
        Map<String,Object> customParamMap = pageParam.getCustomParamMap();
        return RestResult.ok(ePubObjectionService.selectEPubObjectionPage(new Page<>(pageParam.getCurPage(), pageParam.getPageSize()), customParamMap));
    }

    @RequestMapping("/selectById")
    public RestResult<?> selectById(String objid) {
        AssertUtils.isNotNull(objid);
        LambdaQueryWrapper<EPubObjection> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(EPubObjection :: getObjid ,objid);
        return RestResult.ok(ePubObjectionService.getOne(lambdaQueryWrapper));
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/saveAccept")
    public RestResult<?> saveAccept(String objid, HttpServletRequest request){
        AssertUtils.isNotBlank(objid);
        Map<String, Object> result = new HashMap<>();

        LambdaQueryWrapper<BizAnnualDissentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizAnnualDissentInfo::getInfoId,objid);
        BizAnnualDissentInfo bizAnnualDissentInfo = bizAnnualDissentInfoService.getOne(wrapper);
        if (bizAnnualDissentInfo != null) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"已经存在异议反馈流程，不能重复发起!");
        }
//        if (bizAnnualDissentInfo != null) { //已有流程，返回
//            LambdaQueryWrapper<TSTaskList> tswrapper = new LambdaQueryWrapper<>();
//            tswrapper.eq(TSTaskList::getBizseqid,bizAnnualDissentInfo.getBizseq());
//            TSTaskList tsTaskList = taskListService.getOne(tswrapper);
//            result.put("tasklistid", tsTaskList.getTasklistid());
//            result.put("bizseq", tsTaskList.getBizseqid());
//            result.put("workflowId", tsTaskList.getWorkflowid());
//            return RestResult.ok(request);
//        }

        // 创建流程
        AICUser curUser = getLoginUser(request);
        String bizseq = UUID.randomUUID().toString();
        EPubObjection ePubObjection = ePubObjectionService.getById(objid);
        BizAnnualDissentInfo bizInfo = new BizAnnualDissentInfo()
                .setBizseq(bizseq)
                .setInfoId(ePubObjection.getObjid())
                .setCreatorId(curUser.getPrimaryKey())
                .setEntname(ePubObjection.getEntname())
                .setPripid(ePubObjection.getPripid())
                .setRegNo(ePubObjection.getRegno())
                .setState(Constant.TRUE_1_STR)
                .setUniscid(ePubObjection.getUniscid());
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizseq);
        taskListModel.setBustype(BaseDataConstant.ANNUAL_DISSENT_BIZ);//年报公示信息异议
        taskListModel.setBusname(ePubObjection.getEntname());
        bizAnnualDissentInfoService.saveAnnualDissentAccept(curUser, taskListModel, bizInfo);
        ePubObjection.setDispose("0");  //处理中 已提交
        ePubObjectionService.updateById(ePubObjection);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizseq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }
        return RestResult.ok();
    }

    @PostMapping(value = "/next")
    public RestResult<?> next(HttpServletRequest request, BizAnnualDissentInfo bizAnnualDissentInfo, TSOpinion opinionModel,
                              String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID) {
        AICUser user = getLoginUser(request);
        Map<String, Object> resultMap = new HashMap<>();

        LambdaQueryWrapper<BizAnnualDissentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizAnnualDissentInfo::getBizseq,bizAnnualDissentInfo.getBizseq())
                .eq(BizAnnualDissentInfo::getState,"1");
        BizAnnualDissentInfo bizAnnualDissentInfoModel = bizAnnualDissentInfoService.getOne(wrapper);

        TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
        TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
        int order = WorkFlowUtil.checkNextOrder(processNode.getCurrentnode(), nextNodeID);

        if (FlowUtil.ANNUAL_DISSENT_WORKFLOW_HANDLE.equals(nextNodeID) && order>0) { //下一步为审核
            bizAnnualDissentInfoModel.setFinalFeedback(bizAnnualDissentInfo.getFinalFeedback());
        }
        if(StringUtils.isBlank(nextPerformerids)) {
            //回退时不传接收人id
            if(order <0){
                if (taskListModel == null) {
                    return RestResult.error(ResultCode.DATA_NONE);
                }
                List<TSTwfProcessNode> tsTwfProcessNodes = tsTwfProcessNodeService.queryByPROCESSIDAndCURRENTNODE(taskListModel.getWorkflowid(),nextNodeID);
                nextPerformerids = tsTwfProcessNodes.get(0).getCurruserid();
                nextPerformerNames = tsTwfProcessNodeService.queryRealName(tsTwfProcessNodes.get(0).getCurruserid());
            } else {
                // 审批环节不传接收人，查出经办人id
                TSTwfProcessNode tsTwfProcessNode = tsTwfProcessNodeService.queryByPROCESSID(taskListModel.getWorkflowid());
                if(FlowUtil.ANNUAL_DISSENT_WORKFLOW_APPROVE.equals(tsTwfProcessNode.getCurrentnode())
                    || FlowUtil.ANNUAL_DISSENT_WORKFLOW_HANDLE.equals(tsTwfProcessNode.getCurrentnode())) {
                    LambdaQueryWrapper<TSOpinion> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, "0")// 经办为0
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(queryWrapper);
                    if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    nextPerformerids = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                } else {
                    return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
                }
            }
        }
        String[] ids = StringUtils.split(nextPerformerids, Constant.COMMA);
        String[] names = StringUtils.split(nextPerformerNames, Constant.COMMA);
        bizAnnualDissentInfoService.saveAnnualProcess(user, taskListModel, bizAnnualDissentInfoModel, opinionModel, nextNodeID, ids, names);
//            if (ids.length == 1 && StringUtils.equals(user.getPrimaryKey(), ids[0])) {
//                resultMap.put("bizseq", bizAnnualDissentInfoModel.getBizseq());
//                resultMap.put("nextNodeId", nextNodeID);
//                resultMap.put("taskListId", tasklistid);
//                resultMap.put("workFlowId", taskListModel.getWorkflowid());
//            }
        return RestResult.ok(resultMap);
    }

    @PostMapping(value = "/queryAll")
    public RestResult<?> queryAll(String bizseq,String tasklistid) {
        Map<String,Object> rs = new HashMap<>();
        List<BizAnnualDissentInfo> bizAnnualDissentInfos =  bizAnnualDissentInfoService.queryByBizseq(bizseq);
        BizAnnualDissentInfo bizAnnualDissentInfo = bizAnnualDissentInfos.get(0);
        EPubObjection ePubObjection = ePubObjectionService.getById(bizAnnualDissentInfo.getInfoId());
        TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
        List<TSOpinion> tsOpinions = opinionService.getOpinionsWithOrg(taskListModel.getWorkflowid());
        rs.put("bizAnnualDissentInfo",bizAnnualDissentInfo);
        rs.put("ePubObjection",ePubObjection);
        rs.put("taskListModel",taskListModel);
        rs.put("tsOpinions",tsOpinions);
        return RestResult.ok(rs);
    }
}

