package com.chinaweal.aiccs.aiccs.abnormal.controller;

import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizRemList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AicepsAbnRepairParamDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AicepsApiCheckParamDto;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAbnListService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSBizRemListService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.temp.entity.Temprepairinfo;
import com.chinaweal.aiccs.aiccs.temp.service.TemprepairinfoService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.HolidaysUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.exception.custom.ParameterException;
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.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 年报异常名录信用修复
 *
 * @author lroyia
 * @since 2025/2/28 10:24
 **/
@Slf4j
@Api(tags = "年报异常名录信用修复调度接口")
@RestController
@RequestMapping("abnormal/repair/api")
public class AicepsAbnRepairApiController {

    @Autowired
    private OrgUM orgUM;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private IGzaiccodeService iGzaiccodeService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TemprepairinfoService temprepairinfoService;
    @Autowired
    private EBaseinfoService eBaseinfoService;

    /**
     * 修复申请
     *
     * @param param 申请参数
     * @return 申请业务号
     * @author lroyia
     * @since 2025年2月28日10:42:55
     */
    @Transactional
    @ApiOperation("1、信用修复申请")
    @GetMapping("repair")
    public RestResult<?> repairApply(@RequestBody @ApiParam("申请参数") AicepsAbnRepairParamDto param) {
        String applicant = param.getApplicant();
        String applicantId = param.getApplicantId();
        String applicantNo = param.getApplicantNo();
        String abnlistid = param.getAbnlistid();
        AssertUtils.isNotBlank(abnlistid, applicantId, applicantNo, applicant);

        // 校验接口权限
        checkTokenTime(param);
        String sign = DigestUtils.md5DigestAsHex((param.getAbnlistid() + "ChinaWeal@" + param.getTimestampStr().substring(0, 8)
                + param.getTimestampStr()).getBytes(StandardCharsets.UTF_8));
        if (StringUtils.notEquals(sign, param.getSignature())) {
            throw new ParameterException(ResultCode.TOKEN_SIGNATURE);
        }

        TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);
        EBaseinfo eBaseInfo = eBaseinfoService.getById(tsAbnListModel.getPripid());

        String entertype;
        if (StringUtils.equalsAny(eBaseInfo.getEnttype(), "9100", "9200")) {
            entertype = "farmer";
        } else if (StringUtils.equalsAny(eBaseInfo.getEnttype(), "9910", "9500")) {
            entertype = "individual";
        } else {
            entertype = "company";
        }

        String bizseqUp = StringUtils.getUUID();
        Temprepairinfo temprepairinfo = new Temprepairinfo();
        temprepairinfo.setApplyTime(LocalDateTime.now());
        temprepairinfo.setAbnid(abnlistid);
        temprepairinfo.setApplicant(applicant);
        temprepairinfo.setApplicantNo(applicantNo);
        temprepairinfo.setBizseq(bizseqUp);
        temprepairinfo.setType(entertype);
        temprepairinfoService.saveApplyInfo(temprepairinfo);

