package com.chinaweal.aiccs.aiccs.writs.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizRemList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSBizRemListService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.revoke.entity.BizRevEnt;
import com.chinaweal.aiccs.aiccs.revoke.entity.TsCase;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tsrevtasklist;
import com.chinaweal.aiccs.aiccs.revoke.service.BizRevEntService;
import com.chinaweal.aiccs.aiccs.revoke.service.CaseService;
import com.chinaweal.aiccs.aiccs.revoke.service.CreateFileService;
import com.chinaweal.aiccs.aiccs.revoke.service.TsrevtasklistService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalRem;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.entity.dto.WritTempEntInfoDto;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
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.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 文书通用模板 前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-09-26
 */
@RestController
@RequestMapping("/tswrittemplate")
public class TswrittemplateController extends BaseController {

    @Autowired
    private TswrittemplateService tswrittemplateService;
    @Autowired
    private TSBizSerIllegalRemService tsBizSerIllegalRemService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private TsrevtasklistService tsrevtasklistService;
    @Autowired
    private TSOpinionService tsOpinionService;
    @Autowired
    private AicorgService aicorgService;
    @Resource
    private BizRevEntService bizRevEntService;
    @Resource
    private CreateFileService createFileService;
    @Resource
    private TSAttachmentService attachmentService;

    /**
     * 根据业务号及文书类型获取文书模板内容
     *
     * @param writTempEntInfoDto 文书模板内容参数对象
     * @return
     */
    @ApiOperation("根据业务号及文书类型获取文书模板内容")
    @PostMapping("getContentsWithBizseq")
    public RestResult<?> getContentsWithBizseq(@RequestBody WritTempEntInfoDto writTempEntInfoDto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        AssertUtils.isNotBlank(writTempEntInfoDto.getBizseq(), writTempEntInfoDto.getWritsType());
        return RestResult.ok(tswrittemplateService.generateWrits(writTempEntInfoDto.getWritsType(), writTempEntInfoDto.getBizseq(),
                writTempEntInfoDto.getType(), user));
    }


