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.entity.TSAttachment;
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.TSWritService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.revoke.entity.*;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.HearingNoticeDto;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.PunishDecisionDto;
import com.chinaweal.aiccs.aiccs.revoke.service.BizRevEntService;
import com.chinaweal.aiccs.aiccs.revoke.service.CaseService;
import com.chinaweal.aiccs.aiccs.revoke.service.PunishDecisionService;
import com.chinaweal.aiccs.aiccs.revoke.service.TsbizrevlistService;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
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.exception.custom.BusinessException;
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 org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-08-11
 */
@RestController
@RequestMapping("/punishDecision")
public class PunishDecisionController extends BaseController {

    @Autowired
    private PunishDecisionService punishDecisionService;
    @Autowired
    private TsbizrevlistService tsbizrevlistService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSWorkNoService tsWorkNoService;
    @Resource
    private AicorgService aicorgService;
    @Resource
    private BizRevEntService bizRevEntService;
    @Autowired
    private TSWritService tsWritService;
    @Resource
    private TSAttachmentService attachmentService;

    /**
     * 行政处罚决定信息保存
     * @param punishDecision 行政处罚决定信息
     * @return
     */
    @PostMapping("savePunishDecisionInfo")
    public RestResult<?> savePunishDecisionInfo(@RequestBody PunishDecision punishDecision){
        AssertUtils.isNotBlank(punishDecision.getPunishDecisionId());
        return RestResult.ok(punishDecisionService.updateById(punishDecision));
    }


    /**
     * 获取听证告知书信息 以业务中第一家主体为例
     * @param bizseq 业务号
     * @return
     */
    @PostMapping("getPunishDecisionInfo")
    public RestResult<?> getPunishDecisionInfo(String bizseq){
        AssertUtils.isNotBlank(bizseq);
        LambdaQueryWrapper<PunishDecision> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PunishDecision::getBizseq,bizseq);
        PunishDecision punishDecision = punishDecisionService.getOne(wrapper);
        PunishDecisionDto punishDecisionDto = new PunishDecisionDto();

        if(StringUtils.isNotBlank(punishDecision.getAreaCode())) {// 获取地区名称
            String areaName = ConstantsUtil.getAreaName(punishDecision.getAreaCode());
            punishDecision.setAreaName(areaName != null?  areaName: StringUtils.EMPTY);
        }
        BeanUtils.copyProperties(punishDecision, punishDecisionDto);
        //第一家主体基本信息
        List<Tsbizrevlist> list = tsbizrevlistService.list(new LambdaQueryWrapper<Tsbizrevlist>().eq(Tsbizrevlist::getBizseq, bizseq).eq(Tsbizrevlist::getIsRemove, "0").orderByDesc(Tsbizrevlist::getSettime));
        Tsbizrevlist tsbizrevlist = list.get(0);
        TsCase aCase = caseService.getOne(new LambdaQueryWrapper<TsCase>().eq(TsCase::getBizseq, bizseq));
        punishDecisionDto.setBizEntType(aCase.getBizEntType());

        EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, tsbizrevlist.getPripid()));
        punishDecisionDto.setEntname(eBaseinfo.getEntname());
        punishDecisionDto.setName(eBaseinfo.getName());
        punishDecisionDto.setUniscid(eBaseinfo.getUniscid());
        punishDecisionDto.setRegno(eBaseinfo.getRegno());
        punishDecisionDto.setDom(eBaseinfo.getDom());
        punishDecisionDto.setEstdate(eBaseinfo.getEstdate());


        return RestResult.ok(punishDecisionDto);
    }

    /**
     * 行政处罚经办人 批量预生成行政处罚决定书
     * @param bizseq
     * @param request
     * @return
     */
    @PostMapping("createPunishDecBatch")
    public  RestResult<?> createPunishDecBatch(String bizseq, HttpServletRequest request){
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");
        String userOrgCode = aicorgService.getRegionCodeByUser(user);
        // 生成决定书
        LocalDateTime now = LocalDateTime.now();
        LocalDate nowDate = LocalDate.now();
        // 获取起始流水号，只做一次读写
        List<BizRevEnt> bizRevEntList = bizRevEntService.getListByBizseq(bizseq);
        if(CollectionUtils.isEmpty(bizRevEntList)){
            throw new BusinessException("找不到业务主体数据");
        }else if(StringUtils.isNotEmpty(bizRevEntList.get(0).getPrePunDecWritsno())){
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"已批量生成文书，请勿重复操作");
        }
        Tsbizrevlist bizrevlistDB = tsbizrevlistService.getOneBybizseq(bizseq);
        if(bizrevlistDB.getDecWritStartNo() == null){ // 未有决定书流水号值
            Map<String, Object> map = tsWorkNoService.getBatchWrirsno(WorkNoUtil.WORKNOTYPE_33, userOrgCode, bizRevEntList.size());
            int currentNo = (int) map.get("currentNo");
            String genRule = (String) map.get("genRule");
            bizrevlistDB.setDecWritStartNo(currentNo);
            bizrevlistDB.setDecFirstWrit(genRule);
            boolean update = tsbizrevlistService.updateById(bizrevlistDB);
            if(!update) throw new BusinessException("流水号获取错误");
        }
        Integer startNo = bizrevlistDB.getDecWritStartNo();
        ArrayList<TSAttachment> tsAttachments = new ArrayList<>();
        ArrayList<BizRevEnt> bizRevEnts = new ArrayList<>();
        for (BizRevEnt bizRevEnt : bizRevEntList) {

            // 生成文书文件信息
            TSAttachment tsAttachmentModel = new TSAttachment();
            tsAttachmentModel.setAttachmentid(UUID.randomUUID().toString());
            tsAttachmentModel.setCreatetype("1");// 文件为系统生成
            tsAttachmentModel.setBizseq(bizseq);
            tsAttachmentModel.setPripid(bizRevEnt.getPripid());
            tsAttachmentModel.setFileext(".pdf");
            tsAttachmentModel.setFilename(bizRevEnt.getEntname() + "-处罚决定书.pdf");
            tsAttachmentModel.setUploaddate(nowDate);
            tsAttachmentModel.setLauptime(now);
            tsAttachmentModel.setAttachtype("14");// 处罚决定书
            tsAttachments.add(tsAttachmentModel);
            BizRevEnt bizRevEntModel = new BizRevEnt();
            bizRevEntModel.setRevlistid(bizRevEnt.getRevlistid());
            bizRevEntModel.setPrePunDecWritsno(tsWorkNoService.updateWritsNo(bizrevlistDB.getDecFirstWrit(), startNo));
            bizRevEnts.add(bizRevEntModel);
            startNo++;// 生成一份就加一
            bizRevEntService.updateById(bizRevEntModel);
            attachmentService.save(tsAttachmentModel);
        }
        //bizRevEntService.updateBatchById(bizRevEnts);
        //attachmentService.saveBatch(tsAttachments);
        return RestResult.ok();
    }
}

