package com.chinaweal.aiccs.aiccs.susnate.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.susnate.dto.NateOperCombinedAddDTO;
import com.chinaweal.aiccs.aiccs.susnate.dto.NateOperCombinedDeleteDTO;
import com.chinaweal.aiccs.aiccs.susnate.dto.NateOperCombinedQueryDTO;
import com.chinaweal.aiccs.aiccs.susnate.dto.NateOperCombinedUpdateDTO;
import com.chinaweal.aiccs.aiccs.susnate.entity.ENateOperRegDec;
import com.chinaweal.aiccs.aiccs.susnate.entity.ESusNateOperReg;
import com.chinaweal.aiccs.aiccs.susnate.service.IENateOperRegDecService;
import com.chinaweal.aiccs.aiccs.susnate.service.IESusNateOperRegService;
import com.chinaweal.aiccs.aiccs.susnate.vo.NateOperCombinedVO;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.CommonConstants;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 冒用身份登记信息融合Controller
 * 同时对涉嫌冒用和冒用处理决定两个业务表进行CRUD操作
 *
 * @author iFlow
 * @since 2026-02-06
 */
@Api(tags = "3.冒用身份登记信息融合")
@ApiSort(3)
@RestController
@RequestMapping("/nateOperCombined")
public class NateOperCombinedController extends BaseController {

    @Resource
    private IESusNateOperRegService iESusNateOperRegService;

    @Resource
    private IENateOperRegDecService iENateOperRegDecService;

    @ApiOperation(value = "0.融合新增冒用身份登记信息", position = 0)
    @PostMapping("/addNateOperCombined")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<NateOperCombinedVO> addNateOperCombined(@Valid @RequestBody NateOperCombinedAddDTO dto, BindingResult bindingResult, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            return RestResult.error(ResultCode.PARAM_IS_INVALID, bindingResult.getFieldError().getDefaultMessage());
        }

        String id = StringUtils.getUUID();
        LocalDateTime now = LocalDateTime.now();

        AICUser loginUser = getLoginUser(request);

        // 构建涉嫌冒用信息实体
        ESusNateOperReg susEntity = new ESusNateOperReg();
        susEntity.setPersonateId(id);
        susEntity.setPripid(dto.getPripid());
        susEntity.setEntname(dto.getEntname());
        susEntity.setUniscid(dto.getUniscid());
        susEntity.setRegno(dto.getRegno());
        susEntity.setRegTime(dto.getRegTime());
        susEntity.setRegItem(dto.getRegItem());
        susEntity.setRegOrg(dto.getRegOrg());
        susEntity.setRegOrgCn(dto.getRegOrgCn());
        susEntity.setTel(dto.getTel());
        susEntity.setNoticeFrom(dto.getNoticeFrom());
        susEntity.setNoticeTo(dto.getNoticeTo());
        susEntity.setName(dto.getName());
        susEntity.setHandlRest(dto.getHandlRest());
        susEntity.setHandlRea(dto.getHandlRea());
        susEntity.setHandlReaCn(dto.getHandlReaCn());
        susEntity.setJudAuth(dto.getJudAuth());
        susEntity.setJudAuthCn(dto.getJudAuthCn());
        susEntity.setJudDate(dto.getJudDate());
        susEntity.setDstate(CommonConstants.FALSE_0);
        susEntity.setSExtDataTime(now);
        susEntity.setSExtFromNode(loginUser.getRegionID());

        // 构建冒用处理决定信息实体
        ENateOperRegDec decEntity = new ENateOperRegDec();
        decEntity.setPersonatresId(id);
        decEntity.setPripid(dto.getPripid());
        decEntity.setEntname(dto.getEntname());
        decEntity.setUniscid(dto.getUniscid());
        decEntity.setRegno(dto.getRegno());
        decEntity.setRegOrg(dto.getRegOrg());
        decEntity.setRegOrgCn(dto.getRegOrgCn());
        decEntity.setNoticeContent(dto.getNoticeContent());
        decEntity.setJudAuth(dto.getJudAuth());
        decEntity.setJudAuthCn(dto.getJudAuthCn());
        decEntity.setJudDate(dto.getJudDate());
        decEntity.setNoticedate(dto.getNoticeDate());
        decEntity.setDstate(CommonConstants.FALSE_0);
        decEntity.setSExtDataTime(now);
        susEntity.setSExtFromNode(loginUser.getRegionID());

        // 保存两个实体
        iESusNateOperRegService.save(susEntity);
        iENateOperRegDecService.save(decEntity);