    /**
     * 根据文书类型获取文书模板内容
     *
     * @param writsType 文书模板内容参数对象
     * @return
     */
    @ApiOperation("根据文书类型获取文书模板内容")
    @PostMapping("getContentsWithWritstype")
    public Tswrittemplate getTemplateWithWritstype(String writsType) {
        AssertUtils.isNotBlank(writsType);
        LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tswrittemplate::getWritsType, writsType)
                .eq(Tswrittemplate::getIsTemplate, "1");// 是否为模板
        Tswrittemplate template = tswrittemplateService.getOne(wrapper);
        return template;
    }

    /**
     * 业务中保存或更新文书内容
     *
     * @param tswrittemplate
     * @param request
     * @return
     */
    @ApiOperation("业务中保存或更新文书内容")
    @PostMapping("saveOrUpdateContent")
    public RestResult<?> saveOrUpdateContent(@RequestBody Tswrittemplate tswrittemplate, HttpServletRequest request) {
        if (tswrittemplate == null && StringUtils.isEmpty(tswrittemplate.getContent())) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        AICUser user = getLoginUser(request);
        LocalDateTime now = LocalDateTime.now();
        boolean flag = false;
        String writsType = tswrittemplate.getWritsType();
        String bizseq = tswrittemplate.getBizseq();
        Map<String, Object> map = new HashMap<>();
        String path = "static" + File.separator +  "template" + File.separator + "caseReport.docx";
        if (WorkNoUtil.WORKNOTYPE_31.equals(writsType)) { // 案件终结报告才要上传附件到服务器
            String code = aicorgService.getRegionCodeByUser(user);
            String areaName = ConstantsUtil.getAreaName(code);
            List<BizRevEnt> entList = bizRevEntService.getListByBizseq(bizseq);
            map.put("areaName", areaName);
            // 存入名单附录
            map.put("nameList", entList);
        }
        LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tswrittemplate::getBizseq, bizseq)
                .eq(Tswrittemplate::getWritsType, tswrittemplate.getWritsType());
        Tswrittemplate tswrittemplateDB = tswrittemplateService.getOne(wrapper);
        if (tswrittemplateDB != null) { // 已经保存过
            tswrittemplateDB.setContent(tswrittemplate.getContent());
            tswrittemplateDB.setUpdateUserId(user.getPrimaryKey());
            tswrittemplateDB.setUpdateTime(now);
            flag = tswrittemplateService.updateById(tswrittemplateDB);
            if (flag && WorkNoUtil.WORKNOTYPE_31.equals(writsType)) {
                LambdaQueryWrapper<TSAttachment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TSAttachment::getAttachtype, "12")
                        .eq(TSAttachment::getBizseq, bizseq)
                        .eq(TSAttachment::getCreatetype, "1");
                TSAttachment reportInfo = attachmentService.getOne(queryWrapper, false);
                // 更新覆盖案件调查终结报告
                map.put("htmlContent", tswrittemplate.getContent());
                map.put("noAttach", "noAttach"); // 不用再生成文件信息的参数
                map.put("oldPath", reportInfo.getTemppath());
                createFileService.createCasePdfWithModel(bizseq, "案件调查终结报告", "12", path, map);
            }
        } else { // 还未保存过
            tswrittemplate.setCreateUserId(user.getPrimaryKey());
            tswrittemplate.setCreateTime(now);
            tswrittemplate.setIsTemplate("0");
            flag = tswrittemplateService.save(tswrittemplate);
            if (flag && WorkNoUtil.WORKNOTYPE_31.equals(writsType)) {
                // 生成附件上传服务器，添加终结报告文件信息至文件表
                map.put("htmlContent", tswrittemplate.getContent());
                // 生成案件调查终结报告
                createFileService.createCasePdfWithModel(bizseq, "案件调查终结报告", "12", path, map);
            }
        }
        return RestResult.ok(flag);
    }

    @ApiOperation("获取严重违法信用修复决定书")
    @GetMapping("getCreditRepairDecision")
    public RestResult<?> getCreditRepairDecision(@RequestParam String bizSeq) {
        AssertUtils.isNotBlank(bizSeq);
        LambdaQueryWrapper<TSBizSerIllegalRem> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(TSBizSerIllegalRem::getBizSeq, bizSeq);
        TSBizSerIllegalRem bizSerIllegalRem = tsBizSerIllegalRemService.getOne(wrapper1);
        String isAgreeRepair = bizSerIllegalRem.getIsAgreeRepair();
        String writstype = "";
        if ("1".equals(isAgreeRepair)) {// 严重违法准予
            writstype = WorkNoUtil.WORKNOTYPE_53;
        } else if ("0".equals(isAgreeRepair)) {
            writstype = WorkNoUtil.WORKNOTYPE_52;
        }
        LambdaQueryWrapper<TSWrit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSWrit::getBizseq, bizSeq).eq(TSWrit::getWritstype, writstype);
        List<TSWrit> list = tsWritService.list(wrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            TSWrit tsWrit = list.get(0);
            return RestResult.ok(tsWrit.getPath());
        }

        return RestResult.error(ResultCode.DATA_NONE);
    }

    @ApiOperation("获取经营异常信用修复决定书")
    @GetMapping("getAbnRepairDecision")
    public RestResult<?> getAbnRepairDecision(@RequestParam String bizSeq) {
        AssertUtils.isNotBlank(bizSeq);
        List<TSBizRemList> tsBizRemLists = tsBizRemListService.selectbizRembizseq(bizSeq);
        if (CollectionUtils.isNotEmpty(tsBizRemLists)) {
            TSBizRemList bizRemList = tsBizRemLists.get(0);
            String isAgreeRepair = bizRemList.getIsAgreeRepair();
            String type = bizRemList.getType();
            String writstype = "";
            if ("1".equals(isAgreeRepair)) {// 经营异常准予
                if ("company".equals(type) || "farmer".equals(type)) {// 企业农专
                    writstype = WorkNoUtil.WORKNOTYPE_56;
                } else if ("individual".equals(type)) {
                    writstype = WorkNoUtil.WORKNOTYPE_59;
                }
            } else if ("0".equals(isAgreeRepair)) {
                if ("company".equals(type) || "farmer".equals(type)) {// 企业农专
                    writstype = WorkNoUtil.WORKNOTYPE_55;
                } else if ("individual".equals(type)) {
                    writstype = WorkNoUtil.WORKNOTYPE_58;
                }
            }
            LambdaQueryWrapper<TSWrit> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TSWrit::getBizseq, bizSeq).eq(TSWrit::getWritstype, writstype);
            List<TSWrit> list = tsWritService.list(wrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                TSWrit tsWrit = list.get(0);
                return RestResult.ok(tsWrit.getPath());
            }
        }

        return RestResult.error(ResultCode.DATA_NONE);

    }

    /**
     * 批吊业务获取文书模板内容
     *
     * @param writTempEntInfoDto 文书模板内容参数对象
     * @return
     */
    @ApiOperation("批吊业务获取文书模板内容")
    @PostMapping("getRevContentsWithBizseq")
    public RestResult<?> getRevContentsWithBizseq(@RequestBody WritTempEntInfoDto writTempEntInfoDto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        AssertUtils.isNotBlank(writTempEntInfoDto.getBizseq(), writTempEntInfoDto.getWritsType(), writTempEntInfoDto.getNeedTemplate());

        String writsType = writTempEntInfoDto.getWritsType();
        String bizseq = writTempEntInfoDto.getBizseq();
//        String type = writTempEntInfoDto.getType();
        // 先查找业务中有没有编辑保存过的文书内容，有则返回
        LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tswrittemplate::getBizseq, bizseq)
                .eq(Tswrittemplate::getWritsType, writsType)
                .eq(Tswrittemplate::getIsTemplate, "0");// 是否为模板 “0”否“1”是
        Tswrittemplate writtemplateBiz = tswrittemplateService.getOne(wrapper);
        if (writtemplateBiz == null && "1".equals(writTempEntInfoDto.getNeedTemplate())) {// 没有则查找初始模板
            // 不同文书类型对模板内容有 不同处理
            Tswrittemplate templateDB = getTemplateWithWritstype(writsType);
            if (templateDB != null) {
                if (WorkNoUtil.WORKNOTYPE_31.equals(writsType)) {//批量吊销案件终结报告
                    String content = templateDB.getContent();
                    TsCase aCase = caseService.getByBizseq(bizseq);
                    List<Tsrevtasklist> taskLists = tsrevtasklistService.selectByBizSeqID(bizseq);
                    TSOpinion caseApproveOpinion = tsOpinionService.getNewestOpinion(taskLists.get(0).getWorkflowid(), "3");//获取审批意见

                    String assistantName = aCase.getAssistantName();//协办人
                    String handlerName = aCase.getHandlerName();//主办人
                    LocalDateTime setTime = aCase.getSetTime();// 立案时间
                    String caseDate = null;
                    if (setTime != null) {
                        caseDate = DateUtils.localDateFormat(setTime.toLocalDate(), "yyyy年MM月dd日");
                    }
                    String caseReason = BaseDataConstant.REVOKE_CASEREASON_MAP.get(aCase.getBizEntType());// 涉嫌
                    String name = aCase.getCaseName();
                    String caseName = name.replace("关于", StringUtils.EMPTY).replace("的批量吊销", StringUtils.EMPTY);// 当事人
                    String approveName = caseApproveOpinion.getHandler();
                    String blankDate = "<u>&nbsp; &nbsp;</u>年<u>&nbsp; &nbsp;</u>月<u>&nbsp; &nbsp;</u>日";
                    String blankStr = "<u>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</u>";

                    String replaceContent = content.replace("{{assistantName}}", StringUtils.isNotEmpty(assistantName) ? assistantName : StringUtils.EMPTY)
                            .replace("{{handlerName}}", StringUtils.isNotEmpty(handlerName) ? handlerName : StringUtils.EMPTY)
                            .replace("{{approveName}}", StringUtils.isNotEmpty(approveName) ? approveName : blankStr)
                            .replace("{{caseReason}}", StringUtils.isNotEmpty(caseReason) ? caseReason : StringUtils.EMPTY)
                            .replace("{{caseName}}", StringUtils.isNotEmpty(caseName) ? caseName + "（具体名单请看附件）" : StringUtils.EMPTY)
                            .replace("{{caseDate}}", StringUtils.isNotEmpty(caseDate) ? caseDate : blankDate);
                    templateDB.setContent(replaceContent);
//                    caseService.getOne()
                } else if (WorkNoUtil.WORKNOTYPE_32.equals(writsType)) {//	批量吊销听证告知书
                    String content = templateDB.getContent();
                    TsCase aCase = caseService.getByBizseq(bizseq);
                    String illegalActCn = aCase.getIllegalActCn();

                    String caseReason = BaseDataConstant.REVOKE_CASEREASON_MAP.get(aCase.getBizEntType());// 涉嫌
                    String name = aCase.getCaseName();
                    String caseName = name.replace("关于", StringUtils.EMPTY).replace("的批量吊销", StringUtils.EMPTY);
                    String replaceContent = content.replace("{{illegalActCn}}", StringUtils.isNotEmpty(illegalActCn) ? illegalActCn : StringUtils.EMPTY)
                            .replace("{{caseName}}", StringUtils.isNotEmpty(caseName) ? caseName : StringUtils.EMPTY);
                    templateDB.setContent(replaceContent);

                } else if (WorkNoUtil.WORKNOTYPE_33.equals(writsType)) {//	批量吊销行政处罚决定书

                }
                return RestResult.ok(templateDB);
            }
        }
        return RestResult.ok(writtemplateBiz);
    }

    @ApiOperation("获取行政处罚文书模板内容")
    @PostMapping("getRemPunishmentContentsWithBizseq")
    public RestResult<?> getRemPunishmentContentsWithBizseq(@RequestBody WritTempEntInfoDto writTempEntInfoDto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        AssertUtils.isNotBlank(writTempEntInfoDto.getBizseq(), writTempEntInfoDto.getWritsType());
        return RestResult.ok(tswrittemplateService.generateRemPunishmentWrits(writTempEntInfoDto, user));
    }

    @ApiOperation("获取行政处罚信用修复决定书")
    @GetMapping("getRemPunishWrit")
    public RestResult<?> getRemPunishWrit(@RequestParam String bizSeq) {
        AssertUtils.isNotBlank(bizSeq);
        LambdaQueryWrapper<TSWrit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSWrit::getBizseq, bizSeq).in(TSWrit::getWritstype, "65","66");
        List<TSWrit> list = tsWritService.list(wrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            TSWrit tsWrit = list.get(0);
            return RestResult.ok(tsWrit.getPath());
        }
        return RestResult.error(ResultCode.DATA_NONE);
    }

}

