package com.chinaweal.aiccs.aiccs.revoke.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.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.service.BizRevEntService;
import com.chinaweal.aiccs.aiccs.revoke.service.CaseReportService;
import com.chinaweal.aiccs.aiccs.revoke.service.HearingNoticeService;
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-09
 */
@RestController
@RequestMapping("/hearingnotice")
public class HearingNoticeController extends BaseController {

    @Autowired
    private HearingNoticeService hearingNoticeService;
    @Autowired
    private TsbizrevlistService tsbizrevlistService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private CaseReportService caseReportService;
    @Resource
    private AicorgService aicorgService;
    @Resource
    private BizRevEntService bizRevEntService;
    @Autowired
    private TSWorkNoService tsWorkNoService;
    @Resource
    private TSAttachmentService attachmentService;

    /**
     * 听证告知书信息保存
     * @param hearingnotice 听证告知书信息
     * @return
     */
    @PostMapping("saveHearingNoticeInfo")
    public RestResult<?> saveHearingNoticeInfo(@RequestBody Hearingnotice hearingnotice){
        AssertUtils.isNotBlank(hearingnotice.getHearingNoticeId());
        return RestResult.ok(hearingNoticeService.updateById(hearingnotice));
    }


    /**
     * 获取听证告知书信息 以业务中第一家主体为例
     * @param bizseq 业务号
     * @return
     */
    @PostMapping("getHearingNoticeInfo")
    public RestResult<?> getHearingNoticeInfo(String bizseq){
        AssertUtils.isNotBlank(bizseq);
        LambdaQueryWrapper<Hearingnotice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Hearingnotice::getBizseq,bizseq);
        Hearingnotice hearingnotice = hearingNoticeService.getOne(wrapper);
        HearingNoticeDto hearingNoticeDto = new HearingNoticeDto();
        if(StringUtils.isNotBlank(hearingnotice.getAreaCode())) {// 获取地区名称
            String areaName = ConstantsUtil.getAreaName(hearingnotice.getAreaCode());
            hearingnotice.setAreaName(areaName != null?  areaName: StringUtils.EMPTY);
        }
        BeanUtils.copyProperties(hearingnotice, hearingNoticeDto);
        //第一家主体基本信息
        List<Tsbizrevlist> list = tsbizrevlistService.list(new LambdaQueryWrapper<Tsbizrevlist>().eq(Tsbizrevlist::getBizseq, bizseq).eq(Tsbizrevlist::getIsRemove, "0").orderByDesc(Tsbizrevlist::getSettime));
        Tsbizrevlist tsbizrevlist = list.get(0);
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, tsbizrevlist.getPripid()));
        hearingNoticeDto.setEntname(eBaseinfo.getEntname());
        hearingNoticeDto.setName(eBaseinfo.getName());
        hearingNoticeDto.setPhone(eBaseinfo.getPhone());
        hearingNoticeDto.setDom(eBaseinfo.getDom());
        //涉嫌行为
        CaseReport caseReport = caseReportService.getOne(new LambdaQueryWrapper<CaseReport>().eq(CaseReport::getBizseq, bizseq));
        hearingNoticeDto.setSuspectedAtc(caseReport.getSuspectedAtc());

        return RestResult.ok(hearingNoticeDto);
    }

    /**
     * 听证环节经办人 批量预生成听证告知书
     * @param bizseq
     * @param request
     * @return
     */
    @PostMapping("createHearingBatch")
    public  RestResult<?> createHearingBatch(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).getPreHearNotWritsno())){
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"已批量生成文书，请勿重复操作");
        }
        Tsbizrevlist bizrevlistDB = tsbizrevlistService.getOneBybizseq(bizseq);
        if (bizrevlistDB.getHearWritStartNo() == null) { // 未有听证告知书流水号值
            Map<String, Object> map = tsWorkNoService.getBatchWrirsno(WorkNoUtil.WORKNOTYPE_32, userOrgCode, bizRevEntList.size());
            int currentNo = (int) map.get("currentNo");
            String genRule = (String) map.get("genRule");
            bizrevlistDB.setHearWritStartNo(currentNo);
            bizrevlistDB.setHearFirstWrit(genRule);
            boolean update = tsbizrevlistService.updateById(bizrevlistDB);
            if (!update) throw new BusinessException("流水号获取错误");
        }
        Integer startNo = bizrevlistDB.getHearWritStartNo();
        //ArrayList<TSAttachment> tsAttachments = new ArrayList<>();
        //ArrayList<BizRevEnt> bizRevEnts = new ArrayList<>();
        //int total = bizRevEntList.size();
        //int i = 0;

        for (BizRevEnt bizRevEnt : bizRevEntList) {
            //++i;
            // 生成文书文件信息
            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("13");// 听证告知书
            //tsAttachments.add(tsAttachmentModel);
            BizRevEnt bizRevEntModel = new BizRevEnt();
            bizRevEntModel.setRevlistid(bizRevEnt.getRevlistid());
            bizRevEntModel.setPreHearNotWritsno(tsWorkNoService.updateWritsNo(bizrevlistDB.getHearFirstWrit(), startNo));
            //bizRevEnts.add(bizRevEntModel);
            startNo++;// 生成一份就加一
            bizRevEntService.updateById(bizRevEntModel);
            attachmentService.save(tsAttachmentModel);
//            if(i % 500 == 0 || i == total){ // 每隔500保存一次
//                bizRevEntService.updateBatchById(bizRevEnts);
//                attachmentService.saveBatch(tsAttachments);
//                bizRevEnts.clear();// 重置
//                tsAttachments.clear();// 重置
//            }
        }
        return RestResult.ok();
    }
}