        // 构建返回结果
        NateOperCombinedVO result = new NateOperCombinedVO();
        result.setId(id);
        result.setPripid(dto.getPripid());
        result.setEntname(dto.getEntname());
        result.setUniscid(dto.getUniscid());
        result.setRegno(dto.getRegno());
        result.setRegOrg(dto.getRegOrg());
        result.setRegOrgCn(dto.getRegOrgCn());
        result.setJudAuth(dto.getJudAuth());
        result.setJudAuthCn(dto.getJudAuthCn());
        result.setJudDate(dto.getJudDate());
        result.setRegTime(dto.getRegTime());
        result.setRegItem(dto.getRegItem());
        result.setTel(dto.getTel());
        result.setNoticeFrom(dto.getNoticeFrom());
        result.setNoticeTo(dto.getNoticeTo());
        result.setName(dto.getName());
        result.setHandlRest(dto.getHandlRest());
        result.setHandlRea(dto.getHandlRea());
        result.setHandlReaCn(dto.getHandlReaCn());
        result.setNoticeContent(dto.getNoticeContent());
        result.setNoticeDate(dto.getNoticeDate());

        return RestResult.ok(result);
    }

    @ApiOperation(value = "1.融合修改冒用身份登记信息", position = 1)
    @PostMapping("/updateNateOperCombined")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<NateOperCombinedVO> updateNateOperCombined(@Valid @RequestBody NateOperCombinedUpdateDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return RestResult.error(ResultCode.PARAM_IS_INVALID, bindingResult.getFieldError().getDefaultMessage());
        }

        String id = dto.getId();
        LocalDateTime now = LocalDateTime.now();

        // 构建涉嫌冒用信息实体
        ESusNateOperReg susEntity = new ESusNateOperReg();
        susEntity.setPersonateId(id);
        susEntity.setPripid(dto.getPripid());
        susEntity.setEntname(dto.getEntname());
        susEntity.setUniscid(dto.getUniscid());
        susEntity.setRegno(dto.getRegno());
        susEntity.setRegTime(dto.getRegTime());
        susEntity.setRegItem(dto.getRegItem());
        susEntity.setRegOrg(dto.getRegOrg());
        susEntity.setRegOrgCn(dto.getRegOrgCn());
        susEntity.setTel(dto.getTel());
        susEntity.setNoticeFrom(dto.getNoticeFrom());
        susEntity.setNoticeTo(dto.getNoticeTo());
        susEntity.setName(dto.getName());
        susEntity.setHandlRest(dto.getHandlRest());
        susEntity.setHandlRea(dto.getHandlRea());
        susEntity.setHandlReaCn(dto.getHandlReaCn());
        susEntity.setJudAuth(dto.getJudAuth());
        susEntity.setJudAuthCn(dto.getJudAuthCn());
        susEntity.setJudDate(dto.getJudDate());
        susEntity.setSExtDataTime(now);

        // 构建冒用处理决定信息实体
        ENateOperRegDec decEntity = new ENateOperRegDec();
        decEntity.setPersonatresId(id);
        decEntity.setPripid(dto.getPripid());
        decEntity.setEntname(dto.getEntname());
        decEntity.setUniscid(dto.getUniscid());
        decEntity.setRegno(dto.getRegno());
        decEntity.setRegOrg(dto.getRegOrg());
        decEntity.setRegOrgCn(dto.getRegOrgCn());
        decEntity.setNoticeContent(dto.getNoticeContent());
        decEntity.setJudAuth(dto.getJudAuth());
        decEntity.setJudAuthCn(dto.getJudAuthCn());
        decEntity.setJudDate(dto.getJudDate());
        decEntity.setNoticedate(dto.getNoticeDate());
        decEntity.setSExtDataTime(now);

        // 更新两个实体
        iESusNateOperRegService.updateById(susEntity);
        iENateOperRegDecService.updateById(decEntity);

        // 构建返回结果
        NateOperCombinedVO result = new NateOperCombinedVO();
        result.setId(id);
        result.setPripid(dto.getPripid());
        result.setEntname(dto.getEntname());
        result.setUniscid(dto.getUniscid());
        result.setRegno(dto.getRegno());
        result.setRegOrg(dto.getRegOrg());
        result.setRegOrgCn(dto.getRegOrgCn());
        result.setJudAuth(dto.getJudAuth());
        result.setJudAuthCn(dto.getJudAuthCn());
        result.setJudDate(dto.getJudDate());
        result.setRegTime(dto.getRegTime());
        result.setRegItem(dto.getRegItem());
        result.setTel(dto.getTel());
        result.setNoticeFrom(dto.getNoticeFrom());
        result.setNoticeTo(dto.getNoticeTo());
        result.setName(dto.getName());
        result.setHandlRest(dto.getHandlRest());
        result.setHandlRea(dto.getHandlRea());
        result.setHandlReaCn(dto.getHandlReaCn());
        result.setNoticeContent(dto.getNoticeContent());
        result.setNoticeDate(dto.getNoticeDate());

        return RestResult.ok(result);
    }

    @ApiOperation(value = "2.融合删除冒用身份登记信息（软删除）", position = 2)
    @PostMapping("/deleteNateOperCombined")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Boolean> deleteNateOperCombined(@Valid @RequestBody NateOperCombinedDeleteDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return RestResult.error(ResultCode.PARAM_IS_INVALID, bindingResult.getFieldError().getDefaultMessage());
        }

        String id = dto.getId();
        LocalDateTime now = LocalDateTime.now();
        // 软删除涉嫌冒用信息
        LambdaQueryWrapper<ESusNateOperReg> susWrapper = new LambdaQueryWrapper<>();
        susWrapper.eq(ESusNateOperReg::getPersonateId, id);
        ESusNateOperReg susEntity = iESusNateOperRegService.getOne(susWrapper, false);
        if (susEntity != null) {
            susEntity.setDstate(CommonConstants.DELETED_2);
            susEntity.setSExtDataTime(now);
            iESusNateOperRegService.updateById(susEntity);
        }

        // 软删除冒用处理决定信息
        LambdaQueryWrapper<ENateOperRegDec> decWrapper = new LambdaQueryWrapper<>();
        decWrapper.eq(ENateOperRegDec::getPersonatresId, id);
        ENateOperRegDec decEntity = iENateOperRegDecService.getOne(decWrapper, false);
        if (decEntity != null) {
            decEntity.setDstate(CommonConstants.DELETED_2);
            decEntity.setSExtDataTime(now);
            iENateOperRegDecService.updateById(decEntity);
        }

        return RestResult.ok(true);
    }

    @ApiOperation(value = "3.融合通过id查询冒用身份登记信息", position = 3)
    @GetMapping("/getById/{id}")
    public RestResult<NateOperCombinedVO> getById(@ApiParam(value = "ID", required = true) @PathVariable("id") String id) {
        // 查询涉嫌冒用信息
        LambdaQueryWrapper<ESusNateOperReg> susWrapper = new LambdaQueryWrapper<>();
        susWrapper.eq(ESusNateOperReg::getPersonateId, id);
        ESusNateOperReg susEntity = iESusNateOperRegService.getOne(susWrapper, false);

        // 查询冒用处理决定信息
        LambdaQueryWrapper<ENateOperRegDec> decWrapper = new LambdaQueryWrapper<>();
        decWrapper.eq(ENateOperRegDec::getPersonatresId, id);
        ENateOperRegDec decEntity = iENateOperRegDecService.getOne(decWrapper, false);

        // 构建返回结果
        NateOperCombinedVO result = new NateOperCombinedVO();
        if (susEntity != null) {
            result.setId(susEntity.getPersonateId());
            result.setPripid(susEntity.getPripid());
            result.setEntname(susEntity.getEntname());
            result.setUniscid(susEntity.getUniscid());
            result.setRegno(susEntity.getRegno());
            result.setRegOrg(susEntity.getRegOrg());
            result.setRegOrgCn(susEntity.getRegOrgCn());
            result.setJudAuth(susEntity.getJudAuth());
            result.setJudAuthCn(susEntity.getJudAuthCn());
            result.setJudDate(susEntity.getJudDate());
            result.setRegTime(susEntity.getRegTime());
            result.setRegItem(susEntity.getRegItem());
            result.setTel(susEntity.getTel());
            result.setNoticeFrom(susEntity.getNoticeFrom());
            result.setNoticeTo(susEntity.getNoticeTo());
            result.setName(susEntity.getName());
            result.setHandlRest(susEntity.getHandlRest());
            result.setHandlRea(susEntity.getHandlRea());
            result.setHandlReaCn(susEntity.getHandlReaCn());
        }

        if (decEntity != null) {
            result.setId(decEntity.getPersonatresId());
            result.setPripid(decEntity.getPripid());
            result.setEntname(decEntity.getEntname());
            result.setUniscid(decEntity.getUniscid());
            result.setRegno(decEntity.getRegno());
            result.setRegOrg(decEntity.getRegOrg());
            result.setRegOrgCn(decEntity.getRegOrgCn());
            result.setJudAuth(decEntity.getJudAuth());
            result.setJudAuthCn(decEntity.getJudAuthCn());
            result.setJudDate(decEntity.getJudDate());
            result.setNoticeContent(decEntity.getNoticeContent());
            result.setNoticeDate(decEntity.getNoticedate());
        }

        return RestResult.ok(result);
    }
