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


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.annual.entity.BizAnnualDissentInfo;
import com.chinaweal.aiccs.aiccs.annual.entity.EPubObjection;
import com.chinaweal.aiccs.aiccs.annual.entity.dto.AnnualDissentDetailDto;
import com.chinaweal.aiccs.aiccs.annual.service.AnnualDissentInfoService;
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.TSHwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.service.TSHwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
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.MapUtils;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
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.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 * 公示异议记录表 前端控制器
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-04-12
 */
@ApiOperation("年报公示异议接口")
@RestController
@RequestMapping("/annual/dissent")
public class AnnualDissentInfoController extends BaseController {

    @Autowired
    private AnnualDissentInfoService annualDissentInfoService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSTwfProcessNodeService twfProcessNodeService;
    @Autowired
    private TSHwfProcessNodeService hwfProcessNodeService;
    @Autowired
    private BizAnnualDissentInfoService bizAnnualDissentInfoService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    EPubObjectionService ePubObjectionService;

    /**
     * 获取年报公示异议信息分页
     *
     * @param pageParam 分页参数
     * @return 获取结果
     * @author lroyia
     * @since 2021年4月12日 18:01:53
     */
    @ApiOperation("获取年报公示异议信息分页")
    @PostMapping("detail/page")
    public RestResult<IPage<AnnualDissentDetailDto>> getAnnualDissentDetailPage(@ApiParam("分页参数") @RequestBody PageRequestDto pageParam) {
        AssertUtils.isNotNull(pageParam);
        pageParam.checkDefault(1, 10, "dissentDate");
        if (MapUtils.isEmpty(pageParam.getCustomParamMap())){
            Map<String, Object> customParamMap = new HashMap<>();
            pageParam.setCustomParamMap(customParamMap);
        }
        Map<String, Object> customParamMap = pageParam.getCustomParamMap();
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        if(StringUtils.isNotBlank(searchUscc)){
            if(StringUtils.isUscc(searchUscc)){
                customParamMap.put("uniscid",searchUscc);
            }else {
                customParamMap.put("regno",searchUscc);
            }
        }
        return RestResult.ok(annualDissentInfoService.getAnnualDissentDetailPage(new Page<>(pageParam.getCurPage(), pageParam.getPageSize()), customParamMap));
    }

    /**
     * 通过id获取年报公司异议信息
     * @param id 数据id
     * @return  获取结果
     * @author lroyia
     * @since  2021年4月12日 20:09:38
     */
    @ApiOperation("通过id获取年报公示异议信息")
    @GetMapping("detail/{id}")
    public RestResult<?> getAnnualDetailDetailById(@PathVariable @ApiParam("异议记录id") String id){
        LambdaQueryWrapper<EPubObjection> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(EPubObjection :: getObjid ,id);
        EPubObjection ePubObjection = ePubObjectionService.getOne(lambdaQueryWrapper);
//        AnnualDissentDetailDto detailInfo = annualDissentInfoService.getAnnualDissentDetailById(id);
//        Map<String, Object> result = new HashMap<>();
//        result.put("detail", detailInfo);

        Map<String, Object> result = new HashMap<>();
        result.put("detail", ePubObjection);

        List<BizAnnualDissentInfo> bizAnnualDissentInfoList = bizAnnualDissentInfoService.queryByinfoId(ePubObjection.getObjid());
//                .list(new LambdaQueryWrapper<BizAnnualDissentInfo>()
//                        .eq(BizAnnualDissentInfo::getInfoId, ePubObjection.getObjid())
//                        .orderByDesc(BizAnnualDissentInfo::getCreateTime));

        // 如果没处理过待办，则不往下查询
        if(CollectionUtils.isEmpty(bizAnnualDissentInfoList)) return RestResult.ok(result);

        // 获取业务记录信息
        BizAnnualDissentInfo biz = bizAnnualDissentInfoList.get(0);
        result.put("biz", biz);

        // 获取待办信息
        TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, biz.getBizseq()));
        result.put("taskList", taskList);
