package com.chinaweal.aiccs.aiccs.revoke.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.revoke.entity.AnnouncementTaskListDetail;
import com.chinaweal.aiccs.aiccs.revoke.entity.Revokelist;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.AnnouncementTaskListDetailAddDto;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.AnnouncementTaskListDetailAddResultDto;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.AnnouncementTaskListDetailQueryDto;
import com.chinaweal.aiccs.aiccs.revoke.service.AnnouncementTaskListDetailService;
import com.chinaweal.aiccs.aiccs.revoke.service.RevokelistService;
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.base.query.BaseQuery;
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.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 公告任务名单详细名录 Controller
 *
 * @author system
 * @since 2026/2/26
 **/
@Api(tags = "公告任务名单详细名录相关接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("announcement/task/detail")
public class AnnouncementTaskListDetailController extends BaseController {

    private final EBaseinfoService eBaseinfoService;
    private final AnnouncementTaskListDetailService announcementTaskListDetailService;
    private final RevokelistService revokelistService;

    /**
     * 新增公告任务名单详细名录
     *
     * @return 新增结果
     */
    @ApiOperation("新增公告任务名单详细名录")
    @PostMapping("/add")
    public RestResult<?> add(@RequestBody AnnouncementTaskListDetailAddDto dto, HttpServletRequest request) {
        List<String> pripidList = dto.getPripidList();
        String taskListId = dto.getTaskListId();
        AssertUtils.isNotBlank(taskListId);
        AssertUtils.isNotEmpty(pripidList);

        AICUser loginUser = getLoginUser(request);
        LocalDateTime now = LocalDateTime.now();
        List<String> successList = new ArrayList<>();
        List<String> failList = new ArrayList<>();
        for (String each : pripidList) {
            EBaseinfo eBaseinfo = eBaseinfoService.getById(each);
            if (eBaseinfo == null) {
                failList.add(each);
                continue;
            }
            AnnouncementTaskListDetail one = announcementTaskListDetailService.lambdaQuery().eq(AnnouncementTaskListDetail::getPripid, each)
                    .eq(AnnouncementTaskListDetail::getTaskListId, taskListId).eq(AnnouncementTaskListDetail::getDelFlag, 0).last("limit 1").one();
            if(one != null){
                successList.add(each);
                continue;
            }
            AnnouncementTaskListDetail announcementTaskListDetail = new AnnouncementTaskListDetail();
            announcementTaskListDetail.setCreateTime(now);
            announcementTaskListDetail.setUpdateTime(now);
            announcementTaskListDetail.setCreateUserId(loginUser.getPrimaryKey());
            announcementTaskListDetail.setUpdateUserId(loginUser.getPrimaryKey());
            announcementTaskListDetail.setDelFlag("0");
            announcementTaskListDetail.setPripid(each);
            announcementTaskListDetail.setTaskListId(taskListId);
            announcementTaskListDetail.setUniscid(eBaseinfo.getUniscid());
            announcementTaskListDetail.setRegno(eBaseinfo.getRegno());
            announcementTaskListDetail.setEntname(eBaseinfo.getEntname());
            announcementTaskListDetail.setEnttype(eBaseinfo.getEnttype());
            announcementTaskListDetail.setIndustryphy(eBaseinfo.getIndustryphy());
            announcementTaskListDetail.setIndustryco(eBaseinfo.getIndustryco());
            Revokelist revokelist = revokelistService.lambdaQuery().eq(Revokelist::getPripid, each)
                    .eq(Revokelist::getState, "1").last("limit 1").one();
            if(revokelist != null){
                announcementTaskListDetail.setRevoketime(revokelist.getRevokedate().toLocalDate());
            }
            announcementTaskListDetailService.save(announcementTaskListDetail);
            successList.add(each);
        }
        AnnouncementTaskListDetailAddResultDto resultDto = new AnnouncementTaskListDetailAddResultDto();
        resultDto.setSuccessList(successList);
        resultDto.setFailList(failList);
        return RestResult.ok(resultDto);
    }

    /**
     * 更新公告任务名单详细名录
     *
     * @param announcementTaskListDetail 公告任务名单详细名录信息
     * @return 更新结果
     */
    @ApiOperation("更新公告任务名单详细名录")
    @PostMapping("/update")
    public RestResult<?> update(@RequestBody AnnouncementTaskListDetail announcementTaskListDetail, HttpServletRequest request) {
        AssertUtils.isNotNull(announcementTaskListDetail);
        AssertUtils.isNotBlank(announcementTaskListDetail.getId(), "主键ID不能为空");

        AnnouncementTaskListDetail existEntity = announcementTaskListDetailService.getById(announcementTaskListDetail.getId());
        if (existEntity == null) {
            return RestResult.error(ResultCode.DATA_NONE, "数据不存在");
        }
        AICUser loginUser = getLoginUser(request);
        announcementTaskListDetail.setUpdateTime(LocalDateTime.now());
        announcementTaskListDetail.setUpdateUserId(loginUser.getPrimaryKey());
        boolean update = announcementTaskListDetailService.updateById(announcementTaskListDetail);
        if (update) {
            return RestResult.ok(announcementTaskListDetail);
        }
        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
    }

    /**
     * 删除公告任务名单详细名录（逻辑删除）
     *
     * @param id 主键ID
     * @return 删除结果
     */
    @ApiOperation("删除公告任务名单详细名录")
    @PostMapping("/delete/{id}")
    public RestResult<?> delete(@ApiParam("主键ID") @PathVariable String id, HttpServletRequest request) {
        AssertUtils.isNotBlank(id);

        AnnouncementTaskListDetail existEntity = announcementTaskListDetailService.getById(id);
        if (existEntity == null) {
            return RestResult.error(ResultCode.DATA_NONE, "数据不存在");
        }

        AICUser loginUser = getLoginUser(request);
        AnnouncementTaskListDetail updateEntity = new AnnouncementTaskListDetail();
        updateEntity.setId(id);
        updateEntity.setDelFlag("1");
        updateEntity.setUpdateTime(LocalDateTime.now());
        updateEntity.setUpdateUserId(loginUser.getPrimaryKey());

        boolean update = announcementTaskListDetailService.updateById(updateEntity);
        if (update) {
            return RestResult.ok();
        }
        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
    }

    /**
     * 根据ID查询公告任务名单详细名录
     *
     * @param id 主键ID
     * @return 查询结果
     */
    @ApiOperation("根据ID查询公告任务名单详细名录")
    @GetMapping("/get/{id}")
    public RestResult<?> getById(@ApiParam("主键ID") @PathVariable String id) {
        AssertUtils.isNotBlank(id);

        AnnouncementTaskListDetail announcementTaskListDetail = announcementTaskListDetailService.getById(id);
        if (announcementTaskListDetail != null) {
            return RestResult.ok(announcementTaskListDetail);
        }
        return RestResult.error(ResultCode.DATA_NONE);
    }

    /**
     * 分页查询公告任务名单详细名录列表
     *
     * @param query 分页查询参数
     * @return 查询结果
     */
    @ApiOperation("分页查询公告任务名单详细名录列表")
    @PostMapping("/page")
    public RestResult<IPage<AnnouncementTaskListDetail>> page(@RequestBody BaseQuery<AnnouncementTaskListDetailQueryDto> query) {
        AssertUtils.isNotNull(query);

        AnnouncementTaskListDetailQueryDto queryDto = query.getEntity(AnnouncementTaskListDetailQueryDto.class);
        if (queryDto == null) {
            queryDto = new AnnouncementTaskListDetailQueryDto();
        }

        return RestResult.ok(announcementTaskListDetailService.queryPageWithAbnormalAndSeriousIllegal(
                new Page<>(query.getCurrent(), query.getSize()), queryDto));
    }

    /**
     * 根据任务名单ID查询详细名录列表
     *
     * @param taskListId 任务名单ID
     * @return 查询结果
     */
    @ApiOperation("根据任务名单ID查询详细名录列表")
    @GetMapping("/list/{taskListId}")
    public RestResult<?> listByTaskListId(@ApiParam("任务名单ID") @PathVariable String taskListId) {
        AssertUtils.isNotBlank(taskListId);

        LambdaQueryWrapper<AnnouncementTaskListDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AnnouncementTaskListDetail::getTaskListId, taskListId)
                .eq(AnnouncementTaskListDetail::getDelFlag, "0")
                .orderByAsc(AnnouncementTaskListDetail::getCreateTime);

        return RestResult.ok(announcementTaskListDetailService.list(wrapper));
    }

    /**
     * 查询所有公告任务名单详细名录列表（不分页）
     *
     * @return 查询结果
     */
    @ApiOperation("查询所有公告任务名单详细名录列表")
    @GetMapping("/list")
    public RestResult<?> list() {
        LambdaQueryWrapper<AnnouncementTaskListDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AnnouncementTaskListDetail::getDelFlag, "0")
                .orderByDesc(AnnouncementTaskListDetail::getCreateTime);

        return RestResult.ok(announcementTaskListDetailService.list(wrapper));
    }

    /**
     * 通过Excel导入公告任务名单详细名录
     *
     * @param file       Excel文件
     * @param taskListId 任务名单ID
     * @param request    HTTP请求
     * @return 导入结果
     */
    @ApiOperation("通过Excel导入公告任务名单详细名录")
    @PostMapping("/import")
    public RestResult<?> importByExcel(@RequestParam("file") MultipartFile file,
                                       @RequestParam("taskListId") String taskListId,
                                       HttpServletRequest request) {
        AssertUtils.isNotNull(file, "上传文件不能为空");
        AssertUtils.isNotBlank(taskListId, "任务名单ID不能为空");

        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)
                || (!fileName.toLowerCase().endsWith(".xls") && !fileName.toLowerCase().endsWith(".xlsx"))) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "文件类型错误，请上传Excel文件");
        }
        AICUser loginUser = getLoginUser(request);
        String createUserId = loginUser.getPrimaryKey();
        announcementTaskListDetailService.importFromExcel(file, taskListId, createUserId);

        return RestResult.ok("导入成功");
    }
}