package com.chinaweal.aiccs.aiccs.gzgs;

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.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.EntWritsDto;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tsbizrevlist;
import com.chinaweal.aiccs.aiccs.revoke.service.TsbizrevlistService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSForIllOperatingList;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSForIllOperatingListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiceps.annual.entity.dto.QueryAbnormalDto;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
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 io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.LocalDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 严重违法，吊销，经营异常控制器
 *
 * @author lwd
 * @since 2021/2/7 8:59l
 **/
@RestController
@RequestMapping("/abnormalAndBatch")
public class AbnormalBatchController {


    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSForIllOperatingListService forIllOperatingListService;
    @Autowired
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private TsbizrevlistService tsbizrevlistService;
    @Autowired
    private TSBizSpeListService tsBizSpeListService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private IGzaiccodeService gzaiccodeService;

    /**
     * 拟列入严重违法失信企业清单分页
     * @param pageRequestDto 分页参数
     * @return 分页结果
     * @author lwd
     * @since 2021年7月5日 15:52:40
     */
    @ApiOperation("拟列入严重违法失信企业清单分页")
    @PostMapping("selectForIllListPage")
    public RestResult<?> selectForIllListPage(@RequestBody @ApiParam("分页参数") PageRequestDto pageRequestDto){
        AssertUtils.isNotNull(pageRequestDto);
        pageRequestDto.checkDefault(1, 10, "lauptime");
        Map<String, TRBaseCode> causeMap = baseCodeService.getBaseCodeMapFormCache("CD71");
        return RestResult.ok(forIllOperatingListService.defaultPaging(pageRequestDto, w -> {
            LambdaQueryWrapper<TSForIllOperatingList> wrapper = w.lambda();
            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
            if(customParamMap == null) return;
            String searchName = StringUtils.tranObject(customParamMap.get("searchName"));
            String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
            if(StringUtils.isNotBlank(searchName)){
                wrapper.like(TSForIllOperatingList::getEntName, searchName);
            }
            if(StringUtils.isNotBlank(searchUscc)){
                wrapper.like(TSForIllOperatingList::getRegNo, searchUscc);
            }
        }, each -> {
            TRBaseCode causeCode = causeMap.get(each.getSpeCause());
            if(causeCode != null){
                each.setSpeCauseStr(causeCode.getName());
            }
            // TODO:企业类型渲染
        }));
    }


    /**
     * 列入严重违法失信企业清单分页
     * @return 分页结果
     * @author lwd
     * @since 2021年7月5日 19:32:20
     */
    @ApiOperation("列入严重违法失信企业清单分页")
    @PostMapping("queryAbnormalLrPage")
    public RestResult<?> queryAbnormalLrPage(int rows, int page) {
        IPage<TSSerIllegalList> tsSerIllegalListIPage = tsSerIllegalListService.queryAbnormalLrList(new Page<>(page, rows));
        List<TSSerIllegalList> tsSerIllegalListList = tsSerIllegalListIPage.getRecords();

        return RestResult.ok(tsSerIllegalListIPage);
    }

    /**
     * 列入严重违法失信企业清单分页
     * @return 分页结果
     * @author lwd
     * @since 2021年7月6日 9:52:26
     */
    @ApiOperation("严重违法失信企业移除清单分页")
    @PostMapping("queryAbnormalYcPage")
    public RestResult<?> queryAbnormalYcPage(int rows, int page) {
        IPage<TSSerIllegalList> tsSerIllegalListIPage = tsSerIllegalListService.queryAbnormalYcList(new Page<>(page, rows));
        List<TSSerIllegalList> tsSerIllegalListList = tsSerIllegalListIPage.getRecords();

        return RestResult.ok(tsSerIllegalListIPage);
    }

    /**
     * 批量吊销行政处罚听证告知书清单分页
     * @return 分页结果
     * @author lwd
     * @since 2021年7月6日 10:52:21   tsbizrevlistService
     */
    @ApiOperation("批量吊销行政处罚听证告知书清单分页")
    @PostMapping("queryRevocationTzsPage")
    public RestResult<?> queryRevocationTzsPage(int rows, int page) {
        IPage<Tsbizrevlist> tsSerIllegalListIPage = tsbizrevlistService.queryRevocationTzsList(new Page<>(page, rows));
        List<Tsbizrevlist> tsSerIllegalListList = tsSerIllegalListIPage.getRecords();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (int i = 0; i < tsSerIllegalListList.size(); i++) {
            String createTime = dateTimeFormatter.format(tsSerIllegalListList.get(i).getWritsTime());
            String[] timeArr = createTime.split("-");
            String tswritTime = timeArr[0]+"年"+timeArr[1]+"月"+timeArr[2]+"日";
            tsSerIllegalListList.get(i).setWritsTimeStr(tswritTime);
        }
        return RestResult.ok(tsSerIllegalListIPage);
    }