//
//    @ApiOperation(value = "4.融合分页查询市场主体信息（包含冒用身份登记信息判断）", position = 4)
//    @PostMapping("/listEntBaseWithNateOperCombined")
//    public RestResult<NateOperCombinedEntBaseVO> listEntBaseWithNateOperCombined(@RequestBody BaseQuery<NateOperCombinedEntBaseQueryDTO> query) {
//        NateOperCombinedEntBaseQueryDTO queryDTO = query.getEntity(NateOperCombinedEntBaseQueryDTO.class);
//        if (queryDTO == null) {
//            queryDTO = new NateOperCombinedEntBaseQueryDTO();
//        }
//
//        NateOperCombinedEntBaseVO result = new NateOperCombinedEntBaseVO();
//
//        // 查询涉嫌冒用市场主体信息
//        EntBaseWithSusNateOperRegQueryDTO susQuery = new EntBaseWithSusNateOperRegQueryDTO();
//        susQuery.setUniscid(queryDTO.getUniscid());
//        susQuery.setRegno(queryDTO.getRegno());
////        susQuery.setEntname(queryDTO.getEntname());
////        susQuery.setRegstate(queryDTO.getRegstate());
////        susQuery.setRegorg(queryDTO.getRegorg());
//        susQuery.setSearchUscc(queryDTO.getSearchUscc());
//        susQuery.setHasSusNateOperReg(queryDTO.getHasSusNateOperReg());
//
//        IPage<EntBaseWithSusNateOperRegVO> susData = iESusNateOperRegService.listEntBaseWithSusNateOperReg(
//                new Page<>(query.getCurrent(), query.getSize()),
//                susQuery
//        );
//
//        // 查询冒用处理决定市场主体信息
//        EntBaseWithNateOperRegDecQueryDTO decQuery = new EntBaseWithNateOperRegDecQueryDTO();
//        decQuery.setUniscid(queryDTO.getUniscid());
//        decQuery.setRegno(queryDTO.getRegno());
//        decQuery.setEntname(queryDTO.getEntname());

    /// /        decQuery.setRegstate(queryDTO.getRegstate());
    /// /        decQuery.setRegorg(queryDTO.getRegorg());