//        List<TSOpinion> opinionList = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
//                .eq(TSOpinion::getWorkflowid, taskList.getWorkflowid()));
        List<TSOpinion> tsOpinions = opinionService.getOpinionsWithOrg(taskList.getWorkflowid());
        result.put("opinion", tsOpinions);
        List<TSTwfProcessNode> nodes = twfProcessNodeService.list(new LambdaQueryWrapper<TSTwfProcessNode>()
                .eq(TSTwfProcessNode::getProcessid, taskList.getWorkflowid())
                .orderByDesc(TSTwfProcessNode::getCreatedon).orderByAsc(TSTwfProcessNode::getStatus));
        if(CollectionUtils.isEmpty(nodes)){
            List<TSHwfProcessNode> hNodes = hwfProcessNodeService.list(new LambdaQueryWrapper<TSHwfProcessNode>().eq(TSHwfProcessNode::getProcessid, taskList.getWorkflowid()));
            result.put("node", hNodes);
            return RestResult.ok(result);
        }
        result.put("node", nodes);

        return RestResult.ok(result);
    }

    /**
     * 创建年报公示信息异议待办
     * @param dissentId 异议信息id
     * @param finalFeedback 最终反馈信息
     * @param request   请求信息
     * @return  处理结果
     * @author  lroyia
     * @since   2021年4月13日 16:31:30
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("创建年报公示信息异议待办")
    @PostMapping("createTask")
    public RestResult<?> createTask(@ApiParam("异议信息id") String dissentId, @ApiParam("反馈信息") String finalFeedback , HttpServletRequest request){
        AssertUtils.isNotBlank(dissentId);

        // 查询异议信息
//        AnnualDissentDetailDto info = annualDissentInfoService.getAnnualDissentDetailById(dissentId);
        LambdaQueryWrapper<EPubObjection> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(EPubObjection :: getObjid ,dissentId);
        EPubObjection info = ePubObjectionService.getOne(lambdaQueryWrapper);
        if(info == null) return RestResult.error(ResultCode.DATA_NONE);
        if(!Constant.FALSE_0_STR.equals(info.getDispose())) throw new BusinessException("当前反馈信息不可再创建待办");

        AICUser curUser = getLoginUser(request);
        String bizseq = UUID.randomUUID().toString();
        BizAnnualDissentInfo bizInfo = new BizAnnualDissentInfo()
                .setBizseq(bizseq)
                .setInfoId(info.getUniscid())
                .setCreatorId(curUser.getPrimaryKey())
                .setEntname(info.getEntname())
                .setPripid(info.getPripid())
                .setRegNo(info.getRegno())
                .setState(Constant.TRUE_1_STR)
                .setUniscid(info.getUniscid())
                .setFinalFeedback(finalFeedback);

        // 更新附件的业务id
        attachmentService.update(new TSAttachment().setBizseq(bizseq),
                new LambdaUpdateWrapper<TSAttachment>()
                        .eq(TSAttachment::getBizseq, curUser.getPrimaryKey()));

        //待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizseq);
        taskListModel.setBustype(BaseDataConstant.ANNUAL_DISSENT_BIZ);//年报公示信息异议
        taskListModel.setBusname(info.getEntname());
        bizAnnualDissentInfoService.saveAnnualDissentAccept(curUser, taskListModel, bizInfo);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizInfo);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }
        throw new BusinessException("创建年报公示信息异议待办失败");
    }

    /**
     * 进入下一个流程
     * @param request   请求信息
     * @param bizAnnualDissentInfo  业务信息
     * @param opinionModel  处办记录
     * @param tasklistid    待办id
     * @param nextPerformerids  下一个处理人id
     * @param nextPerformerNames    下一个处理人名称
     * @param nextNodeID    下一个节点id
     * @return  处理结果
     * @author lroyia
     * @since  2021年4月13日 16:36:07
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("进入下一个流程")
    @PostMapping("nextProcess")
    public RestResult<?> nextProcess(HttpServletRequest request, BizAnnualDissentInfo bizAnnualDissentInfo, TSOpinion opinionModel,
                                     String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID){
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotBlank(nextPerformerids, nextNodeID, tasklistid);

        Map<String, Object> resultMap = new HashMap<>();
        if(StringUtils.isNotBlank(bizAnnualDissentInfo.getBizseq())){
            String[] ids = StringUtils.split(nextPerformerids, ",");
            String[] names = StringUtils.split(nextPerformerNames, ",");
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            bizAnnualDissentInfoService.nextProcess(user, taskListModel, opinionModel, nextNodeID, ids, names, bizAnnualDissentInfo);
            resultMap.put("bizseq", bizAnnualDissentInfo.getBizseq());
            resultMap.put("workflowid", taskListModel.getWorkflowid());
            resultMap.put("nextNodeID", nextNodeID);
            resultMap.put("tasklistid", tasklistid);
        }
        return RestResult.ok(resultMap);
    }
}