    /**
     * 批量吊销行政处罚决定书清单分页  queryRevocationJds
     * @return 分页结果
     * @author lwd
     * @since 2021年7月6日 11:12:29
     */
    @ApiOperation("批量吊销行政处罚决定书清单分页")
    @PostMapping("queryRevocationJdsPage")
    public RestResult<?> queryRevocationJdsPage(int rows, int page) {
        IPage<Tsbizrevlist> tsSerIllegalListIPage = tsbizrevlistService.queryRevocationJdsList(new Page<>(page, rows));
        List<Tsbizrevlist> tsSerIllegalListList = tsSerIllegalListIPage.getRecords();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (int i = 0; i < tsSerIllegalListList.size(); i++) {
            String createTime = dateTimeFormatter.format(tsSerIllegalListList.get(i).getWritsTime());
            String[] timeArr = createTime.split("-");
            String tswritTime = timeArr[0]+"年"+timeArr[1]+"月"+timeArr[2]+"日";
            tsSerIllegalListList.get(i).setWritsTimeStr(tswritTime);
        }

        return RestResult.ok(tsSerIllegalListIPage);
    }

    /**
     * 查看未按规定参加年报被列入批次
     *
     * @param rows              分页大小
     * @param page              当前分页
     * @return 分页结果
     * @author lroyia
     * @since 2021年7月06日 15:41:54
     */
    @PostMapping("/getWnbPage")
    public RestResult<?> getWnbPage(int rows, int page) {
        IPage<EntWritsDto> iPage = tsWritService.getWnbBatchPage(new Page<>(page, rows));
        List<EntWritsDto> records = iPage.getRecords();
        if(CollectionUtils.isNotEmpty(records)){
            for (EntWritsDto record : records) {
                String format = DateUtils.localDateFormat(record.getCreatetime().toLocalDate(), "yyyy年MM月dd日");
                record.setCreatetimeStr(format);
            }
        }
        return RestResult.ok(iPage);
    }


    /**
     * 查看因地址原因及其他原因列入企业
     *
     * @param rows              分页大小
     * @param page              当前分页
     * @return 分页结果
     * @author lwd
     * @since 2021年7月06日 15:41:54
     */
    @PostMapping("/selectTSAbnListByPageList")
    public RestResult<?> selectBizSpeByPageLis(int rows, int page, String entName , String abnTime ) {
        Map<String,Object> pram = new HashMap<>();
        if (StringUtils.isNotBlank(entName)){
            pram.put("entName",entName);
        }
        if (StringUtils.isNotBlank(abnTime)){
            pram.put("abnTime",abnTime);
        }
        IPage<TSAbnList> tsBizSpeListIPage = tsAbnListService.selectTSAbnListByPageList(new Page<>(page, rows,false),pram);


        return RestResult.ok(tsBizSpeListIPage);
    }


    /**
     * 列入严重违法失信企业清单详情
     * @return 详情结果
     * @author lwd
     * @since 2021年7月8日 17:22:31
     */
    @ApiOperation("列入严重违法失信企业清单详情")
    @GetMapping("abnormalLrDetails")
    @ResponseBody
    public RestResult<?> abnormalLrDetails(@RequestParam String writsid) {
        AssertUtils.isNotEmpty(writsid);
        TSWrit writ = tsWritService.getById(writsid);
        EntWritsDto entWritsDto = new EntWritsDto();
        if(writ == null) throw new BusinessException("获取文书详情失败");
        BeanUtils.copyProperties(writ,entWritsDto);

        String pripid = writ.getPripid();
        if (pripid == null || "".equals(pripid))throw new BusinessException("请确认该当事人是否存在");

        EBaseinfo eBaseinfo =  eBaseinfoService.getOneByPripid(pripid);
        BeanUtils.copyProperties(eBaseinfo,entWritsDto);
        String areaName = "";
        areaName = gzaiccodeService.getNameByCode(writ.getAreaCode());
        entWritsDto.setDecOrgName(areaName);
        LocalDateTime createtime = entWritsDto.getCreatetime();
        String format = DateUtils.localDateFormat(createtime.toLocalDate(), "yyyy年MM月dd日");
        entWritsDto.setCreatetimeStr(format);

        return RestResult.ok(entWritsDto);
    }

