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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiceps.annual.entity.AnModifyPermit;
import com.chinaweal.aiccs.aiceps.annual.service.AnModifyPermitService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.util.StringUtils;
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 com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 年报修改许可 前端控制器
 * </p>
 *
 * @author lcc
 * @since 2026-01-03
 */
@ApiOperation("年报修改许可接口")
@RestController
@RequestMapping("/anModify")
public class AnModifyPermitController extends BaseController  {

    @Autowired
    private AnModifyPermitService anModifyPermitService;
    @Autowired
    private EBaseinfoService eBaseinfoService;


    @ApiOperation(value = "1.新增信息 ", position = 1)
    @ApiOperationSupport(order = 1)
    @PostMapping("/save")
    public RestResult<AnModifyPermit> savePermit(@RequestBody @Valid AnModifyPermit anModifyPermit, BindingResult bindingResult, HttpServletRequest request) {
        AssertUtils.isBndingValidit(bindingResult);
        AICUser user = getLoginUser(request);

        // 根据uniscid查询企业主体信息
        if (StringUtils.isNotBlank(anModifyPermit.getUniscid())) {
            // 先尝试通过统一社会信用代码查询
            List<EBaseinfo> entList = eBaseinfoService.list(new LambdaQueryWrapper<EBaseinfo>()
                    .eq(EBaseinfo::getUniscid, anModifyPermit.getUniscid()));

            // 如果没找到，再尝试通过注册号查询
            if (entList.isEmpty()) {
                entList = eBaseinfoService.list(new LambdaQueryWrapper<EBaseinfo>()
                        .eq(EBaseinfo::getRegno, anModifyPermit.getUniscid()));
            }

            if (!entList.isEmpty()) {
                EBaseinfo entBase = entList.get(0); // 取第一个匹配的结果
                // 填充企业信息到anModifyPermit对象中
                anModifyPermit.setRegno(entBase.getRegno());           // 注册号
                anModifyPermit.setRegorg(user.getRegionID());         // 登记机关
                anModifyPermit.setRegorgCn(user.getOrgName());     // 登记机关中文
                anModifyPermit.setPripid(entBase.getPripid());         // 企业主键
                anModifyPermit.setEntname(entBase.getEntname());   // 企业名称
            } else {
                return RestResult.error(ResultCode.DATA_NONE, "未找到对应的企业主体信息");
            }
            anModifyPermit.setCreateId(getLoginUser(request).getPrimaryKey());
            anModifyPermit.setUpdateId(getLoginUser(request).getPrimaryKey());
            anModifyPermit.setCreateTime(LocalDateTime.now());
            anModifyPermit.setUpdateTime(LocalDateTime.now());
            anModifyPermitService.save(anModifyPermit);
            return RestResult.ok(anModifyPermit);
        } else {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "统一社会信用代码不能为空");
        }
    }

    @ApiOperation(value = "2.删除信息 ", position = 2)
    @PostMapping("/delete")
    public RestResult<String> removePermit(@RequestParam @ApiParam("id") String id) {
        if(StringUtils.isBlank(id)){
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        AnModifyPermit anModifyPermit = null;
        anModifyPermit = anModifyPermitService.getById(id);
        if(anModifyPermit != null){
            anModifyPermitService.removeById(anModifyPermit);
        }

        return RestResult.ok();
    }

    @ApiOperation(value = "3.修改信息 ", position = 3)
    @PostMapping("/update")
    public RestResult<String> updatePermit(@RequestBody @Valid AnModifyPermit anModifyPermit, BindingResult bindingResult, HttpServletRequest request) {
        AssertUtils.isBndingValidit(bindingResult);
        anModifyPermit.setUpdateId(getLoginUser(request).getPrimaryKey());
        anModifyPermit.setUpdateTime(LocalDateTime.now());
        anModifyPermitService.updateById(anModifyPermit);
        return RestResult.ok();
    }

    @ApiOperation(value = "4.查询信息 ", position = 4)
    @GetMapping("/get")
    public RestResult<AnModifyPermit> getPermit(@RequestParam @ApiParam("id") Serializable id) {
        AnModifyPermit anModifyPermit = anModifyPermitService.getById(id);
        return RestResult.ok(anModifyPermit);
    }

    @ApiOperation(value = "5.分页查询信息 ", position = 5)
    @PostMapping("/list")
    public RestResult<IPage<AnModifyPermit>> listPermit(@RequestBody PageRequestDto pageRequestDto) {
        IPage<AnModifyPermit> data = anModifyPermitService.defaultPaging(pageRequestDto, queryWrapper -> {
            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
            if (customParamMap == null) return;
            // 统一码
            String uniscid = StringUtils.tranObject(customParamMap.get("uniscid"));
            if (StringUtils.isNotBlank(uniscid)) {
                queryWrapper.lambda().eq(AnModifyPermit::getUniscid, uniscid);
            }
        }, null);

        // 对查询结果进行处理，补充缺失的entname和regorgcn字段
        if (data != null && data.getRecords() != null && !data.getRecords().isEmpty()) {
            for (AnModifyPermit permit : data.getRecords()) {
                // 如果entname或regorgcn为空，查询EBaseinfo补充信息
                if (StringUtils.isBlank(permit.getEntname()) || StringUtils.isBlank(permit.getRegorgCn())) {
                    if (StringUtils.isNotBlank(permit.getUniscid())) {
                        // 先尝试通过统一社会信用代码查询
                        List<EBaseinfo> entList = eBaseinfoService.list(new LambdaQueryWrapper<EBaseinfo>()
                                .eq(EBaseinfo::getUniscid, permit.getUniscid()));

                        // 如果没找到，再尝试通过注册号查询
                        if (entList.isEmpty()) {
                            entList = eBaseinfoService.list(new LambdaQueryWrapper<EBaseinfo>()
                                    .eq(EBaseinfo::getRegno, permit.getUniscid()));
                        }

                        if (!entList.isEmpty()) {
                            EBaseinfo entBase = entList.get(0);
                            // 补充缺失的字段
                            if (StringUtils.isBlank(permit.getEntname())) {
                                permit.setEntname(entBase.getEntname());
                            }
                            if (StringUtils.isBlank(permit.getRegorgCn())) {
                                permit.setRegorgCn(entBase.getRegorgCn());
                            }
                        }
                    }
                }
            }
        }

        return RestResult.ok(data);
    }

    @ApiOperation(value = "检查市场主体是否存在", position = 6)
    @GetMapping("/checkEBaseInfo")
    public RestResult<?> checkEBaseInfo(@RequestParam @ApiParam("uniscid") Serializable uniscid) {
        List<EBaseinfo> list = eBaseinfoService.list(new LambdaQueryWrapper<EBaseinfo>()
                .eq(EBaseinfo::getUniscid, uniscid)
                .or().eq(EBaseinfo::getRegno, uniscid));
        if(list.isEmpty()){
            return RestResult.error(ResultCode.DATA_NONE,"无法查询到该主体");
        } else {
            return RestResult.ok();
        }
    }

}
