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

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.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.revoke.entity.Illegalact;
import com.chinaweal.aiccs.aiccs.revoke.entity.TsCase;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tsbizrevlist;
import com.chinaweal.aiccs.aiccs.revoke.mapper.CaseMapper;
import com.chinaweal.aiccs.aiccs.revoke.service.CaseService;
import com.chinaweal.aiccs.aiccs.revoke.service.IllegalactService;
import com.chinaweal.aiccs.aiccs.revoke.service.TsbizrevlistService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
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.deepoove.poi.XWPFTemplate;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 案件审批表 服务实现类
 * </p>
 *
 * @author Lee
 * @since 2021-03-30
 */
@Service
public class CaseServiceImpl extends BaseServiceImpl<CaseMapper, TsCase> implements CaseService {

    @Autowired
    private IllegalactService illegalactService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private TSOpinionService opinionService;
    @Lazy
    @Autowired
    private TsbizrevlistService tsbizrevlistService;

    @Override
    public void createCaseApprovalDocx(String bizseq) {
        if(StringUtils.isNotBlank(bizseq)) {
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq,bizseq);
            TsCase tsCase = getOne(wrapper);
            // 案件信息
            if(tsCase != null){
                Map<String, Object> map = new HashMap<>();
                // 违法行为信息
                List<Illegalact> illegalactList = illegalactService.list(new LambdaQueryWrapper<Illegalact>().eq(Illegalact::getCaseId, tsCase.getCaseId()));
                if(CollectionUtils.isNotEmpty(illegalactList)){
                    Illegalact illegalactFirst = illegalactList.get(0);
                    map.put("illegactTypeL",illegalactFirst.getIllegactTypeL());
                    map.put("illegactTypeM",illegalactFirst.getIllegactTypeM());
                    map.put("illegactTypeS",illegalactFirst.getIllegactTypeS());
                    map.put("illegact",illegalactFirst.getIllegact());
                }
//                map.put("illegalTypeCn",tsCase.getIllegalTypeCn());
                map.put("caseName",tsCase.getCaseName());
                map.put("caseNo",tsCase.getCaseNo());
                map.put("place",tsCase.getPlace());

                Map<String, TRBaseCode> caseFromMap = baseCodeService.getBaseCodeMapFormCache("CE03");

//                map.put("caseFrom", caseFromMap.get(tsCase.getCaseFrom()).getName());
                map.put("registTime",DateUtils.localDateFormat(tsCase.getRegistTime().toLocalDate(),"yyyy年MM月dd日"));
                // 立案或不予立案 标题
                String title = tsCase.getIsRegister().equals("1")? "立案审批表": "不予立案审批表";
                map.put("title",title);

                try {
                    ClassPathResource classPathResource = new ClassPathResource("static/template/caseApproval.docx");
                    String resource = classPathResource.getURL().getPath();

                    String realPath = CommonConfig.getUploadPath();
                    realPath += File.separator + bizseq;
                    File dir = new File(realPath);
                    dir.mkdirs();
                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + title + ".docx");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                String ext = ".docx";
                String fileName = title + ext;
                String tempPath = bizseq + File.separator + fileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(StringUtils.EMPTY);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public void createInvestigateApprovalDocx(String bizseq,String workflowId) {
        if(StringUtils.isNotBlank(bizseq) && StringUtils.isNotBlank(workflowId)) {
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq,bizseq);
            TsCase tsCase = getOne(wrapper);
            // 案件信息
            if(tsCase != null){
                Map<String, Object> map = new HashMap<>();

                map.put("caseName",tsCase.getCaseName());
                map.put("caseNo",tsCase.getCaseNo());
                map.put("place",tsCase.getPlace());
                Map<String, TRBaseCode> caseFromMap = baseCodeService.getBaseCodeMapFormCache("CE03");
//                map.put("caseFrom", caseFromMap.get(tsCase.getCaseFrom()).getName());
                map.put("registTime", DateUtils.localDateFormat(tsCase.getRegistTime().toLocalDate(),"yyyy年MM月dd日"));

                // 标题
                String title = "调查审批表";
                map.put("title",title);

                //获取按时间降序，调查意见标识4 5 6排序好的意见列表
                List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                        .eq(TSOpinion::getWorkflowid, workflowId)
                        .eq(TSOpinion::getIsagree,"1")
                        .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
                boolean flag0 = false;
                boolean flag1 = false;
                boolean flag2 = false;
                for (TSOpinion item : list) {
                    if ("4".equals(item.getOpiniontype()) && !flag0) {
                        map.put("enterOpinion",item.getOpinioncontent());
                        flag0 = true;
                    }
                    if ("5".equals(item.getOpiniontype()) && !flag1) {
                        map.put("handleOpinion",item.getOpinioncontent());
                        flag1 = true;
                    }
                    if ("6".equals(item.getOpiniontype()) && !flag2) {
                        map.put("approvalOpinion",item.getOpinioncontent());
                        flag2 = true;
                    }
                }

                try {
                    ClassPathResource classPathResource = new ClassPathResource("static/template/investigateAppr.docx");
                    String resource = classPathResource.getURL().getPath();

                    String realPath = CommonConfig.getUploadPath();
                    realPath += File.separator + bizseq;
                    File dir = new File(realPath);
                    dir.mkdirs();
                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + title + ".docx");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                String ext = ".docx";
                String fileName = title + ext;
                String tempPath = bizseq + File.separator + fileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(StringUtils.EMPTY);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public TsCase getByBizseq(String bizseq) {
        LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TsCase::getBizseq,bizseq);
        return getOne(wrapper);
    }

    @Override
    public String updateCaseName(String bizseq) {
//        LambdaQueryWrapper<Tsbizrevlist> wrapper = new LambdaQueryWrapper<>();
////        wrapper.eq(Tsbizrevlist::getBizseq,bizseq)
////                .eq(Tsbizrevlist::getIsRemove,"0")
////                .orderByDesc(Tsbizrevlist::getInsertTime);
////        Page<Tsbizrevlist> page = tsbizrevlistService.page(new Page<>(1, 1), wrapper);
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("bizseq",bizseq);
        IPage<Tsbizrevlist> page = tsbizrevlistService.getRevEntPage(new Page<>(1, 1), paramMap);
        if(CollectionUtils.isNotEmpty(page.getRecords())) {
            String casename = null;
            TsCase aCase = getByBizseq(bizseq);
            casename = "关于" + page.getRecords().get(0).getEntname() + "等" +
                    page.getTotal() + "家" + ("2".equals(aCase.getBizEntType()) ? "个人独资企业" : "公司") + "的批量吊销";
            aCase.setCaseName(casename);
            boolean update = updateById(aCase);
            if (update) {
                return casename;
            }
        }
        return null;
    }
}