    public synchronized String getAreaName(String writsNo) {
        String areaName = "";
        int i = writsNo.indexOf("蒙");
        String areaCode = "";
        areaName = writsNo.substring(i+1, i+2);
        for (Map.Entry<String,String> entry: Constant.NM_REGION_CODE_SHORTNAME.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (value.equals(areaName)) {
                areaCode = key;
                break;
            }
        }
        areaName = Constant.NM_REGION_CODE.get(areaCode);
        if (StringUtils.isBlank(areaName)) {
            areaName = "内蒙古自治区市场监督管理局";
        } else {
            areaName = areaName + "市场监督管理局";
        }
        return areaName;
    }


    /**
     * 移除严重违法失信企业清单详情
     * @return 详情结果
     * @author lwd
     * @since 2021年7月10日 15:52:37
     */
    @ApiOperation("移除严重违法失信企业清单详情")
    @GetMapping("abnormalYcDetails")
    @ResponseBody
    public RestResult<?> abnormalYcDetails(@RequestParam String writsid) {

        AssertUtils.isNotEmpty(writsid);
        TSWrit writ = tsWritService.getById(writsid);
        EntWritsDto entWritsDto = new EntWritsDto();
        if(writ == null) throw new BusinessException("获取文书详情失败");
        BeanUtils.copyProperties(writ,entWritsDto);
        // 旧数据前端作处理
//        String content = tswrittemplateService.illegalRepairDecContentFormatter(entWritsDto.getContent());
//        entWritsDto.setContent(content);
        String pripid = writ.getPripid();
        if (StringUtils.isEmpty(pripid))throw new BusinessException("请确认该当事人是否存在");

        EBaseinfo eBaseinfo =  eBaseinfoService.getOneByPripid(pripid);
        BeanUtils.copyProperties(eBaseinfo,entWritsDto);

        String areaName = "";
        areaName = gzaiccodeService.getNameByCode(writ.getAreaCode());
        entWritsDto.setDecOrgName(areaName);
        LocalDateTime createtime = entWritsDto.getCreatetime();
        String format = DateUtils.localDateFormat(createtime.toLocalDate(), "yyyy年MM月dd日");
        entWritsDto.setCreatetimeStr(format);

        return RestResult.ok(entWritsDto);
    }


    /**
     * 未按年报列入详情
     * @return 详情结果
     * @author lwd
     * @since 2021年7月114日 19:52:21
     */
    @ApiOperation("未按年报列入详情")
    @PostMapping("abnormalAicepsDetails")
    @ResponseBody
    public RestResult<?> abnormalAicepsDetails(String writsid) {
        AssertUtils.isNotEmpty(writsid);
        TSWrit writ = tsWritService.getById(writsid);
        return RestResult.ok(writ);
    }


    /**
     * 批量吊销行政处罚听证告知书清单详情
     * @return 详情结果
     * @author lwd
     * @since 2021年7月26日 16:02:21
     */
    @ApiOperation("批量吊销行政处罚听证告知书清单详情")
    @PostMapping("queryRevocationTzsDetails")
    public RestResult<?> queryRevocationTzsDetails(String bizseq, String uniscid, String regno, String writsTimeStr, String areaCode,
                                                   String entname, String name, String writsno, String writstype,String pripid) {

        Map<String,Object> restResultMap = new HashMap<>();
        //查找对应区域
        String decOrgName = gzaiccodeService.getNameByCode(areaCode);

        AssertUtils.isNotBlank(writstype);
        LambdaQueryWrapper<TSWrit> wrapper = new LambdaQueryWrapper<>();
        String writscontent = "";
        wrapper.eq(TSWrit::getBizseq,bizseq)
                .eq(TSWrit::getPripid, pripid)
                .eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_32)
                .orderByDesc(TSWrit::getCreatetime);
        List<TSWrit> list = tsWritService.list(wrapper);
        if(CollectionUtils.isNotEmpty(list)){
            TSWrit tsWrit = list.get(0);
            writscontent = tsWrit.getContent();
        }
        restResultMap.put("uniscid",uniscid);
        restResultMap.put("regno",regno);
        restResultMap.put("writsTimeStr",writsTimeStr);
        restResultMap.put("areaName",decOrgName);
        restResultMap.put("entname",entname);
        restResultMap.put("name",name);
        restResultMap.put("writsno",writsno);
        restResultMap.put("writscontent",writscontent);

