package com.chinaweal.aiccs.aiccs.abnormal.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AbnProcessDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.TSBizSpeListVO;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.TSBizSpeListMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.auditing.mapper.TSOpinionMapper;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.entbase.entity.TREntPriseType;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntPriseTypeService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.query.entity.TSEntBaseQuery;
import com.chinaweal.aiccs.aiccs.query.service.TSEntBaseQueryService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.org.mapper.TUsersMapper;
import com.chinaweal.aiccs.org.service.AicorgService;
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.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 com.chinaweal.youfool.framework.sso.util.SSOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 列入经营异常名录业务表 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-01-19
 */
@Service
@Transactional
@Slf4j
public class TSBizSpeListServiceImpl extends ServiceImpl<TSBizSpeListMapper, TSBizSpeList> implements TSBizSpeListService {

    @Autowired
    private TSTaskListService taskListService;

    @Autowired
    private TSAbnListService tsAbnListService;

    @Autowired
    private TSWorkNoService tsWorkNoService;

    @Autowired
    private TSWritService tsWritService;

    @Autowired
    private TSEntBaseQueryService tsEntBaseQueryService;
    @Autowired
    private AicorgService aicorgService;

    @Autowired
    private ToincludeabnService toincludeabnService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Lazy
    @Resource
    private EBaseinfoService eBaseinfoService;
    @Resource
    private TSOpinionService opinionService;
    @Lazy
    @Resource
    private TSAttachmentService attachmentService;

    @Resource
    private WorkFlowService workFlowService;
    @Resource
    private OrgUM orgUM;
    @Lazy
    @Resource
    private IGzaiccodeService gzaiccodeService;

    @Resource
    private TUsersMapper tUsersMapper;
    @Autowired
    private ToinrosterService toinrosterService;
    @Resource
    private TSAttachmentService tsAttachmentService;
    @Resource
    private TSOpinionMapper tsOpinionMapper;
    @Autowired
    private TREntPriseTypeService entPriseTypeService;
    @Resource
    private AbnSerSmsLogService abnSerSmsLogService;

