package com.chinaweal.aiccs.aiccs.force.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.business.entity.vo.XrTaskListVo;
import com.chinaweal.aiccs.aiccs.business.service.IXrActivityService;
import com.chinaweal.aiccs.aiccs.force.entity.XrForceDeregisterSpe;
import com.chinaweal.aiccs.aiccs.force.entity.querydto.ForceDeregisterSpeQueryDto;
import com.chinaweal.aiccs.aiccs.force.entity.querydto.ForceDeregisterSpeSaveDto;
import com.chinaweal.aiccs.aiccs.force.entity.vo.XrForceDeregisterSpeVo;
import com.chinaweal.aiccs.aiccs.force.service.IXrForceDeregisterSpeService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.SessionConstants;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.pojo.AICPermission;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 拟强制注销业务表 控制器
 *
 * @author zhouxy
 * @since 2025/9/26
 */
@Api(tags = "拟强制注销公告表")
@RestController
@RequestMapping("/XrForceDeregisterSpe")
@Slf4j
public class XrForceDeregisterSpeController extends BaseController {

    @Resource
    private IXrForceDeregisterSpeService iXrForceDeregisterSpeService;
    @Resource
    private IXrActivityService iXrActivityService;
    @Resource
    private EBaseinfoService iEBaseinfoService;