        return RestResult.ok(restResultMap);
    }

    /**
     * 批量吊销行政处罚决定书清单详情
     * @return 分页结果
     * @author lwd
     * @since 2021年7月26日 16:32:45
     */
    @ApiOperation("批量吊销行政处罚决定书清单详情")
    @PostMapping("queryRevocationJdsDetails")
    public RestResult<?> queryRevocationJdsDetails(String bizseq,String pripid) {

        Map<String,Object> restResultMap = new HashMap<>();

        LambdaQueryWrapper<TSWrit> wrapper = new LambdaQueryWrapper<>();
        String writscontent = "";
        String areaCode = "";
        wrapper.eq(TSWrit::getBizseq,bizseq)
                .eq(TSWrit::getPripid, pripid)
                .eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_33)
                .orderByDesc(TSWrit::getCreatetime);
        List<TSWrit> list = tsWritService.list(wrapper);
        if(CollectionUtils.isNotEmpty(list)){
            TSWrit tsWrit = list.get(0);
            writscontent = tsWrit.getContent();
            areaCode = tsWrit.getAreaCode();
        }
        //查找对应区域
        String decOrgName = gzaiccodeService.getNameByCode(areaCode);

        restResultMap.put("areaName",decOrgName);
        restResultMap.put("writscontent",writscontent);

        return RestResult.ok(restResultMap);
    }


    /**
     * 严重违法失信企业按条件查询清单分页
     * @return 分页结果
     * @author lwd
     * @since 2021年9月11日 11:44:22
     */
    @ApiOperation("严重违法失信企业按条件查询清单分页")
    @PostMapping(value ="queryAbnormalByNamePage")
    public RestResult<?> queryAbnormalByNamePage(@RequestBody QueryAbnormalDto queryAbnormalDto) {
        String type = queryAbnormalDto.getType();
        int rows = queryAbnormalDto.getRows();
        int page = queryAbnormalDto.getPage();
        Map<String,Object> pram = new HashMap<>();
        pram.put("entName", queryAbnormalDto.getEntName());
        IPage<EntWritsDto> writsDtoPage = null;
        List<EntWritsDto> writsDtoList = null;
        if ("1".equals(type)){//1查询拟列入严重违法；2查询列入严重违法；3查询移除严重违法
            writsDtoPage = tsSerIllegalListService.queryToIllegalByNameList(new Page<>(page, rows),pram);
        }
        else if ("2".equals(type)){
            writsDtoPage = tsSerIllegalListService.queryAbnormalLrByNameList(new Page<>(page, rows),pram);
        }
        else if ("3".equals(type)){
            writsDtoPage = tsSerIllegalListService.queryAbnormalYcByNameList(new Page<>(page, rows),pram);
        }
        if(writsDtoPage != null && CollectionUtils.isNotEmpty(writsDtoPage.getRecords())){
            writsDtoList = writsDtoPage.getRecords();
            for (EntWritsDto entWritsDto : writsDtoList) {
                LocalDateTime createtime = entWritsDto.getCreatetime();
                String format = DateUtils.localDateFormat(createtime.toLocalDate(), "yyyy年MM月dd日");
                entWritsDto.setCreatetimeStr(format);
            }
        }
        return RestResult.ok(writsDtoPage);
    }

    /**
     * 行政处罚证书按条件查询清单分页
     * @return 分页结果
     * @author lwd
     * @since 2021年9月11日 15:13:42
     */
    @ApiOperation("行政处罚证书按条件查询清单分页")
    @PostMapping("queryRevocationByNamePage")
    public RestResult<?> queryRevocationByNamePage(int rows, int page, String entName, String type) {
        Map<String,Object> pram = new HashMap<>();
        if (StringUtils.isNotBlank(entName)){
            pram.put("entName","%"+entName+"%");
        }

        IPage<Tsbizrevlist> tsbizrevlist = null;

        List<Tsbizrevlist> bizrevlists = null;
        if ("1".equals(type)){//1查询行政处罚听证告知书；2查询行政处罚决定告知书
            tsbizrevlist = tsbizrevlistService.queryRevocationTzsByNameList(new Page<>(page, rows),pram);
            bizrevlists = tsbizrevlist.getRecords();

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            for (int i = 0; i < bizrevlists.size(); i++) {
                String createTime = dateTimeFormatter.format(bizrevlists.get(i).getWritsTime());
                String[] timeArr = createTime.split("-");
                String tswritTime = timeArr[0]+"年"+timeArr[1]+"月"+timeArr[2]+"日";
                bizrevlists.get(i).setWritsTimeStr(tswritTime);
            }
        }else if ("2".equals(type)){
            tsbizrevlist = tsbizrevlistService.queryRevocationJdsByNameList(new Page<>(page, rows),pram);
            bizrevlists = tsbizrevlist.getRecords();

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            for (int i = 0; i < bizrevlists.size(); i++) {
                String createTime = dateTimeFormatter.format(bizrevlists.get(i).getWritsTime());
                String[] timeArr = createTime.split("-");
                String tswritTime = timeArr[0]+"年"+timeArr[1]+"月"+timeArr[2]+"日";
                bizrevlists.get(i).setWritsTimeStr(tswritTime);
            }
        }

        return RestResult.ok(tsbizrevlist);
    }

    /**
     * 新增未年报批量列入文书记录
     * @return
     */
    @ApiOperation("新增未年报批量列入文书记录")
    @GetMapping("insertWnbRecods")
    public RestResult<?> insertWnbRecods(String firstEntName,String num,String approvalDate){
        TSWrit tsWritModel = new TSWrit();
        tsWritModel.setBizseq(UUID.randomUUID().toString());
        tsWritModel.setWritsname("内蒙古自治区市场监督管理局列入经营异常名录决定书");
        tsWritModel.setWritstype(WorkNoUtil.WORKNOTYPE_17);
        // 未年报年度
        int year = LocalDate.now().minusYears(1).getYear();
        String lastYear = String.valueOf(year);

        String fileName = "因未在规定期限内报送year年度报告被列入经营异常名录企业名单(num户).xlsx";
        fileName.replace("year",lastYear).replace("num",num);
        StringBuilder text = new StringBuilder("");
        text.append("<span>" + firstEntName + "等"+num+"户企业：</span>");
        text.append("<p>经查，你单位未按照《企业信息公示暂行条例》第八条规定的期限公示年度报告，符合《" +
                "企业经营异常名录管理暂行办法》第四条第一款第(一)项所指的情形，根据《企业经营异常名录管理暂行办法》" +
                "第六条的规定，我局决定将你单位列入经营异常名录，并向社会公示。</p>");
        text.append("<p>如对被列入经营异常名录有异议的，可自公示之日起30日内向作出决定的市场监督管理部门提出书面申请并提交" +
                "相关证明材料，市场监督管理部门依法作出处理。</p>");
        text.append("<p>附件：" + fileName +"</p>");
        text.append("<p style=\"text-align: right;\" >内蒙古自治区市场监督管理局</p>");
        text.append("<p style=\"text-align: right;\" >"+approvalDate +"</p>");
        tsWritModel.setContent(text.toString());
        tsWritModel.setCreatetime(LocalDateTime.now());
        boolean save = tsWritService.save(tsWritModel);
        return RestResult.ok(save);
    }


    /**
     * 提供年报系统调用-查询主体是否存在因未按时年报被列异经营异常名录且未移出名录的记录
     *
     * @return
     */
    @ApiOperation("查询主体是否存在因未按时年报被列异经营异常名录且未移出名录的记录")
    @GetMapping("queryAbnInfoForEps")
    public RestResult<Boolean> queryAbnInfoForEps(@RequestParam String pripid) {
        if (StringUtils.isBlank(pripid)) {
            throw new BusinessException(ResultCode.PARAM_IS_BLANK);
        }

        int count = tsAbnListService.lambdaQuery()
                .eq(TSAbnList::getPripid, pripid)
                .eq(TSAbnList::getSpecause, "1")
                .eq(TSAbnList::getOperatestatus, "1")
                .count();

        return RestResult.ok(count > 0);

    }
}