        try {
            List<TSBizRemList> bizRemListModelList = new ArrayList<>();
            //添加到 移出异常名录业务表
            //查询个体业务主体信息
            TSBizRemList tsBizRemListModel = new TSBizRemList();
            tsBizRemListModel.setBizseq(bizseqUp);
            tsBizRemListModel.setAbnlistid(tsAbnListModel.getAbnlistid());
            tsBizRemListModel.setPripid(tsAbnListModel.getPripid());
            tsBizRemListModel.setRegno(tsAbnListModel.getRegno());
            tsBizRemListModel.setEntname(tsAbnListModel.getEntname());
            tsBizRemListModel.setSpecause(tsAbnListModel.getSpecause());
            tsBizRemListModel.setAbntime(tsAbnListModel.getAbntime());
            tsBizRemListModel.setSpereasons(tsAbnListModel.getSpereasons());
            tsBizRemListModel.setApplicant(applicant);
            tsBizRemListModel.setApplicantNo(applicantNo);
            tsBizRemListModel.setApplicantId(applicantId);
            tsBizRemListModel.setCerno(eBaseInfo.getCerno());
            tsBizRemListModel.setType(entertype);
            tsBizRemListModel.setLauptime(LocalDateTime.now());
            tsBizRemListModel.setAppOrPc("0");//移动端
            tsBizRemListModel.setApplyTime(LocalDateTime.now());
            tsBizRemListModel.setHandleStatus("1");
            bizRemListModelList.add(tsBizRemListModel);

            //根据主体机关和权限标识，分配对应部门，拿到对应的用户列表
            String permission = "individual".equals(entertype) ? "individualRecoverAccept" : "exptRemoveEnter";
            List<String> userIdList = iGzaiccodeService.byPermissionListHandleUserList(tsAbnListModel.getPripid(), permission, tsAbnListModel.getDecorg(), tsAbnListModel.getIntoDecorg())
                    .stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
            if (userIdList.isEmpty()) {
                log.error("分派失败，受理人列表为空,tsabnlist为：{},权限为：{}", tsAbnListModel, permission);
                throw new BusinessException("受理人列表为空！");
            } else {
                TSTaskList taskListModel = new TSTaskList();
                //添加待办
                taskListModel.setBizseqid(bizseqUp);
                if ("individual".equals(entertype)) {
                    taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_RESTORE);
                } else if ("farmer".equals(entertype)) {
                    taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_REMOVE);
                } else {
                    taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_REMOVE);
                }
                taskListModel.setDeadlineDate(HolidaysUtil.getNextWorkingDay(tsBizRemListService.getInsertDeadlineDate(tsAbnListModel.getSpecause(), taskListModel.getBustype(), true)));
                taskListModel.setBusname(bizRemListModelList.get(0).getEntname());
                //移动端过来的数据要更新为申请人的信息
                taskListModel.setSenderuserid("");
                taskListModel.setSenderorgid("");
                taskListModel.setSendername(applicant);

                // 判断是否可以进行智能办结
                RestResult<?> restResult = tsBizRemListService.canProcessSmart(eBaseInfo, taskListModel, bizRemListModelList);
                // 判断是否需要智能办结
                if (restResult.getCode() != 0) {
                    // 旧流程
                    AICUser aicUser = orgUM.findUserByPrimaryKey(userIdList.get(0));
                    if (userIdList.size() == 1) {
                        taskListModel = tsBizRemListService.saveAbnListStart(aicUser, taskListModel, bizRemListModelList);
                    } else {
                        taskListModel = tsBizRemListService.saveAbnListStartApp(aicUser, userIdList, taskListModel, bizRemListModelList);
                    }
                    //移动端过来的数据要更新为申请人的信息
                    taskListModel.setSenderuserid("");
                    taskListModel.setSenderorgid("");
                    taskListModel.setSendername(applicant);
                    taskListService.updateById(taskListModel);
                } else {
                    // 智能办结
                    tsBizRemListService.processSmart(eBaseInfo, taskListModel, bizRemListModelList, tsAbnListModel.getDecorg(), applicant);
                }
            }

        } catch (Exception e) {
            log.error("移动端经营异常启动流程出错", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if (e.getMessage().equals("受理人列表为空！"))
                throw new BusinessException("受理人列表为空！");
        }

        return RestResult.ok();
    }

    /**
     * 检查Token时间
     *
     * @param param 请求参数
     * @author lroyia
     * @since 2025年2月28日10:54:46
     */
    private void checkTokenTime(AicepsApiCheckParamDto param) {
        AssertUtils.isNotBlank(param.getTimestampStr());
        LocalDateTime parse = LocalDateTime.parse(param.getTimestampStr(), DateTimeFormatter.ofPattern(DateUtils.DATETIME_NOT_UNDERLINE_FORMAT));
        if (LocalDateTime.now().minusMinutes(5).isAfter(parse)) {
            throw new ParameterException(ResultCode.TOKEN_EXPIRED);
        }
    }
}