    @ApiOperation(value = "1.分页查询拟强制注销业务数据", position = 1)
    @PostMapping("/list")
    public RestResult<IPage<XrForceDeregisterSpeVo>> listXrForceDeregisterSpe(@RequestBody BaseQuery<ForceDeregisterSpeQueryDto> query, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_LOGGED_IN);
        }
        IPage<XrForceDeregisterSpeVo> data = iXrForceDeregisterSpeService.listXrForceDeregisterSpe(query, user);
        return RestResult.ok(data);
    }

    @ApiOperation(value = "2.根据登记机关分页显示经营主体", position = 2)
    @PostMapping("/baseinfoListByRegOrg")
    public RestResult<?> baseinfoListByRegOrg(@RequestBody BaseQuery<ForceDeregisterSpeQueryDto> query, HttpServletRequest request) {
        Map<String,Object> rs = new HashMap<>();
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        IPage<EBaseinfo> data = iXrForceDeregisterSpeService.baseinfoListByRegOrg(query, user);
        rs.put("dataPage",data);
        return RestResult.ok(rs);
    }

    @ApiOperation(value = "3.批量启动待办", position = 3)
    @PostMapping("/saveIvdAcceptList")
    public RestResult<XrTaskListVo> saveIvdAcceptList(@RequestBody ForceDeregisterSpeQueryDto queryDto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        String busType = queryDto.getBusType();
        if(StringUtils.isEmpty(busType)){
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        XrTaskListVo xrTaskListVo = new XrTaskListVo(null, null, null);
        if(busType.equals("inclusion")){    //拟强制注销
            if (queryDto.getPripIdList().size() == 0) {
                return RestResult.error(ResultCode.PARAM_IS_BLANK);
            }
            xrTaskListVo = iXrForceDeregisterSpeService.saveSpeAcceptList(queryDto, user);
        } else if(busType.equals("force")){    //强制注销
            if (queryDto.getXrForceDeregisterSpe() == null) {
                return RestResult.error(ResultCode.PARAM_IS_BLANK);
            }
            xrTaskListVo = iXrForceDeregisterSpeService.saveForceAcceptList(queryDto, user);
        }
        return RestResult.ok(xrTaskListVo);
    }

    @ApiOperation(value = "4.业务号批量查询拟强制注销业务", position = 4)
    @GetMapping("/listByBizSeqNo")
    public RestResult<IPage<XrForceDeregisterSpeVo>> listByBizSeqNo(@RequestParam @ApiParam("id") String bizSeqNo,String forceType, Integer current, Integer size, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        LambdaQueryWrapper<XrForceDeregisterSpe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrForceDeregisterSpe::getBizSeqNo, bizSeqNo);
        //判断forceType为不为空
        if(StringUtils.isNotBlank(forceType)){
            queryWrapper.eq(XrForceDeregisterSpe::getForceType, forceType);
        }
        Page<XrForceDeregisterSpe> page = new Page<>(current, size);
        IPage<XrForceDeregisterSpe> pageSpe = iXrForceDeregisterSpeService.page(page, queryWrapper);
        List<XrForceDeregisterSpe> speList = pageSpe.getRecords();
        IPage<XrForceDeregisterSpeVo> pageSpeVo = new Page<>(page.getCurrent(), page.getSize(), pageSpe.getTotal());
        List<XrForceDeregisterSpeVo> speVoList = new ArrayList<>();

        if (!speList.isEmpty()) {
            for (XrForceDeregisterSpe xrForceDeregisterSpe : speList) {
                XrForceDeregisterSpeVo xrForceDeregisterSpeVo = new XrForceDeregisterSpeVo();
                BeanUtils.copyProperties(xrForceDeregisterSpe, xrForceDeregisterSpeVo);
                EBaseinfo eBaseinfo =
                        iEBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, xrForceDeregisterSpe.getPripId()));
                xrForceDeregisterSpeVo.setLeRep(eBaseinfo.getName());
                xrForceDeregisterSpeVo.setOpState(eBaseinfo.getRegstate());
                //判断当前用户所在单位是否是登记机关
                boolean userIsRegOrg = StringUtils.equals(user.getRegionID(), xrForceDeregisterSpe.getRegOrg());
                xrForceDeregisterSpeVo.setUserIsRegOrg(userIsRegOrg);
                speVoList.add(xrForceDeregisterSpeVo);
            }
        }
        return RestResult.ok(pageSpeVo.setRecords(speVoList));
    }

    @ApiOperation(value = "5.获取拟强制注销公告内容", position = 5)
    @PostMapping("/getForceDeregisterContent")
    public RestResult<?> getForceDeregisterContent(@RequestBody ForceDeregisterSpeSaveDto forceSaveDto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        String noticeContent = iXrForceDeregisterSpeService.getForceDeregisterContent(user,forceSaveDto);
        if(noticeContent != null){
            return RestResult.ok(noticeContent);
        } else {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
    }

    @ApiOperation(value = "6.流程控制", position = 6)
    @PostMapping("/processControl")
    public RestResult<?> processControl(@RequestBody @Validated ForceDeregisterSpeSaveDto forceSaveDto, HttpServletRequest request) {
//        SaSession session = StpUtil.getSession();
//        Map<String, Object> dataMap = session.getDataMap();
//        AICUser user = (AICUser) dataMap.get(SessionConstants.AICUSER);
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        if (StringUtils.isEmpty(forceSaveDto.getNextNodeID()) || StringUtils.isEmpty(forceSaveDto.getBizSeqNo())) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        Map<String, AICPermission> aicPermissions = user.getAicPermissions();
        //根据当前流程节点判断权限
//        if (!iXrActivityService.checkPermissionsAndNodeID(aicPermissions, forceSaveDto.getCurrentNodeID(), forceSaveDto.getNextNodeID(),"seriousillegal")) {
//            return RestResult.error(ResultCode.INTERFACE_FORBID_VISIT, "无权操作");
//        }

        String forceType = forceSaveDto.getForceType();
        if(forceType.equals("1")){  //拟强制注销
            iXrForceDeregisterSpeService.processControlSpe(forceSaveDto, user);
        } else if(forceType.equals("0")){   //强制注销
            iXrForceDeregisterSpeService.processControlForce(forceSaveDto, user);
        } else {
            return RestResult.error(ResultCode.PARAM_NOT_COMPLETE);
        }
        return RestResult.ok();
    }

//    @ApiOperation(value = "7.批量列异excel文件导入解析", position = 7)
//    @PostMapping("fileParamExplainLr")
//    public RestResult<?> fileParamExplainLr(HttpServletRequest request, @ApiParam("上传的excel文件") MultipartFile file, String type) {
//        AssertUtils.isNotNull(file);
//        AssertUtils.isNotBlank(type);
//        // 获得上传目录
//        AICUser curUser = getLoginUser(request);
//        if (curUser == null) {
//            throw new BusinessException("登录超时，请重新登录");
//        }
//
//        String bizseq = UUID.randomUUID().toString();
//        Map<String, Object> resultMap = iXrForceDeregisterSpeService.fileParamExplainLr(file,type, bizseq,curUser);
//        return RestResult.ok(resultMap);
//    }

    @ApiOperation(value = "8.根据登记机关分页显示拟强制注销公告数据", position = 8)
    @PostMapping("/forceDeregisterPageByRegOrg")
    public RestResult<?> forceDeregisterPageByRegOrg(@RequestBody BaseQuery<ForceDeregisterSpeQueryDto> query, HttpServletRequest request) {
        Map<String,Object> rs = new HashMap<>();
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        IPage<XrForceDeregisterSpe> data = iXrForceDeregisterSpeService.forceDeregisterPageByRegOrg(query, user);
        rs.put("dataPage",data);
        return RestResult.ok(rs);
    }

    @ApiOperation(value = "9.添加待办关联的强制注销市场主体", position = 9)
    @PostMapping("/addForceDeregisterSpe")
    public RestResult<?> addForceDeregisterSpe(@RequestBody ForceDeregisterSpeQueryDto queryDto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        String bizSeqNo = queryDto.getBizSeqNo();
        List<String> pripIdList = queryDto.getPripIdList();
        if (StringUtils.isEmpty(bizSeqNo) || pripIdList == null || pripIdList.isEmpty()) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        boolean result = iXrForceDeregisterSpeService.addForceDeregisterSpe(bizSeqNo, pripIdList, user);
        return result ? RestResult.ok() : RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
    }

    @ApiOperation(value = "10.删除待办关联的强制注销市场主体", position = 10)
    @PostMapping("/deleteForceDeregisterSpe")
    public RestResult<?> deleteForceDeregisterSpe(@RequestParam @ApiParam("业务表主键") String forceSpeId, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        if (StringUtils.isEmpty(forceSpeId)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        boolean result = iXrForceDeregisterSpeService.deleteForceDeregisterSpe(forceSpeId, user);
        return result ? RestResult.ok() : RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
    }

}