//        decQuery.setSearchUscc(queryDTO.getSearchUscc());
//        decQuery.setHasNateOperRegDec(queryDTO.getHasNateOperRegDec());
//
//        IPage<EntBaseWithNateOperRegDecVO> decData = iENateOperRegDecService.listEntBaseWithNateOperRegDec(
//                new Page<>(query.getCurrent(), query.getSize()),
//                decQuery
//        );
//
//        // 融合结果：如果两个表都有数据，优先使用涉嫌冒用的数据，合并has字段
//        if (susData.getRecords() != null && !susData.getRecords().isEmpty()) {
//            EntBaseWithSusNateOperRegVO firstSus = susData.getRecords().get(0);
//            BeanUtils.copyProperties(firstSus, result);
//            result.setHasSusNateOperReg(firstSus.getHasSusNateOperReg());
//            result.setHasNateOperRegDec(queryDTO.getHasNateOperRegDec());
//        } else if (decData.getRecords() != null && !decData.getRecords().isEmpty()) {
//            EntBaseWithNateOperRegDecVO firstDec = decData.getRecords().get(0);
//            BeanUtils.copyProperties(firstDec, result);
//            result.setHasNateOperRegDec(firstDec.getHasNateOperRegDec());
//            result.setHasSusNateOperReg(queryDTO.getHasSusNateOperReg());
//        }
//
//        return RestResult.ok(result);
//    }
    @ApiOperation(value = "5.融合分页查询冒用身份登记信息表", position = 5)
    @PostMapping("/listNateOperCombined")
    public RestResult<IPage<NateOperCombinedVO>> listNateOperCombined(@RequestBody BaseQuery<NateOperCombinedQueryDTO> query) {
        NateOperCombinedQueryDTO queryDTO = query.getEntity(NateOperCombinedQueryDTO.class);
        if (queryDTO == null) {
            queryDTO = new NateOperCombinedQueryDTO();
        }

        // 使用 LEFT JOIN 查询融合数据
        IPage<NateOperCombinedVO> resultPage = iESusNateOperRegService.listNateOperCombined(
                new Page<>(query.getCurrent(), query.getSize()),
                queryDTO
        );

        return RestResult.ok(resultPage);
    }
}