    @Override
    public TSTaskList saveAbnListAccept(AICUser user, TSTaskList taskListModel, List<TSBizSpeList> bizSpeList) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            for (TSBizSpeList bizSpeListModel : bizSpeList) {
                if(StringUtils.isNotEmpty(bizSpeListModel.getToIncludeId())) {
                    Toincludeabn toincludeabn = new Toincludeabn();
                    toincludeabn.setState("1");
                    toincludeabn.setToIncludeId(bizSpeListModel.getToIncludeId());
                    toincludeabn.setUpdateTime(LocalDateTime.now());
                    toincludeabnService.updateById(toincludeabn);// 更新拟列入表中数据状态
                }
                bizSpeListModel.setIntoSponsor(user.getName());//设置列入主办人
                bizSpeListModel.setIntoSponsorId(user.getPrimaryKey());
                bizSpeListModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
                bizSpeListModel.setLauptime(LocalDateTime.now());
                saveOrUpdate(bizSpeListModel);
            }
            String definedname = FlowUtil.EXPTLISTWORKFLOW;//企业经营异常名录流程模板
            //新待办 设置待办信息
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, user);
            //开始工作流
            taskListService.startWorkFlow(taskListModel, user, definedname);
        }
        return taskListModel;
    }

    @Override
    public List<TSBizSpeList> selectBSPexptlist(TSBizSpeList tsBizSpeListModel) {
        return baseMapper.selectBSPexptlist(tsBizSpeListModel);
    }

    @Override
    public IPage<TSBizSpeList> selectBSPExptByPageList(TSBizSpeList tsBizSpeListModel, IPage<TSBizSpeList> pagingCriteria) {
        return baseMapper.selectBSPExptByPageList(tsBizSpeListModel, pagingCriteria);
    }

    @Override
    public TSTaskList saveAbnListAuditProcess(AICUser user, TSTaskList taskListModel, List<TSBizSpeList> tsBizSpeList, TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        try {
            Map<String, TRBaseCode> codeMap;
            String type = tsBizSpeList.get(0).getType();
            if("company".equals(type)){
                codeMap = baseCodeService.getBaseCodeMapFormCache("CD71");
            }else if("individual".equals(type)) {
                codeMap = baseCodeService.getBaseCodeMapFormCache("CD75");
            }else {
                codeMap = baseCodeService.getBaseCodeMapFormCache("CD77");
            }
//            String orgCode = tUsersService.findOrgCode(user.getPrimaryKey());
//            String decOrgName = ConstantsUtil.getDecOrgName(orgCode);
            String orgCode = aicorgService.getRegionCodeByUser(user);
            String decOrgName = gzaiccodeService.getNameByCode(orgCode);
            for (TSBizSpeList bizSpeListModel : tsBizSpeList) {

                //下一步为审核
                if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeID)) {
                    bizSpeListModel.setStatus("1"); // 审批流程中把状态设置成 "审批中"
                    bizSpeListModel.setLauptime(LocalDateTime.now());
                    saveOrUpdate(bizSpeListModel);
                }
                //添加到 异常名录表
                if (FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeID)) {//完结时
                    if(bizSpeListModel.getEndApply()!=null && bizSpeListModel.getEndApply().equals("2")){ //不作列异操作
                        bizSpeListModel.setApprovaldate(LocalDate.now());//核准日期
                        bizSpeListModel.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                        bizSpeListModel.setLauptime(LocalDateTime.now());
                        updateById(bizSpeListModel);
                        continue;
                    }
                    TSAbnList tsAbnListModel = new TSAbnList();
                    tsAbnListModel.setAbnlistid(bizSpeListModel.getSpelistid());
                    tsAbnListModel.setPripid(bizSpeListModel.getPripid());
                    tsAbnListModel.setEntname(bizSpeListModel.getEntname());
                    tsAbnListModel.setRegno(bizSpeListModel.getRegno());
                    tsAbnListModel.setUniscid(bizSpeListModel.getUniscid());
                    tsAbnListModel.setEnttype(bizSpeListModel.getEnttype());
//                    tsAbnListModel.setSpereasons(bizSpeListModel.getSpereasons());
                    if(StringUtils.isNotEmpty(bizSpeListModel.getRemark()) && !bizSpeListModel.getRemark().equals("null")) {
                        tsAbnListModel.setIntoRemark(bizSpeListModel.getRemark());
                    }
//                    String regionCode = aicorgService.getRegionCodeByUser(user);
                    tsAbnListModel.setDecorg(orgCode);
                    tsAbnListModel.setIntoDecorg(decOrgName);
                    tsAbnListModel.setAbntime(LocalDate.now());
                    tsAbnListModel.setSpecause(bizSpeListModel.getSpecause());
                    TRBaseCode code = codeMap.get(bizSpeListModel.getSpecause());
                    if (code != null) {
                        tsAbnListModel.setSpereasons(code.getName());// 列入原因中文
                    }
                    // 法人信息
                    EBaseinfo baseinfo = eBaseinfoService.getOneByPripid(bizSpeListModel.getPripid());
                    tsAbnListModel.setLerep(baseinfo.getLerep());
                    tsAbnListModel.setCertype(baseinfo.getCertype());
                    tsAbnListModel.setCerno(baseinfo.getCerno());

                    tsAbnListModel.setReconsiderationOrg(bizSpeListModel.getReconsiderationOrg());
                    tsAbnListModel.setGovernmentOrg(bizSpeListModel.getGovernmentOrg());
                    tsAbnListModel.setLitiOrg(bizSpeListModel.getLitiOrg());
                    tsAbnListModel.setIntoSponsor(bizSpeListModel.getIntoSponsor()); // 主办人(列入)
                    if(StringUtils.isNotEmpty(bizSpeListModel.getRemark()) && !bizSpeListModel.getRemark().equals("null"))
                        tsAbnListModel.setIntoRemark(bizSpeListModel.getRemark());
                    tsAbnListModel.setAreaCode(orgCode);// 区码值
                    tsAbnListModel.setOperatestatus("1");
                    tsAbnListService.save(tsAbnListModel);

                    //获取法人手机号码
//        List<Map<String,String>> epriPersonList = eBaseinfoService.queryEpriPersonList(bizSpeListModel.getPripid());
//        if (epriPersonList.size() > 0) {
//            Map<String,String> epriPerson = epriPersonList.get(0);
//            if ( !"".equals(epriPerson.get("phone")) && epriPerson.get("phone") != null ) {
//                String phone = epriPerson.get("phone");
//                Set<String> set = new HashSet<>();
//                set.add(phone);
//                Calendar calendar = Calendar.getInstance();
//                int year = calendar.get(Calendar.YEAR);
//                int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以加1
//                int day = calendar.get(Calendar.DAY_OF_MONTH);
//                String text = "【信用监管系统】 您的企业：" + bizSpeListModel.getEntname() + "于" + year + "年" + month + "月" + day + "日被列入经营异常，如有异议请联系当地市场监督管理局询问。" ;
//                try {
//                    AbnSerSmsLog abnSerSmsLog = new AbnSerSmsLog();
//                    abnSerSmsLog.setAbnSerSmsid(UUID.randomUUID().toString());
//                    abnSerSmsLog.setAbnserid(bizSpeListModel.getSpelistid());
//                    abnSerSmsLog.setUsername(user.getPrimaryKey());
//                    abnSerSmsLog.setBizseq(bizSpeListModel.getBizseq());
//                    abnSerSmsLog.setContent(text);
//                    abnSerSmsLog.setPhones(phone);
//                    abnSerSmsLogService.save(abnSerSmsLog);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }


                    if(StringUtils.isNotEmpty(bizSpeListModel.getToIncludeId())) {
                        Toincludeabn toincludeabn = new Toincludeabn();
                        toincludeabn.setState("2");
                        toincludeabn.setToIncludeId(bizSpeListModel.getToIncludeId());
                        toincludeabn.setUpdateTime(LocalDateTime.now());
                        toincludeabnService.updateById(toincludeabn);// 更新拟列入表中数据状态
                    }
                    bizSpeListModel.setApprovaldate(LocalDate.now());//核准日期
                    bizSpeListModel.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                    updateById(bizSpeListModel);

/*
                    //生成文书号
                    if (BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG.equals(taskListModel.getBustype())) { //todo 个体户农合不用打印文书？
                        //个体工商户文书添加
                    } else if (BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD .equals(taskListModel.getBustype())) {
                        //农村合作社文书添加
                    } else {
                    }
*/
                    //文书号暂无分别对应规则 三类主体一样
                    LocalDateTime now = LocalDateTime.now();
                    TSWrit tsWritModel = new TSWrit();
                    tsWritModel.setWritsid(UUID.randomUUID().toString());
                    String workNoType = WorkNoUtil.WORKNOTYPE_11; //企业列入经营异常名录决定书文号
                    tsWritModel.setBizseq(bizSpeListModel.getBizseq());
                    //获取用户所在部门辖区码值
                    tsWritModel.setAreaCode(orgCode);

                    tsWritModel.setWritsno(tsWorkNoService.getOperatingWrirsno(workNoType, tsWritModel.getAreaCode())); //当前用户的regionID
                    tsWritModel.setWritstype(workNoType);
                    tsWritModel.setPripid(bizSpeListModel.getPripid());
                    tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
                    tsWritModel.setCreatetime(now);
                    tsWritModel.setContent(bizSpeListModel.getDecisionContent());
                    tsWritService.save(tsWritModel);
                    // 生成列异决定书附件
//                    HashMap<String, Object> map = new HashMap<>();
//                    String areaName = Constant.GZ_REGION_CODE.get(tsWritModel.getAreaCode());
//                    areaName = areaName.contains("广州市")? areaName:("广州市"+areaName);
//                    map.put("areaName",areaName);
//                    map.put("writsNo",tsWritModel.getWritsno());
//                    map.put("entname",bizSpeListModel.getEntname());
//                    map.put("decisionContent",tsWritModel.getContent());
//                    map.put("year",now.getYear());
//                    map.put("month",now.getMonthValue());
//                    map.put("day",now.getDayOfMonth());
//                    String path = "static" + File.separator +  "template" + File.separator + "incAbnDecision.docx";
//                    String pdfPath = createPdfService.createPdfWithTemplate(bizSpeListModel.getBizseq(), path, map);
//                    if(StringUtils.isNotBlank(pdfPath)){
//                        tsWritModel.setPath(pdfPath);
//                        tsWritService.updateById(tsWritModel);
//                    }
                    tsAbnListModel.setIntowritid(tsWritModel.getWritsid());
                    tsAbnListModel.setLauptime(LocalDateTime.now());
                    tsAbnListService.updateById(tsAbnListModel);

                    //  updateLimitInfo(user, tsBizSpeListModel1, map);//添加异常名录受限
                }
                //  审批选择不同意> 结束流程
                if (FlowUtil.EXPTLISTWORKFLOW_OVEREXPTLIST.equals(nextNodeID)) {
                    bizSpeListModel.setApprovaldate(LocalDate.now());//核准日期
                    bizSpeListModel.setStatus("3");// 9 受理中、1 审批中、2 已通过、3 不通过
                    bizSpeListModel.setLauptime(LocalDateTime.now());
                    updateById(bizSpeListModel);

                    if(StringUtils.isNotEmpty(bizSpeListModel.getToIncludeId())) {
                        Toincludeabn toincludeabn = new Toincludeabn();
                        toincludeabn.setState("0");
                        toincludeabn.setToIncludeId(bizSpeListModel.getToIncludeId());
                        toincludeabn.setUpdateTime(LocalDateTime.now());
                        toincludeabnService.updateById(toincludeabn);// 更新拟列入表中数据状态
                    }
                }
            }
            taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("列入经营异常名录审核出错");
        }
        return taskListModel;
    }

    @Override
    public IPage<TSEntBaseQuery> abnormalListByPage(IPage<TSEntBaseQuery> page, TSEntBaseQuery tsEntBaseQueryModel) {
        return tsEntBaseQueryService.abnormalListByPage(page, tsEntBaseQueryModel);
    }

    @Override
    public IPage<TSBizSpeList> selectAbnListBussByPage(IPage<TSBizSpeList> page, TSAbnList tsAbnListModel, String acceptno) {
        return baseMapper.selectAbnListBussByPage(page, tsAbnListModel, acceptno);
    }

    @Override
    public TSTaskList saveAbnModifyAuditProcess(AICUser user, TSTaskList taskListModel, List<TSBizSpeList> tsBizSpeList, TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        try {
            for (TSBizSpeList bizSpeListModel : tsBizSpeList) {
                if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeID)) { //审批时操作
                    bizSpeListModel.setStatus("1"); // 审批流程中把状态设置成 "审批中"
                    saveOrUpdate(bizSpeListModel);
                }

                if (FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeID)) {//完结时
                    //异常名录表 原记录
                    TSAbnList abnListModel = tsAbnListService.getById(bizSpeListModel.getBizseq());
                    abnListModel.setOperatestatus("3");//修改标识(相当该记录作废，下面生成一条新记录)
                    tsAbnListService.updateById(abnListModel);

                    //新增记录
                    TSAbnList tsAbnListModel = new TSAbnList();
                    tsAbnListModel.setAbnlistid(bizSpeListModel.getSpelistid());
                    tsAbnListModel.setPripid(bizSpeListModel.getPripid());
                    tsAbnListModel.setEntname(bizSpeListModel.getEntname());
                    tsAbnListModel.setRegno(bizSpeListModel.getRegno());
                    tsAbnListModel.setEnttype(bizSpeListModel.getEnttype());
                    tsAbnListModel.setSpereasons(bizSpeListModel.getSpereasons());
                    tsAbnListModel.setIntoDecorg(bizSpeListModel.getDecorg());
                    tsAbnListModel.setAbntime(abnListModel.getAbntime());//列入日期不变
                    tsAbnListModel.setSpecause(bizSpeListModel.getSpecause());
                    tsAbnListModel.setReconsiderationOrg(bizSpeListModel.getReconsiderationOrg());
                    tsAbnListModel.setGovernmentOrg(bizSpeListModel.getGovernmentOrg());
                    tsAbnListModel.setLitiOrg(bizSpeListModel.getLitiOrg());
                    tsAbnListModel.setOperatestatus("1");
                    tsAbnListService.save(tsAbnListModel);

                    //业务表
                    bizSpeListModel.setApprovaldate(LocalDate.now());//核准日期 异常名录修改查询结果，该字段用作列入日期
                    bizSpeListModel.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                    updateById(bizSpeListModel);

                    //todo 个体户农合不用打印文书？
                    if (BaseDataConstant.BUSINESS_TYPE_INDIVIDUAL_MODIFY.equals(taskListModel.getBustype())) {//个体工商户文书添加

                    } else if (BaseDataConstant.BUSINESS_TYPE_FARMER_MODIFY.equals(taskListModel.getBustype())) {//农合文书添加

                    } else { //企业文书添加
                        TSWrit tsWritModel = new TSWrit();
                        tsWritModel.setWritsid(UUID.randomUUID().toString());
                        String writsno = tsWorkNoService.getOperatingWrirsno(WorkNoUtil.WORKNOTYPE_11, user.getRegionID());
                        tsWritModel.setBizseq(bizSpeListModel.getBizseq());
                        tsWritModel.setWritsno(writsno);
                        tsWritModel.setWritstype(WorkNoUtil.WORKNOTYPE_11);
                        tsWritModel.setPripid(bizSpeListModel.getPripid());
                        tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(WorkNoUtil.WORKNOTYPE_11));
                        tsWritModel.setCreatetime(LocalDateTime.now());
                        tsWritService.save(tsWritModel);
                    }
                }
                //  审批选择不同意> 结束流程
                if (FlowUtil.EXPTLISTWORKFLOW_OVEREXPTLIST.equals(nextNodeID)) {
                    bizSpeListModel.setApprovaldate(LocalDate.now());//核准日期 异常名录修改查询结果，该字段用作列入日期
                    bizSpeListModel.setStatus("3"); // 9 受理中、1 审批中、2 已通过、3 不通过
                    updateById(bizSpeListModel);
                }
            }
            taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("修改经营异常名录审核出错");
        }
        return taskListModel;
    }

    @Override
    public IPage<TSBizSpeList> selectBizSpeByPageList(IPage<TSBizSpeList> pagingCriteria) {
        return baseMapper.selectBizSpeByPageList(pagingCriteria);
    }

    @Override
    public TSBizSpeList selectBSPexptlistById(String abnlistid) {
        return baseMapper.selectById(abnlistid);
    }

    @Override
    public IPage<TSBizSpeListVO> selectBizSpeListPage(IPage<TSBizSpeListVO> page, Map<String, Object> customParamMap) {
        return baseMapper.selectBizSpeListPage(page,customParamMap);
    }

    @Override
    public String updateTaskBusName(String bizseq) {
        List<TSTaskList> taskLists = taskListService.selectTaskListByBizseqid(bizseq);
        if(CollectionUtils.isNotEmpty(taskLists)) {
            TSTaskList taskList = taskLists.get(0);
            String bustype = taskList.getBustype();
            String type = null;
            if(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG.equals(bustype)){// 个体户
                type = "个体户";
            }else if(BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD.equals(bustype)) {
                type = "农合";
            }else {
                type = "企业";
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("bizseq",bizseq);
            map.put("type","biz");// 只查在办的
            IPage<TSBizSpeListVO> page = selectBizSpeListPage(new Page<>(1, 1), map);
            if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(page.getRecords())) {
                String busName = "(" + page.getTotal() + "家）关于" + page.getRecords().get(0).getEntname() + "等" + type;
                taskList.setBusname(busName);
                boolean update = taskListService.updateById(taskList);
                if(update){
                    return busName;
                }
            }
        }
        return null;
    }

    @Override
    public void clueResubmit(String dataFromId) {

    }

    @Override
    public boolean deleteClue(String toIncludeId, String deleteReason, AICUser user) {

        Toincludeabn toincludeabn = toincludeabnService.getById(toIncludeId);
        if(toincludeabn == null) {
            throw new BusinessException("找不到线索，无法废弃");
        }
//        String toIncludeId = toincludeabn.getToIncludeId();
        LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSBizSpeList::getToIncludeId, toIncludeId).eq(TSBizSpeList::getStatus,"9");
        List<TSBizSpeList> bizSpeLists = list(wrapper);
        if(bizSpeLists == null || bizSpeLists.size() == 0) {
            throw new BusinessException("业务表为空");
        }

        String bizseq = bizSpeLists.get(0).getBizseq();
        List<TSTaskList> taskLists = taskListService.selectByBizSeqID(bizseq);
        TSTaskList taskList = taskLists.get(0);
        // 废弃原因保存到意见表
        TSOpinion tsOpinion = new TSOpinion();
        tsOpinion.setOpiniontype("8");// 列异中 回退
        tsOpinion.setOpinioncontent(deleteReason);
        tsOpinion.setIsagree("2");
        tsOpinion.setLauptime(LocalDateTime.now());

        String[] ids = new String[]{user.getPrimaryKey()};
        String[] names = new String[]{user.getName()};
        taskListService.updateWorkFlow(user, tsOpinion, taskList, "overNullify", ids, names);

        // 更新业务表
        for(TSBizSpeList bizSpeList : bizSpeLists){
            bizSpeList.setStatus("4");// 4线索作废
            bizSpeList.setLauptime(LocalDateTime.now());
            updateById(bizSpeList);
        }

        // 作废线索
        Toincludeabn toincludeabnModel = new Toincludeabn();
        toincludeabnModel.setToIncludeId(toIncludeId);
        toincludeabnModel.setState("0");
        toincludeabnModel.setDataState("1");
        toincludeabnModel.setUpdateTime(LocalDateTime.now());
        boolean update = toincludeabnService.updateById(toincludeabnModel);
        if(!update){
            throw new BusinessException("线索作废失败");
        }
        return true;
    }

    @Override
    public Map<String, Object> clueAdd(String pripid, String includeType, String regEntryUserId, String regEntryUserName, String dataFrom, String dataFromId) {

        //地址的，列异中和已列异不生成线索
//        if("4".equals(includeType)){
//            LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
//            abnWrapper.eq(TSAbnList::getPripid, pripid)
//                    .eq(TSAbnList::getSpecause, "4")
//                    .eq(TSAbnList::getOperatestatus, "1");
//            List<TSAbnList> abnList = tsAbnListService.list(abnWrapper);
//            if(abnList.size() > 0){
//                Map<String, Object> resultMap = new HashMap<>();
//                resultMap.put("msg","该"+abnList.get(0).getEntname()+"企业因地址原因已列异，不重复生成列异线索");
//                return resultMap;
//            }
//
//            LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(TSBizSpeList::getPripid,pripid)
//                    .eq(TSBizSpeList::getIsRemove,"0")
//                    .eq(TSBizSpeList::getSpecause, "4")
//                    .notIn(TSBizSpeList::getStatus, "2", "3","4");
//            List<TSBizSpeList> list = list(wrapper);
//            if(list.size() > 0){
//                Map<String, Object> resultMap = new HashMap<>();
//                resultMap.put("msg","该"+list.get(0).getEntname()+"企业因地址原因在列异中，不重复生成列异线索");
//                return resultMap;
//            }
//        }

        // 判断是否需要保存
//        List<Toincludeabn> toincludeabns = toincludeabnService.list(
//                new LambdaQueryWrapper<Toincludeabn>().eq(Toincludeabn::getPripid,pripid).eq(Toincludeabn::getDataFromId, dataFromId)
//                        .eq(Toincludeabn::getIncludeType, includeType)
//                        .in(Toincludeabn::getState, new String[] {"0","1"}).eq(Toincludeabn::getDataState,"0")
//        );
//        if (toincludeabns.size() > 0) {
//            return null;
//        }
        // 保存
        EBaseinfo eBaseinfo = eBaseinfoService.getById(pripid);
        Toincludeabn toincludeabn = new Toincludeabn();
        toincludeabn.setToIncludeId(UUID.randomUUID().toString())
                .setPripid(eBaseinfo.getPripid())
                .setUniscid(eBaseinfo.getUniscid())
                .setRegno(eBaseinfo.getRegno())
                .setIncludeType(includeType)
                .setState("0")
                .setInsertTime(LocalDateTime.now())
                .setDataState("0")
                .setRegEntryUserId(regEntryUserId)
                .setRegEntryUserName(regEntryUserName).setDataFrom(dataFrom)
                .setDataFromId(dataFromId)
                .setEntOrgDer(eBaseinfo.getSuporg());
        Boolean rs = toincludeabnService.save(toincludeabn);
        return null;
    }

    @Override
    public boolean clueAddBatch(String pripids, String includeType, String regEntryUserId, String regEntryUserName, String dataFrom, String dataFromId) {
        if (StringUtils.isBlank(pripids)) return false;
        String[] pripidArrys = pripids.split(";");
        if (pripidArrys.length == 0) return false;
        // 查询用户是哪个所的
        String orgNumber = tUsersMapper.queryOrgNumByUserid(regEntryUserId);
//        // 保存
//        EBaseinfo eBaseinfo = eBaseinfoService.getById(pripidArrys[0]);
//        Toincludeabn toincludeabn1 = new Toincludeabn();
//        toincludeabn1.setToIncludeId(UUID.randomUUID().toString())
//                .setPripid(eBaseinfo.getPripid())
//                .setUniscid(eBaseinfo.getUniscid())
//                .setRegno(eBaseinfo.getRegno())
//                .setIncludeType(includeType)
//                .setState("0")
//                .setInsertTime(LocalDateTime.now())
//                .setDataState("0")
//                .setRegEntryUserId(regEntryUserId)
//                .setRegEntryUserName(regEntryUserName).setDataFrom(dataFrom)
//                .setDataFromId(dataFromId)
//                .setEntOrgDer(orgNumber)
//                .setIsbatch("1");
//        Boolean rs = toincludeabnService.save(toincludeabn1);
        String enterprise_sj_id = "";   //市局企业类型拟列异主体表id
        String individual_sj_id = "";   //市局个体户类型拟列异主体表id
        String farmer_sj_id = "";       //市局农合类型拟列异主体表id
        String enterprise_qj_id = "";   //区局企业类型拟列异主体表id
        String individual_qj_id = "";   //区局个体户类型拟列异主体表id
        String farmer_qj_id = "";       //区局农合类型拟列异主体表id
        for (int i=0; i<pripidArrys.length; i++) {
            EBaseinfo byId = eBaseinfoService.getById(pripidArrys[i]);
            //======市局======
            if ("440101".equals(byId.getRegorg())){
                switch (byId.getEnttype()) {
                    case "9910":
                    case "99100":
                    case "99101":
                    case "99102":
                    case "99103":
                    case "9999":   //个体户
                        individual_sj_id = this.saveToincludeabnAndToinroster(individual_sj_id, byId, includeType, regEntryUserId, regEntryUserName, dataFrom, dataFromId, orgNumber);
                        break;
                    case "9100":
                    case "9200":   //农合
                        farmer_sj_id = this.saveToincludeabnAndToinroster(farmer_sj_id, byId, includeType, regEntryUserId, regEntryUserName, dataFrom, dataFromId, orgNumber);
                        break;
                    default:       //企业
                        enterprise_sj_id = this.saveToincludeabnAndToinroster(enterprise_sj_id, byId, includeType, regEntryUserId, regEntryUserName, dataFrom, dataFromId, orgNumber);
                        break;
                }
            } else {   //======区局=======
                switch (byId.getEnttype()) {
                    case "9910":
                    case "99100":
                    case "99101":
                    case "99102":
                    case "99103":
                    case "9999":    //个体户
                        individual_qj_id = this.saveToincludeabnAndToinroster(individual_qj_id, byId, includeType, regEntryUserId, regEntryUserName, dataFrom, dataFromId, orgNumber);
                        break;
                    case "9100":
                    case "9200":    //农合
                        farmer_qj_id = this.saveToincludeabnAndToinroster(farmer_qj_id, byId, includeType, regEntryUserId, regEntryUserName, dataFrom, dataFromId, orgNumber);
                        break;
                    default:        //企业
                        enterprise_qj_id = this.saveToincludeabnAndToinroster(enterprise_qj_id, byId, includeType, regEntryUserId, regEntryUserName, dataFrom, dataFromId, orgNumber);
                        break;
                }
            }

        }
//        for (int i=0; i<pripidArrys.length; i++) {
//            EBaseinfo ebn = eBaseinfoService.getById(pripidArrys[i]);
//            Toinroster toinroster = new Toinroster().setId(UUID.randomUUID().toString())
//                    .setToIncludeId(toincludeabn1.getToIncludeId())
//                    .setPripid(ebn.getPripid())
//                    .setUniscid(ebn.getUniscid())
//                    .setRegno(ebn.getRegno())
//                    .setEntname(ebn.getEntname())
//                    .setRegOrg(ebn.getRegorg())
//                    .setAcceptOrg(ebn.getSuporg());
//            toinrosterService.save(toinroster);
//        }
        return true;
    }

    private String saveToincludeabnAndToinroster(String id, EBaseinfo eBaseinfo, String includeType,String regEntryUserId, String regEntryUserName, String dataFrom, String dataFromId, String orgNumber){
        if( StringUtils.isBlank(id)) {
            id = UUID.randomUUID().toString();
            Toincludeabn toincludeabn = new Toincludeabn();
            toincludeabn.setToIncludeId(id)
                    .setPripid(eBaseinfo.getPripid())
                    .setUniscid(eBaseinfo.getUniscid())
                    .setRegno(eBaseinfo.getRegno())
                    .setIncludeType(includeType)
                    .setState("0")
                    .setInsertTime(LocalDateTime.now())
                    .setDataState("0")
                    .setRegEntryUserId(regEntryUserId)
                    .setRegEntryUserName(regEntryUserName).setDataFrom(dataFrom)
                    .setDataFromId(dataFromId)
                    .setEntOrgDer(orgNumber)
                    .setIsbatch("1");
            toincludeabnService.save(toincludeabn);
        }
        if( StringUtils.isNotBlank(id) ){
            Toinroster toinroster = new Toinroster().setId(UUID.randomUUID().toString())
                    .setToIncludeId(id)
                    .setPripid(eBaseinfo.getPripid())
                    .setUniscid(eBaseinfo.getUniscid())
                    .setRegno(eBaseinfo.getRegno())
                    .setEntname(eBaseinfo.getEntname())
                    .setRegOrg(eBaseinfo.getRegorg())
                    .setAcceptOrg(eBaseinfo.getSuporg());
            toinrosterService.save(toinroster);
        }
        return id;
    }
    @Override
    public boolean updateClue(String type, String dataFromId) {
        List<Toincludeabn> toincludeabns = toincludeabnService.getListByDataFromId(dataFromId);
        for (Toincludeabn toincludeabn : toincludeabns) {

            String toIncludeId = toincludeabn.getToIncludeId();
            LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TSBizSpeList::getToIncludeId, toIncludeId).eq(TSBizSpeList::getStatus,"0");
            TSBizSpeList bizSpeList = getOne(wrapper);
            if (bizSpeList == null) {
                if ("delete".equals(type)) {
                    toincludeabn.setDataState("1");
                    toincludeabn.setUpdateTime(LocalDateTime.now());
                    toincludeabnService.updateById(toincludeabn);
                    continue;
                } else if ("update".equals(type)) {
                    // 未发起待办，不做处理
                    toincludeabn.setState("0");
                    toincludeabn.setUpdateTime(LocalDateTime.now());
                    toincludeabnService.updateById(toincludeabn);
                    continue;
                }
            }
            if (!"5".equals(toincludeabn.getState())) continue; // 不是回退状态，不做处理
            String bizseq = bizSpeList.getBizseq();
            List<TSTaskList> taskLists = taskListService.selectByBizSeqID(bizseq);
            TSTaskList taskList = taskLists.get(0);
            LambdaQueryWrapper<TSOpinion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TSOpinion::getWorkflowid, taskList.getWorkflowid())
                    .eq(TSOpinion::getOpiniontype, "9")
                    .orderByDesc(TSOpinion::getLauptime);
            List<TSOpinion> list = opinionService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                throw new BusinessException(ResultCode.DATA_NONE, "找不到经办人");
            }
            String[] ids = new String[]{list.get(0).getHandlerid()};
            String[] names = new String[]{list.get(0).getHandler()};
            AICUser user = new AICUser();
            user.setPrimaryKey(taskList.getSignuserid());
            user.setName(taskList.getSignloginname());
            // 废弃为delete
            if ("delete".equals(type)) {
                // 作废线索
                Toincludeabn toincludeabnModel = new Toincludeabn();
                toincludeabnModel.setToIncludeId(toIncludeId);
                toincludeabnModel.setDataState("1");
                boolean update = toincludeabnService.updateById(toincludeabnModel);
                if (!update) {
                    throw new BusinessException("线索作废失败");
                }
                // 更新业务表
                bizSpeList.setStatus("4");// 4线索作废
                bizSpeList.setLauptime(LocalDateTime.now());
                boolean update1 = updateById(bizSpeList);
                if (!update1) {
                    throw new BusinessException("业务更新失败");
                }
                // 更新流程
                taskListService.updateWorkFlow(user, null, taskList, "overNullify", ids, names);
            } else if ("update".equals(type)) {// 重新提交为update
                // 更新业务表
                bizSpeList.setStatus("9");// 设置为受理中
                bizSpeList.setLauptime(LocalDateTime.now());
                boolean update1 = updateById(bizSpeList);
                if (!update1) {
                    throw new BusinessException("业务更新失败");
                }
                // 更新附件列表
                TSAttachment tsAttachment = new TSAttachment();
                tsAttachment.setBizseq(bizseq);
                tsAttachment.setAttachtype("1");
                List<TSAttachment> attachments = attachmentService.selectwritByPage(tsAttachment);
                if (CollectionUtils.isNotEmpty(attachments)) {
                    for (TSAttachment attachment : attachments) {
                        attachmentService.removeById(attachment.getAttachmentid());
                    }
                }
                TSAttachment tsAttachment1 = new TSAttachment();
                tsAttachment1.setBizseq(dataFromId);
                List<TSAttachment> attachmentList = attachmentService.selectwritByPage(tsAttachment1);
                for (TSAttachment attachment : attachmentList) {
                    attachment.setAttachmentid(UUID.randomUUID().toString());
                    attachment.setBizseq(bizseq);
                    attachment.setAttachtype("1");//标记线索上传的附件类型为1
                    attachmentService.save(attachment);
                }
                toincludeabn.setState("1");
                toincludeabn.setUpdateTime(LocalDateTime.now());
                toincludeabnService.updateById(toincludeabn);
                // 更新流程
                taskListService.updateWorkFlow(user, null, taskList, "exptlistEnter", ids, names);
            }
        }
        return true;
    }

    @Override
    public boolean updateClueBatch(String type, String dataFromId, String pripids) {
        Toincludeabn toincludeabn = toincludeabnService.getOne(
                new LambdaQueryWrapper<Toincludeabn>().eq(Toincludeabn::getDataFromId,dataFromId));
        String toIncludeId = toincludeabn.getToIncludeId();
        List<TSBizSpeList> bizSpeLists = list(new LambdaQueryWrapper<TSBizSpeList>()
                .eq(TSBizSpeList::getToIncludeId,toIncludeId)
                .eq(TSBizSpeList::getStatus,"0")); // 线索回退状态业务表
        if(bizSpeLists.size() == 0) {
            if("delete".equals(type)){
                toincludeabn.setDataState("1");
                toincludeabn.setUpdateTime(LocalDateTime.now());
                toincludeabnService.updateById(toincludeabn);
                return true;
            } else if("update".equals(type)){
                // 未发起待办，不做处理
                toincludeabn.setState("0");
                toincludeabn.setUpdateTime(LocalDateTime.now());
                toincludeabnService.updateById(toincludeabn);
                return true;
            }
        }
        if (!"5".equals(toincludeabn.getState())) return true; // 不是回退状态，不做处理
        String bizseq = bizSpeLists.get(0).getBizseq();
        // 有可能再动态监管中剔除了
        List<String> pripidList = Arrays.asList(pripids.split(";"));
        for (TSBizSpeList tsBizSpeList : bizSpeLists) {
            if (!pripidList.contains(tsBizSpeList.getPripid())) {
                tsBizSpeList.setIsRemove("1");
                tsBizSpeList.setRemoveReason("在动态监管中剔除");
                updateById(tsBizSpeList);
            }
        }
        List<TSTaskList> taskLists = taskListService.selectByBizSeqID(bizseq);
        TSTaskList taskList = taskLists.get(0);
        LambdaQueryWrapper<TSOpinion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSOpinion::getWorkflowid, taskList.getWorkflowid())
                .eq(TSOpinion::getOpiniontype, "9")
                .orderByDesc(TSOpinion::getLauptime);
        List<TSOpinion> list = opinionService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException(ResultCode.DATA_NONE,"找不到经办人");
        }
        String[] ids = new String[]{list.get(0).getHandlerid()};
        String[] names = new String[]{list.get(0).getHandler()};
        AICUser user = new AICUser();
        user.setPrimaryKey(taskList.getSignuserid());
        user.setName(taskList.getSignloginname());
        // 废弃为delete
        if("delete".equals(type)){
            // 作废线索
            Toincludeabn toincludeabnModel = new Toincludeabn();
            toincludeabnModel.setToIncludeId(toIncludeId);
            toincludeabnModel.setDataState("1");
            boolean update = toincludeabnService.updateById(toincludeabnModel);
            if(!update){
                throw new BusinessException("线索作废失败");
            }
            // 更新业务表
            for (TSBizSpeList bizSpeList : bizSpeLists) {
                bizSpeList.setStatus("4");// 4线索作废
                bizSpeList.setLauptime(LocalDateTime.now());
                boolean update1 = updateById(bizSpeList);
                if(!update1){
                    throw new BusinessException("业务更新失败");
                }
            }
            // 更新流程
            taskListService.updateWorkFlow(user, null, taskList, "overNullify", ids, names);
        }else if("update".equals(type)){// 重新提交为update
            // 更新业务表
            for (TSBizSpeList bizSpeList : bizSpeLists) {
                bizSpeList.setStatus("9");// 设置为受理中
                bizSpeList.setLauptime(LocalDateTime.now());
                boolean update1 = updateById(bizSpeList);
                if(!update1){
                    throw new BusinessException("业务更新失败");
                }
            }
            // 更新附件列表
            TSAttachment tsAttachment = new TSAttachment();
            tsAttachment.setBizseq(bizseq);
//            tsAttachment.setAttachtype("1");
            List<TSAttachment> attachments = attachmentService.selectwritByPage(tsAttachment);
            if(CollectionUtils.isNotEmpty(attachments)) {
                for (TSAttachment attachment : attachments) {
                    attachmentService.removeById(attachment.getAttachmentid());
                }
            }
            TSAttachment tsAttachment1 = new TSAttachment();
            tsAttachment1.setBizseq(dataFromId);
            List<TSAttachment> attachmentList = attachmentService.selectwritByPage(tsAttachment1);
            for (TSAttachment attachment : attachmentList) {
                attachment.setAttachmentid(UUID.randomUUID().toString());
                attachment.setBizseq(bizseq);
                attachment.setAttachtype("1");//标记线索上传的附件类型为1
                attachmentService.save(attachment);
            }
            toincludeabn.setState("1");
            toincludeabn.setUpdateTime(LocalDateTime.now());
            toincludeabnService.updateById(toincludeabn);
            // 更改待办名称
            String busName = null;
            if(bizSpeLists.size() >1 ){
                busName = "(" + bizSpeLists.size() +  "家）关于" +bizSpeLists.get(0).getEntname() + "等" + type;
            }else {
                busName = bizSpeLists.get(0).getEntname();
            }
            taskList.setBusname(busName);
            taskListService.updateById(taskList);
            // 更新流程
            taskListService.updateWorkFlow(user, null, taskList, "exptlistEnter", ids, names);
        }
        return true;
    }

    @Override
    public boolean updateAicodsClue(String type, String dataFromId, String files) {
        List<Toincludeabn> toincludeabns = toincludeabnService.getListByDataFromId(dataFromId);
        for (Toincludeabn toincludeabn : toincludeabns) {
            if(toincludeabn == null) {
                throw new BusinessException(ResultCode.DATA_NONE,"找不到线索,无法操作");
            }
            String toIncludeId = toincludeabn.getToIncludeId();
            LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TSBizSpeList::getToIncludeId, toIncludeId).eq(TSBizSpeList::getStatus, "0");
            TSBizSpeList bizSpeList = getOne(wrapper);
            if(bizSpeList == null) { // 未发起的线索
                if("delete".equals(type)){
                    // 作废线索
                    toincludeabn.setDataState("1");
                    boolean update = toincludeabnService.updateById(toincludeabn);
                    return update;
                }else if("update".equals(type)){
                    // 更新附件列表
                    TSAttachment tsAttachment = new TSAttachment();
                    tsAttachment.setBizseq(dataFromId);
                    tsAttachment.setAttachtype("1");
                    List<TSAttachment> attachments = attachmentService.selectwritByPage(tsAttachment);
                    if(CollectionUtils.isNotEmpty(attachments)) {
                        for (TSAttachment attachment : attachments) {
                            attachmentService.removeById(attachment.getAttachmentid());
                        }
                    }
                    if(StringUtils.isNotBlank(files)) {
                        try {
                            attachmentService.saveClueFile(files,dataFromId);
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.info("业务更新失败" + e.getMessage());
                            throw new BusinessException("业务更新失败");
                        }
                    }
                    toincludeabn.setState("0");
                    toincludeabn.setDataState("0");
                    boolean update = toincludeabnService.updateById(toincludeabn);
                    return update;
                }
            }
            String bizseq = bizSpeList.getBizseq();
            List<TSTaskList> taskLists = taskListService.selectByBizSeqID(bizseq);
            TSTaskList taskList = taskLists.get(0);
            LambdaQueryWrapper<TSOpinion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TSOpinion::getWorkflowid, taskList.getWorkflowid())
                    .eq(TSOpinion::getOpiniontype, "9")
                    .orderByDesc(TSOpinion::getLauptime);
            List<TSOpinion> list = opinionService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                throw new BusinessException(ResultCode.DATA_NONE,"找不到经办人");
            }
            String[] ids = new String[]{list.get(0).getHandlerid()};
            String[] names = new String[]{list.get(0).getHandler()};
            AICUser user = new AICUser();
            user.setPrimaryKey(taskList.getSignuserid());
            user.setName(taskList.getSignloginname());
            // 废弃为delete
            if("delete".equals(type)){
                // 作废线索
                Toincludeabn toincludeabnModel = new Toincludeabn();
                toincludeabnModel.setToIncludeId(toIncludeId);
                toincludeabnModel.setDataState("1");
//            toincludeabnModel.setDataFromId(toincludeabn.getDataFromId() + "-FQ");
                boolean update = toincludeabnService.updateById(toincludeabnModel);
                if(!update){
                    throw new BusinessException("线索作废失败");
                }
                // 更新业务表
                bizSpeList.setStatus("4");// 4线索作废
                bizSpeList.setLauptime(LocalDateTime.now());
                boolean update1 = updateById(bizSpeList);
                if(!update1){
                    throw new BusinessException("业务更新失败");
                }
                // 更新流程
                taskListService.updateWorkFlow(user, null, taskList, "overNullify", ids, names);
            }else if("update".equals(type)){// 重新提交为update
                // 更新业务表
                bizSpeList.setStatus("9");// 设置为受理中
                bizSpeList.setLauptime(LocalDateTime.now());
                boolean update1 = updateById(bizSpeList);
                if(!update1){
                    throw new BusinessException("业务更新失败");
                }
                // 更新附件列表
                TSAttachment tsAttachment = new TSAttachment();
                tsAttachment.setBizseq(bizseq);
                tsAttachment.setAttachtype("1");
                List<TSAttachment> attachments = attachmentService.selectwritByPage(tsAttachment);
                if(CollectionUtils.isNotEmpty(attachments)) {
                    for (TSAttachment attachment : attachments) {
                        attachmentService.removeById(attachment.getAttachmentid());
                    }
                }

                if(StringUtils.isNotBlank(files)) {
                    try {
                        attachmentService.saveClueFile(files,bizseq);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("业务更新失败" + e.getMessage());
                        throw new BusinessException("业务更新失败");
                    }
                }
                // 更新流程
                taskListService.updateWorkFlow(user, null, taskList, "exptlistEnter", ids, names);
                Toincludeabn toincludeabnModel = new Toincludeabn();
                toincludeabnModel.setToIncludeId(toIncludeId);
                toincludeabnModel.setState("1");
                toincludeabnService.updateById(toincludeabnModel);
            }
        }
        return true;
    }

    @Override
    public TSBizSpeList getByToIncludeId(String toIncludeId) {
        LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSBizSpeList::getToIncludeId,toIncludeId)
                .eq(TSBizSpeList::getStatus,"0");
        return getOne(wrapper);
    }

    @Override
    public String getDecTempContent(String specause,String entertype,String decorg) {

//        String addr = "";
//        String phone = "";
//        addr = ConstantsUtil.getlyAddr(decorg);
//        phone = ConstantsUtil.getlyPhone(decorg);
        String secondPra = "";
        String xw = "";
        if ("individual".equals(entertype)) {
            xw = "标记经营异常状态";
        } else {
            xw = "列入经营异常名录";
        }
        secondPra = String.format("如对被%s有异议的，可自公示之日起30日内向作出决定的市场监督管理部门提出书面申请并提交相关证明材料，" +
                "市场监督管理部门依法作出处理。", xw);
        String firstPra = "";
        // 企业
        String specauseStr = "";
        String baseStr = "";
        if ("company".equals(entertype)){
            Map<String, TRBaseCode> causeMap = baseCodeService.getBaseCodeMapFormCache("CD71");
            if("5".equals(specause)){
                firstPra = "经查，登记机关认定你单位的商事主体名称为不适宜的商事主体名称，符合《内蒙古自治区商事登记条例》第三十六条所指的情形，根据《内蒙古自治区商事登记条例》第三十六条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
            }else {
                if ("1".equals(specause)) {
                    baseStr = "，根据《企业经营异常名录管理暂行办法》第六条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";

                } else if ("2".equals(specause)) {
                    baseStr = "，符合《企业经营异常名录管理暂行办法》第四条第一款第(二)项所指的情形，根据《企业经营异常名录管理暂行办法》第七条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
                } else if ("3".equals(specause)) {
                    baseStr = "，符合《企业经营异常名录管理暂行办法》第四条第一款第(三)项所指的情形，根据《企业经营异常名录管理暂行办法》第八条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
                } else if ("4".equals(specause)) {
                    baseStr = "，符合《企业经营异常名录管理暂行办法》第四条第一款第(四)项所指的情形，根据《企业经营异常名录管理暂行办法》第九条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
                }
                TRBaseCode code = causeMap.get(specause);
                if (code != null) {
                    specauseStr = code.getName();
                }
                firstPra = "经查，你单位因" + specauseStr + baseStr;
            }
        }else if ("individual".equals(entertype)){// 个体户
            Map<String, TRBaseCode> causeMap = baseCodeService.getBaseCodeMapFormCache("CD75");
            if ("1".equals(specause)) {
                baseStr = "，根据《个体工商户年度报告暂行办法》第十三条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
            }else if ("2".equals(specause)) {
                baseStr = "，根据《个体工商户年度报告暂行办法》第十四条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
            }else if ("3".equals(specause)) {
                baseStr = "，根据《个体工商户年度报告暂行办法》第十五条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
            }
            TRBaseCode code = causeMap.get(specause);
            if (code != null) {
                specauseStr = code.getName();
            }
            firstPra = "经查，你单位因" + specauseStr + baseStr;
        }else if ("farmer".equals(entertype)){// 农专社

            Map<String, TRBaseCode> causeMap = baseCodeService.getBaseCodeMapFormCache("CD77");
            if ("1".equals(specause)) {
                baseStr = "，根据《农民专业合作社年度报告公示暂行办法》第十条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
            }else if ("2".equals(specause)) {
                baseStr = "，根据《农民专业合作社年度报告公示暂行办法》第十一条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
            }else if ("3".equals(specause)) {
                baseStr = "，根据《农民专业合作社年度报告公示暂行办法》第十二条的规定，我局决定将你单位列入经营异常名录，并向社会公示。";
            }
            TRBaseCode code = causeMap.get(specause);
            if (code != null) {
                specauseStr = code.getName();
            }
            firstPra = "经查，你单位因" + specauseStr + baseStr;
        }
        return firstPra + "\n" + secondPra;
    }

    @Override
    public void processControl(AbnProcessDto abnProcessDto, TSTaskList taskList, List<TSBizSpeList> tsBizSpeList, AICUser loginUser) throws Exception {
        TSTwfProcessNode twfProcessNode = workFlowService.findCurrentNode(taskList.getWorkflowid());
        String link = String.format("%s_%s", twfProcessNode.getCurrentnode(), abnProcessDto.getNextNodeID());
        switch (link) {
            case "exptlistEnter_handleExptlist": // 经办_审核
                this.toHandleCase(abnProcessDto, taskList, tsBizSpeList, loginUser);
                break;
            case "exptlistEnter_clueReturn": // 线索回退
                break;
            case "exptlistEnter_overNullify": // 线索作废
                break;
            case "clueReturn_overNullify": // 线索作废
                break;
            case "clueReturn_exptlistEnter": // 线索重新提交
                break;
            case "handleExptlist_exptlistEnter": // 审核回退经办
            case "approvelist_exptlistEnter": // 审批回退至经办
                LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TSBizSpeList::getBizseq, taskList.getBizseqid()).eq(TSBizSpeList::getIsRemove, "0");
                List<TSBizSpeList> bizSpeLists = this.list(wrapper);
                for(TSBizSpeList bizSpeList : bizSpeLists){
                    bizSpeList.setStatus("9");      //修改状态为受理中
                    bizSpeList.setLauptime(LocalDateTime.now());
                    this.updateById(bizSpeList);
                }
                this.backLastStep(abnProcessDto,taskList,twfProcessNode.getCurrentnode(),abnProcessDto.getNextNodeID());
                break;
            case "approvelist_handleExptlist": // 审批回退审核
                this.backLastStep(abnProcessDto,taskList,twfProcessNode.getCurrentnode(),abnProcessDto.getNextNodeID());
                break;
            case "handleExptlist_approvelist": // 审核_审批
                break;
            case "approvelist_endExptlist": // 审批通过
                this.toEndExptlist(abnProcessDto, taskList, tsBizSpeList, loginUser);
                break;
            case "exptlistEnter_overFinish": // 经办人结束流程
            case "exptlistEnter_overExptlist": // 经办人结束流程
            case "approvelist_overExptlist": // 审批不同意
                this.toOverExptlist(abnProcessDto, taskList, tsBizSpeList, loginUser);
                break;
            default:
                throw new RuntimeException("流程扭转出错");
        }
        // 流程推进
        taskListService.updateWorkFlow(loginUser, abnProcessDto.getOpinion(), taskList, abnProcessDto.getNextNodeID(), abnProcessDto.getNextPerformerIds(), abnProcessDto.getNextPerformerNames());

    }

    @Override
    public void toHandleCase(AbnProcessDto abnProcessDto, TSTaskList taskList, List<TSBizSpeList> tsBizSpeList, AICUser loginUser){
        Boolean qs = StringUtils.isBlank(tsBizSpeList.get(0).getIntoSponsor()); // 是否需要签收
        TSBizSpeList tsBizSpeListModel = abnProcessDto.getTsBizSpeListModel();
        TSBizSpeList tsBizSpeListParam = new TSBizSpeList();
        tsBizSpeListParam.setBizseq(tsBizSpeListModel.getBizseq());
        if(StringUtils.isNotEmpty(tsBizSpeListModel.getRemark())) {
            tsBizSpeListParam.setRemark(tsBizSpeListModel.getRemark());
        }
        tsBizSpeListParam.setReconsiderationOrg(tsBizSpeListModel.getReconsiderationOrg());
        tsBizSpeListParam.setGovernmentOrg(tsBizSpeListModel.getGovernmentOrg());
        tsBizSpeListParam.setLitiOrg(tsBizSpeListModel.getLitiOrg());
        tsBizSpeListParam.setSpecause(tsBizSpeListModel.getSpecause());
        tsBizSpeListParam.setDecisionContent(tsBizSpeListModel.getDecisionContent());
        tsBizSpeListParam.setEndApply(tsBizSpeListModel.getEndApply());
        tsBizSpeListParam.setEndReason(tsBizSpeListModel.getEndReason());
        tsBizSpeListParam.setCaseSource(tsBizSpeListModel.getCaseSource());
        tsBizSpeListParam.setContactEntity(tsBizSpeListModel.getContactEntity());
        tsBizSpeListParam.setContactMethodOrg(tsBizSpeListModel.getContactMethodOrg());

        tsBizSpeListParam.setStatus("1"); // 审批流程中把状态设置成 "审批中"
        tsBizSpeListParam.setLauptime(LocalDateTime.now());
        if (qs) {
            tsBizSpeListParam.setIntoSponsorId(loginUser.getPrimaryKey());
            tsBizSpeListParam.setIntoSponsor(loginUser.getName());
        }
        updateByBizseq(tsBizSpeListParam);
        if (qs) { // 以组为接收单位的需要签收
            workFlowService.claimGroup(taskList.getWorkflowid(),loginUser.getPrimaryKey());
        }
//        updateBatchById(tsBizSpeList);
    }

    @Override
    public void toEndExptlist(AbnProcessDto abnProcessDto, TSTaskList taskList, List<TSBizSpeList> tsBizSpeList, AICUser loginUser) {
        AICUser user = SSOUtil.getUser();
        TSBizSpeList speListDB = tsBizSpeList.get(0);
        // 获取主办人
        abnProcessDto.setNextPerformerIds(new String[]{speListDB.getIntoSponsorId()});
        abnProcessDto.setNextPerformerNames(new String[]{speListDB.getIntoSponsor()});
//        String orgCode = tUsersService.findOrgCode(loginUser.getPrimaryKey());
//        String decOrgName = ConstantsUtil.getDecOrgName(orgCode);
        String orgCode = aicorgService.getRegionCodeByUser(loginUser);
        String decOrgName = gzaiccodeService.getNameByCode(orgCode);
        Map<String, TRBaseCode> codeMap;
        String type = tsBizSpeList.get(0).getType();
        if("company".equals(type)){
            codeMap = baseCodeService.getBaseCodeMapFormCache("CD71");
        }else if("individual".equals(type)) {
            codeMap = baseCodeService.getBaseCodeMapFormCache("CD75");
        }else {
            codeMap = baseCodeService.getBaseCodeMapFormCache("CD77");
        }
        int i = 0;
        int total = tsBizSpeList.size();
        List<TSAbnList> tsAbnLists = new ArrayList<>();
        List<TSWrit> tsWritList = new ArrayList<>();
        List<AbnSerSmsLog> abnSerSmsLogList = new ArrayList<>();
        List<String> wrisnoList = tsWorkNoService.getOperatingWrirsnoBatch(WorkNoUtil.WORKNOTYPE_11, orgCode,tsBizSpeList.size());


        Long start = System.currentTimeMillis();
        if(speListDB.getEndApply()!=null && speListDB.getEndApply().equals("2")){ //不作列异操作
            speListDB.setApprovaldate(LocalDate.now());//核准日期
            speListDB.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
            speListDB.setLauptime(LocalDateTime.now());
            updateStatus(speListDB);
        } else {
            speListDB.setApprovaldate(LocalDate.now());//核准日期
            speListDB.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
            speListDB.setLauptime(LocalDateTime.now());
            updateStatus(speListDB);
        }
        log.info("审批环节更新业务表耗时：" + (System.currentTimeMillis() - start)+ "ms");
        start = System.currentTimeMillis();
        for (TSBizSpeList each : tsBizSpeList) {
            if(each.getEndApply()!=null && each.getEndApply().equals("2")){ //不作列异操作
                continue;
            }

            // 保存至异常名录表
            TSAbnList tsAbnListModel = new TSAbnList();
            tsAbnListModel.setAbnlistid(each.getSpelistid());
            tsAbnListModel.setPripid(each.getPripid());
            tsAbnListModel.setEntname(each.getEntname());
            tsAbnListModel.setRegno(each.getRegno());
            tsAbnListModel.setUniscid(each.getUniscid());
            tsAbnListModel.setEnttype(each.getEnttype());
            if(StringUtils.isNotEmpty(each.getRemark()) && !each.getRemark().equals("null")) {
                tsAbnListModel.setIntoRemark(each.getRemark());
            }
            tsAbnListModel.setDecorg(orgCode);
            tsAbnListModel.setIntoDecorg(decOrgName);
            tsAbnListModel.setAbntime(LocalDate.now());
            tsAbnListModel.setSpecause(each.getSpecause());
            tsAbnListModel.setCaseSource(each.getCaseSource());
            tsAbnListModel.setContactEntity(each.getContactEntity());
            tsAbnListModel.setContactMethodOrg(each.getContactMethodOrg());
            TRBaseCode code = codeMap.get(each.getSpecause());
            if (code != null) {
                tsAbnListModel.setSpereasons(code.getName());// 列入原因中文
            }
            // 法人信息
            EBaseinfo baseinfo = eBaseinfoService.getOneByPripid(each.getPripid());
//            if (baseinfo.getLerep() == null || "".equals(baseinfo.getLerep())){
//                throw new BusinessException("列入经营异常法人名称为空！");
//            }
            tsAbnListModel.setLerep(baseinfo.getLerep());
            tsAbnListModel.setCertype(baseinfo.getCertype());
//            if (baseinfo.getCerno() == null || "".equals(baseinfo.getCerno())){
//                throw new BusinessException("列入经营异常身份证为空！");
//            }
            tsAbnListModel.setCerno(baseinfo.getCerno());

            tsAbnListModel.setReconsiderationOrg(each.getReconsiderationOrg());
            tsAbnListModel.setGovernmentOrg(each.getGovernmentOrg());
            tsAbnListModel.setLitiOrg(each.getLitiOrg());
            tsAbnListModel.setIntoSponsor(each.getIntoSponsor()); // 主办人(列入)
            tsAbnListModel.setAreaCode(orgCode);// 区码值
            tsAbnListModel.setOperatestatus("1");
//            tsAbnListService.save(tsAbnListModel);
            if(StringUtils.isNotEmpty(each.getToIncludeId())) {
                Toincludeabn toincludeabn = new Toincludeabn();
                toincludeabn.setState("2");
                toincludeabn.setToIncludeId(each.getToIncludeId());
                toincludeabn.setUpdateTime(LocalDateTime.now());
                toincludeabnService.updateById(toincludeabn);// 更新拟列入表中数据状态
            }
//            each.setApprovaldate(LocalDate.now());//核准日期
//            each.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
//            updateById(each);

            //文书号暂无分别对应规则 三类主体一样
            LocalDateTime now = LocalDateTime.now();
            TSWrit tsWritModel = new TSWrit();
            tsWritModel.setWritsid(UUID.randomUUID().toString());
            String workNoType = WorkNoUtil.WORKNOTYPE_11; //企业列入经营异常名录决定书文号
            tsWritModel.setBizseq(each.getBizseq());
            //获取用户所在部门辖区码值
            tsWritModel.setAreaCode(orgCode);

            tsWritModel.setWritsno(wrisnoList.get(i)); //当前用户的regionID
            tsWritModel.setWritstype(workNoType);
            tsWritModel.setPripid(each.getPripid());
            tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
            tsWritModel.setCreatetime(now);
            tsWritModel.setContent(each.getDecisionContent());
            tsWritList.add(tsWritModel);
//            tsWritService.save(tsWritModel);
            //TODO 待确认是否要生成附件实体并上传至服务器 生成列异决定书附件
            tsAbnListModel.setIntowritid(tsWritModel.getWritsid());
            tsAbnListModel.setLauptime(LocalDateTime.now());
            tsAbnLists.add(tsAbnListModel);
            i++;
            //获取法人手机号码
//        List<Map<String,String>> epriPersonList = eBaseinfoService.queryEpriPersonList(each.getPripid());
//        if (epriPersonList.size() > 0) {
//            Map<String,String> epriPerson = epriPersonList.get(0);
//            if ( !"".equals(epriPerson.get("phone")) && epriPerson.get("phone") != null ) {
//                String phone = epriPerson.get("phone");
//                Set<String> set = new HashSet<>();
//                set.add(phone);
//                Calendar calendar = Calendar.getInstance();
//                int year = calendar.get(Calendar.YEAR);
//                int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以加1
//                int day = calendar.get(Calendar.DAY_OF_MONTH);
//                String text = "【信用监管系统】 您的企业：" + each.getEntname() + "于" + year + "年" + month + "月" + day + "日被列入经营异常，如有异议请联系当地市场监督管理局询问。" ;
//                try {
//                    AbnSerSmsLog abnSerSmsLog = new AbnSerSmsLog();
//                    abnSerSmsLog.setAbnSerSmsid(UUID.randomUUID().toString());
//                    abnSerSmsLog.setAbnserid(each.getSpelistid());
//                    abnSerSmsLog.setUsername(user.getPrimaryKey());
//                    abnSerSmsLog.setBizseq(each.getBizseq());
//                    abnSerSmsLog.setContent(text);
//                    abnSerSmsLog.setPhones(phone);
//                    abnSerSmsLogList.add(abnSerSmsLog);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }
            // 500条commit一次
            if (i % 500 == 0 || i == total) {
                Long start2 = System.currentTimeMillis();
                tsAbnListService.saveAbnBatch(tsAbnLists);
                log.info("审批环节插入异常名录表(500条commit一次)耗时：" + (System.currentTimeMillis() - start2)+ "ms");
                start2 = System.currentTimeMillis();
                tsWritService.saveBatchWithList(tsWritList);
                log.info("审批环节插入文书表(500条commit一次)耗时：" + (System.currentTimeMillis() - start2)+ "ms");
//                abnSerSmsLogService.saveBatch(abnSerSmsLogList);
                tsAbnLists.clear();
                tsWritList.clear();
            }
//            tsAbnListService.updateById(tsAbnListModel);
        }
        log.info("审批环节操作结果耗时：" + (System.currentTimeMillis() - start)+ "ms");
    }

    @Override
    public void toOverExptlist(AbnProcessDto abnProcessDto, TSTaskList taskList, List<TSBizSpeList> tsBizSpeList, AICUser loginUser) {
        TSBizSpeList tsBizSpeListModel = abnProcessDto.getTsBizSpeListModel();
        for (TSBizSpeList each : tsBizSpeList) {
            each.setEndReason(tsBizSpeListModel.getEndReason());
            each.setApprovaldate(LocalDate.now());//核准日期
            each.setStatus("3");// 9 受理中、1 审批中、2 已通过、3 不通过
            each.setLauptime(LocalDateTime.now());
            updateById(each);
            if (StringUtils.isNotEmpty(each.getToIncludeId())) {
                Toincludeabn toincludeabn = new Toincludeabn();
                toincludeabn.setState("0");
                toincludeabn.setToIncludeId(each.getToIncludeId());
                toincludeabn.setUpdateTime(LocalDateTime.now());
                toincludeabnService.updateById(toincludeabn);// 更新拟列入表中数据状态
            }
        }
    }
    @Override
    public void backLastStep(AbnProcessDto abnProcessDto, TSTaskList taskList, String currentNode, String nextNode) {
        String userId = workFlowService.findLastTwfprocessnodeByProcessidAndNodename(taskList.getWorkflowid(), currentNode, nextNode);
        AICUser handler = orgUM.findUserByPrimaryKey(userId);
        abnProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        abnProcessDto.setNextPerformerNames(new String[]{handler.getName()});
    }

    @Override
    public Boolean saveTsbizspelistBatch(List<TSBizSpeList> list) {
        return baseMapper.saveTsbizspelistBatch(list);
    }

    @Override
    public void updateByBizseq(TSBizSpeList tsBizSpeList) {
        baseMapper.updateByBizseq(tsBizSpeList);
    }

    @Override
    public void updateStatus(TSBizSpeList tsBizSpeList) {
        baseMapper.updateStatus(tsBizSpeList);
    }

    @Override
    public String checkEBaseinfo(String pripid, String entertype, String includeType) {
        // 校验是否开业状态
        LambdaQueryWrapper<EBaseinfo> entWrapper = new LambdaQueryWrapper<>();
        entWrapper.eq(EBaseinfo::getPripid, pripid);
        EBaseinfo baseinfo = eBaseinfoService.getOne(entWrapper, false);
        if(baseinfo != null && !"1".equals(baseinfo.getRegstate())){
            return "该主体非开业状态";
        }
        //监管机构验证---------------
        // "非本机构监管主体,不能列入"
//        if (toincludeabn != null) {
//            if (!StringUtils.equals(StringUtils.trimToEmpty(aicUser.getRegionID()),
//                    StringUtils.trimToEmpty(toincludeabn))) {
//                return "1";//"非本机构监管主体,不能列入"
//            }
//        }
//        String reason = "";
//        // 校验是否已列
//        LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
//        abnWrapper.eq(TSAbnList::getPripid, pripid)// pripid
//                .eq(TSAbnList::getOperatestatus, "1");// 列入状态
//        if("4".equals(includeType)){
//            if (entertype.equals("company")) {
//                abnWrapper.eq(TSAbnList::getSpecause, "4");// 因地址列入
//            } else if (entertype.equals("individual") || entertype.equals("farmer")) {
//                abnWrapper.eq(TSAbnList::getSpecause, "3");
//            }
//            reason = "因实地查无";
//        } else if("3".equals(includeType)){
//            if (entertype.equals("company")) {
//                abnWrapper.eq(TSAbnList::getSpecause, "3");
//            } else if (entertype.equals("individual") || entertype.equals("farmer")) {
//                abnWrapper.eq(TSAbnList::getSpecause, "2");
//            }
//            reason = "因虚假公示";
//        }
//        // 企业列入原因为2 "未在市场监督管理部门依照《企业信息公示暂行条例》第十条规定责令的期限内公示有关企业信息的"的验证
//        else if("2".equals(includeType)){
//            if (entertype.equals("company")) {
//                abnWrapper.eq(TSAbnList::getSpecause, "2");
//                reason = "因未在市场监督管理部门依照《企业信息公示暂行条例》第十条规定责令的期限内公示有关企业信息";
//            }
//
//        }
//        TSAbnList abnList = tsAbnListService.getOne(abnWrapper, false);
//        if (abnList != null) {// 未被列异
//            return abnList.getEntname() + reason +"已被列异";
//        }
        return "success";
    }

    @Override
    public RestResult<?> saveAcceptBatch(String id, String entertype, HttpServletRequest request) {
        AICUser aicUser = SSOUtil.getUser();
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotBlank(id, entertype);
        String bizSeq = UUID.randomUUID().toString();
        List<TSBizSpeList> bizSpeList = new ArrayList<>();
        String code = aicorgService.getRegionCodeByUser(aicUser);
        Toincludeabn toincludeabn = toincludeabnService.getOne(new LambdaQueryWrapper<Toincludeabn>().eq(Toincludeabn::getToIncludeId, id));
        String reaType = toincludeabn.getIncludeType();
        List<Toinroster> toinrosters = toinrosterService.list(new LambdaQueryWrapper<Toinroster>()
                .eq(Toinroster::getToIncludeId,toincludeabn.getToIncludeId()));
        for (Toinroster toinroster : toinrosters) {
            EBaseinfo eBaseinfo = eBaseinfoService.getById(toinroster.getPripid());
            TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
            tsBizSpeListModel.setToIncludeId(toincludeabn.getToIncludeId());
            tsBizSpeListModel.setBizseq(bizSeq);
            tsBizSpeListModel.setPripid(eBaseinfo.getPripid());
            tsBizSpeListModel.setRegno(eBaseinfo.getRegno());
            tsBizSpeListModel.setUniscid(eBaseinfo.getUniscid());
            tsBizSpeListModel.setEntname(eBaseinfo.getEntname());
            tsBizSpeListModel.setEnttype(eBaseinfo.getEnttype());
            tsBizSpeListModel.setIsRemove("0");
            tsBizSpeListModel.setType(entertype);// 区分主体类型：企业，个体户，农专
            if("3".equals(reaType)){//虚假公示
                if("company".equals(entertype)){
                    tsBizSpeListModel.setSpecause("3");
                }else {
                    tsBizSpeListModel.setSpecause("2");
                }
            }else if("4".equals(reaType)){// 实地查无
                if("company".equals(entertype)){
                    tsBizSpeListModel.setSpecause("4");
                }else {
                    tsBizSpeListModel.setSpecause("3");
                }
                // 实地查无 保存当时主体地址
                // TODO 确认地址信息字段
                if("individual".equals(entertype)){
                    tsBizSpeListModel.setDom(eBaseinfo.getOploc());
                }else {
                    tsBizSpeListModel.setDom(eBaseinfo.getDom());
                }
            }else if("1".equals(reaType)) {// 未年报
                // TODO 保存未年报年度
//                tsBizSpeListModel.setReportYear());
            }else if("2".equals(reaType)) {// 未在规定期内公示
                if("company".equals(entertype)){
                    tsBizSpeListModel.setSpecause("2");
                }
            }
            tsBizSpeListModel.setDecorg(code);
            tsBizSpeListModel.setDecisionContent(getDecTempContent(tsBizSpeListModel.getSpecause(),
                    entertype,tsBizSpeListModel.getDecorg()));
            bizSpeList.add(tsBizSpeListModel);
        }
        if (bizSpeList.size() == 0) throw new BusinessException("尚未查找到企业信息");
        // 文件信息拷贝
        TSAttachment tsAttachment = new TSAttachment();
        tsAttachment.setBizseq(toincludeabn.getDataFromId());
        List<TSAttachment> attachmentList = tsAttachmentService.selectwritByPage(tsAttachment);
        for (TSAttachment attachment : attachmentList) {
            TSAttachment tsAttachmentModel = new TSAttachment();
            tsAttachmentModel.setAttachmentid(UUID.randomUUID().toString());
            tsAttachmentModel.setBizseq(bizSeq);
            tsAttachmentModel.setAttachtype("1");//标记线索上传的附件类型为1
            tsAttachmentModel.setLauptime(LocalDateTime.now());
            tsAttachmentModel.setFileurl(attachment.getFileurl());
            tsAttachmentModel.setTemppath(attachment.getTemppath());
            tsAttachmentModel.setFilename(attachment.getFilename());
            tsAttachmentModel.setUploaddate(attachment.getUploaddate());
            tsAttachmentModel.setFileext(attachment.getFileext());
            tsAttachment.setCreatetype("1");
            tsAttachmentService.save(tsAttachmentModel);
        }
        //待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        String type = "";
        if (entertype.equals("individual")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG);//个体工商户
            type = "个体户";
        } else if (entertype.equals("farmer")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD);////农合
            type = "农合";
        } else {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP);//企业异常名录
            type = "企业";
        }
        String busName = null;
        if(bizSpeList.size() >1 ){
            busName = "(" + bizSpeList.size() +  "家）关于" +bizSpeList.get(0).getEntname() + "等" + type;

        }else {
            busName = bizSpeList.get(0).getEntname();
        }
        taskListModel.setBusname(busName);
        //经营异常受理保存
        taskListModel = saveAbnListAccept(aicUser, taskListModel, bizSpeList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, String> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizSeq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }
        return RestResult.ok();
    }

    @Override
    public RestResult<?> queryOldabnInfo(String SAPPROVECODE) {
        Map<String, Object> rsMap = new HashMap<>();
        List<TSOpinion> tsOpinions = tsOpinionMapper.queryOldOpninion(SAPPROVECODE);
        TSBizSpeListVO tsBizSpeListVO = baseMapper.getOldBizSpeListInfo(SAPPROVECODE);
        List<TSAttachment> tsAttachments = tsAttachmentService.queryFileByHistory(SAPPROVECODE);
        rsMap.put("tsOpinions", tsOpinions);
        rsMap.put("tsBizSpeListVO", tsBizSpeListVO);
        rsMap.put("tsAttachments",tsAttachments);
        return RestResult.ok(rsMap);
    }

    @Override
    public RestResult<?> getOldBizSpeListPage(PageRequestDto pageRequestDto) {
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        String SAPPROVECODE = paramMap.get("bizseq").toString();
        IPage<TSBizSpeListVO> page = baseMapper.getOldBizSpeListPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()),SAPPROVECODE);
        // 封装企业基本信息
        if(CollectionUtils.isNotEmpty(page.getRecords())){
            page.setRecords(fillAttribute(page.getRecords()));
        }
        return RestResult.ok(page);
    }

    @Override
    public void exportExcelOldBizSpeList(OutputStream outputStream, String SAPPROVECODE) {
        List<TSBizSpeListVO> tsBizSpeListVOS = baseMapper.getOldBizSpeListPage(SAPPROVECODE);
        tsBizSpeListVOS = fillAttribute(tsBizSpeListVOS);
        ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
        WriteSheet writeSheet1 = EasyExcel.writerSheet(0, "sheet1").head(TSBizSpeListVO.class).build();
        excelWriter.write(tsBizSpeListVOS, writeSheet1);
        excelWriter.finish();
    }

    public List<TSBizSpeListVO> fillAttribute(List<TSBizSpeListVO> tsBizSpeListVOS) {
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        for (TSBizSpeListVO record : tsBizSpeListVOS) {
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, record.getPripid()));
            record.setUscc(eBaseinfo.getUniscid());
            record.setUniscid(eBaseinfo.getUniscid());
            record.setRegstate(eBaseinfo.getRegstate());//登记状态
            TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
            if(code != null) {
                record.setRegstateCn(code.getName());//登记状态str
            }
            record.setEstDate(eBaseinfo.getEstdate());//成立日期
            if (eBaseinfo.getEnttypeCn() == null) {
                TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(eBaseinfo.getEnttype());
                if (type != null) {
                    record.setEntTypeName(type.getDisplayvalue());
                }
            }else {
                record.setEntTypeName(eBaseinfo.getEnttypeCn());
            }
            record.setDecorgCn(gzaiccodeService.getNameByCode(record.getDecorg()));
        }
        return tsBizSpeListVOS;
    }
}
