package com.jeeplus.centrecareful.reportArchieve.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.centrecareful.reportArchieve.domain.ZsReportArchieve;
import com.jeeplus.centrecareful.reportArchieve.mapper.ZsReportArchieveMapper;
import com.jeeplus.centrecareful.reportArchieve.service.dto.ZsReportArchieveExport;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;

import com.jeeplus.sys.feign.*;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional
public class ZsReportArchieveService {

    @Resource
    private ZsReportArchieveMapper reportArchieveMapper;

    /**
     * 列表查询
     * @param page
     * @param zsReportArchieve
     * @return
     */
    public IPage<ZsReportArchieve> list(Page<ZsReportArchieve> page, ZsReportArchieve zsReportArchieve) throws Exception {
        QueryWrapper<ZsReportArchieve> queryWrapper = QueryWrapperGenerator.buildQueryCondition(zsReportArchieve, ZsReportArchieve.class);
        queryWrapper.eq("a.del_flag", 0);
        //流水号
        if (StringUtils.isNotBlank(zsReportArchieve.getArchieveNo())){
            queryWrapper.like("a.archieve_no",zsReportArchieve.getArchieveNo());
        }
        //部门
        if (StringUtils.isNotBlank(zsReportArchieve.getOfficeName())){
            queryWrapper.like("a.office_name",zsReportArchieve.getOfficeName());
        }
        //业务类型
        if (StringUtils.isNotBlank(zsReportArchieve.getBusinessType())){
            queryWrapper.eq("a.business_type",zsReportArchieve.getBusinessType());
        }
        //项目名称
        if (StringUtils.isNotBlank(zsReportArchieve.getProject())){
            queryWrapper.like("a.project",zsReportArchieve.getProject());
        }
        //报告文号
        if (StringUtils.isNotBlank(zsReportArchieve.getReportNo())){
            queryWrapper.like("a.report_no",zsReportArchieve.getReportNo());
        }
        //报告日期
        if (zsReportArchieve.getReportDates() != null){
            queryWrapper.between("a.report_date",zsReportArchieve.getReportDates()[0],zsReportArchieve.getReportDates()[1]);
        }
        //盖章日期
        if (zsReportArchieve.getStampDates() != null){
            queryWrapper.between("a.stamp_date",zsReportArchieve.getStampDates()[0],zsReportArchieve.getStampDates()[1]);
        }
        //归档日期
        if (zsReportArchieve.getArchieveDates() != null){
            queryWrapper.between("a.archieve_date",zsReportArchieve.getArchieveDates()[0],zsReportArchieve.getArchieveDates()[1]);
        }
        //盒号
        if (StringUtils.isNotBlank(zsReportArchieve.getFileBoxNumber())){
            queryWrapper.like("a.file_box_number",zsReportArchieve.getFileBoxNumber());
        }
        //合同原件
        if (StringUtils.isNotBlank(zsReportArchieve.getOriginalContract())){
            queryWrapper.like("a.original_contract",zsReportArchieve.getOriginalContract());
        }
        //归档接收人
        if (StringUtils.isNotBlank(zsReportArchieve.getArchieveResever())){
            queryWrapper.apply("(a.archieve_resever",zsReportArchieve.getArchieveResever()).or().like("su.name",zsReportArchieve.getArchieveResever());
        }
        //存放地点
        if (StringUtils.isNotBlank(zsReportArchieve.getStoragePlace())){
            queryWrapper.like("a.storage_place",zsReportArchieve.getStoragePlace());
        }
        //状态
        if (StringUtils.isNotBlank(zsReportArchieve.getStatus())){
            queryWrapper.eq("a.status",zsReportArchieve.getStatus());
        }
        IPage<ZsReportArchieve> list = reportArchieveMapper.findList(page,queryWrapper);
        for (ZsReportArchieve record : list.getRecords()) {
            if (StringUtils.isNotBlank(record.getStoragePlace())){
                if (record.getStoragePlace().contains(",")){
                    String[] split = record.getStoragePlace().split(",");
                    StringBuilder vaBuilder = new StringBuilder();
                    for (String s : split) {
                        String placeValue = SpringUtil.getBean(IDictApi.class).getDictLabel(s, "storage_place", "");
                        if (StringUtils.isNotBlank(placeValue)) {
                            if (vaBuilder.length() > 0) {
                                vaBuilder.append(",");  // 用逗号分隔每个拼接的值
                            }
                            vaBuilder.append(placeValue);  // 拼接 value
                        }
                    }
                    record.setStoragePlace(vaBuilder.toString());
                }else {
                    String placeValue = SpringUtil.getBean(IDictApi.class).getDictLabel(record.getStoragePlace(), "storage_place", "");
                    record.setStoragePlace(placeValue);
                }
                if (StringUtils.isNotBlank(record.getSpecialPlace())){
                    record.setStoragePlace(record.getSpecialPlace());
                }

            }
        }

        return list;
    }

    public IPage<ZsReportArchieveExport> exportList(Page<ZsReportArchieveExport> page, ZsReportArchieveExport zsReportArchieveExport) throws Exception {
        QueryWrapper<ZsReportArchieveExport> queryWrapper = QueryWrapperGenerator.buildQueryCondition(zsReportArchieveExport, ZsReportArchieveExport.class);
        queryWrapper.eq("a.del_flag", 0);
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (ObjectUtil.isNotEmpty(userDTO)){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                if (ObjectUtils.isNotEmpty(roleDTO)){
                    RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                    if ("zsbggdgly".equals(dtoById.getEnName())){
                        queryWrapper.eq("a.office_name","业务三部");
                    }
                }
            }
        }
        //流水号
        if (StringUtils.isNotBlank(zsReportArchieveExport.getArchieveNo())){
            queryWrapper.like("a.archieve_no",zsReportArchieveExport.getArchieveNo());
        }
        //业务类型
        if (StringUtils.isNotBlank(zsReportArchieveExport.getBusinessType())){
            queryWrapper.eq("a.business_type",zsReportArchieveExport.getBusinessType());
        }
        //项目名称
        if (StringUtils.isNotBlank(zsReportArchieveExport.getProject())){
            queryWrapper.like("a.project",zsReportArchieveExport.getProject());
        }
        //报告文号
        if (StringUtils.isNotBlank(zsReportArchieveExport.getReportNo())){
            queryWrapper.like("a.report_no",zsReportArchieveExport.getReportNo());
        }
        //报告日期
        if (zsReportArchieveExport.getReportDates() != null){
            queryWrapper.between("a.report_date",zsReportArchieveExport.getReportDates()[0],zsReportArchieveExport.getReportDates()[1]);
        }
        //盖章日期
        if (zsReportArchieveExport.getStampDates() != null){
            queryWrapper.between("a.stamp_date",zsReportArchieveExport.getStampDates()[0],zsReportArchieveExport.getStampDates()[1]);
        }
        //归档日期
        if (zsReportArchieveExport.getArchieveDates() != null){
            queryWrapper.between("a.archieve_date",zsReportArchieveExport.getArchieveDates()[0],zsReportArchieveExport.getArchieveDates()[1]);
        }
        //盒号
        if (StringUtils.isNotBlank(zsReportArchieveExport.getFileBoxNumber())){
            queryWrapper.like("a.file_box_number",zsReportArchieveExport.getFileBoxNumber());
        }
        //合同原件
        if (StringUtils.isNotBlank(zsReportArchieveExport.getOriginalContract())){
            queryWrapper.like("a.original_contract",zsReportArchieveExport.getOriginalContract());
        }
        //归档接收人
        if (StringUtils.isNotBlank(zsReportArchieveExport.getArchieveResever())){
            queryWrapper.apply("(a.archieve_resever",zsReportArchieveExport.getArchieveResever()).or().like("su.name",zsReportArchieveExport.getArchieveResever());
        }
        //存放地点
        if (StringUtils.isNotBlank(zsReportArchieveExport.getStoragePlace())){
            queryWrapper.eq("a.storage_place",zsReportArchieveExport.getStoragePlace());
        }
        //状态
        if (StringUtils.isNotBlank(zsReportArchieveExport.getStatus())){
            queryWrapper.eq("a.status",zsReportArchieveExport.getStatus());
        }
        IPage<ZsReportArchieveExport> list = reportArchieveMapper.exportList(page,queryWrapper);

        for (ZsReportArchieveExport record : list.getRecords()) {
            if (StringUtils.isNotBlank(record.getStoragePlace())){
                if (record.getStoragePlace().contains(",")){
                    String[] split = record.getStoragePlace().split(",");
                    StringBuilder vaBuilder = new StringBuilder();
                    for (String s : split) {
                        String placeValue = SpringUtil.getBean(IDictApi.class).getDictLabel(s, "storage_place", "");
                        if (StringUtils.isNotBlank(placeValue)) {
                            if (vaBuilder.length() > 0) {
                                vaBuilder.append(",");  // 用逗号分隔每个拼接的值
                            }
                            vaBuilder.append(placeValue);  // 拼接 label
                        }
                    }
                    record.setStoragePlace(vaBuilder.toString());
                }else {
                    String placeValue = SpringUtil.getBean(IDictApi.class).getDictLabel(record.getStoragePlace(), "storage_place", "");
                    record.setStoragePlace(placeValue);
                }

            }
        }

        return list;

    }

    /**
     * 获取部门列表
     * @return
     */
    public List<ZsReportArchieve> getOfficeNameList() {
        List<ZsReportArchieve> list = reportArchieveMapper.getOfficeNameList();
        return list;
    }

    /**
     * 导入数据
     * @param list
     * @param arrayList
     * @return
     */
    public String importDecide(List<ZsReportArchieveExport> list, ArrayList<ZsReportArchieveExport> arrayList) throws Exception {
        for (ZsReportArchieveExport reportArchieveDTO : list) {
            reportArchieveDTO.setReportNo(reportArchieveDTO.getReportNo().replace(" ", ""));
            reportArchieveDTO.setReportNo(reportArchieveDTO.getReportNo().replace("（", "("));
            reportArchieveDTO.setReportNo(reportArchieveDTO.getReportNo().replace("）", ")"));
            if(ObjectUtil.isEmpty(reportArchieveDTO)){
                continue;
            }
            if(StringUtils.isNotBlank(reportArchieveDTO.getReportNo())){

                List<ZsReportArchieve> financeInvoiceDetailList = reportArchieveMapper.selectList(new QueryWrapper<ZsReportArchieve>().eq("report_no", reportArchieveDTO.getReportNo()));
                if(CollectionUtil.isNotEmpty(financeInvoiceDetailList)){
                    return "文件中报告文号--"+reportArchieveDTO.getReportNo()+"已在系统中存在，请重新填写";
                }
            }else {
                return "文件中有报告文号为空，请重新填写";
            }

            arrayList.add(reportArchieveDTO);
        }
        //将数据进行保存
        if (CollectionUtils.isNotEmpty(arrayList)){
            List<ZsReportArchieve> zsReportArchieves = createZsReportArchieve(arrayList);

            if (CollectionUtils.isNotEmpty(zsReportArchieves)){
                // 每次最多插入 100 条数据
                int batchSize = 100;
                int totalSize = zsReportArchieves.size();

                // 按批次处理插入
                for (int i = 0; i < totalSize; i += batchSize) {
                    // 计算当前批次的结束位置
                    int endIndex = Math.min(i + batchSize, totalSize);
                    // 获取当前批次的子列表
                    List<ZsReportArchieve> batchList = zsReportArchieves.subList(i, endIndex);

                    // 执行批量插入
                    reportArchieveMapper.insertBatch(batchList);
                }
            }
        }
        return null;
    }

    public List<ZsReportArchieve> createZsReportArchieve(ArrayList<ZsReportArchieveExport> reportArchieveExport) throws Exception {
        List<ZsReportArchieve> zsReportArchieves = new ArrayList<>();
        String businessTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictValueListMapByDict ("business_type");
        Map<String,Object> businessTypeValueDTOs = JSON.parseObject(businessTypeDatas, new TypeReference<Map<String,Object>>() {});

        String storagePlaceDatas = SpringUtil.getBean ( IDictApi.class ).getDictValueListMapByDict ("storage_place");
        Map<String,Object> storagePlaceValueDTOs = JSON.parseObject(storagePlaceDatas, new TypeReference<Map<String,Object>>() {});

        String reportNoTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictValueListMapByDict ("report_no_type");
        Map<String,Object> reportNoTypeDTOs = JSON.parseObject(reportNoTypeDatas, new TypeReference<Map<String,Object>>() {});


        for (ZsReportArchieveExport reportArchieveDTO : reportArchieveExport) {
            ZsReportArchieve zsReportArchieve = new ZsReportArchieve();
            BeanUtils.copyProperties(reportArchieveDTO,zsReportArchieve);
            //业务类型
            if (StringUtils.isNotBlank(reportArchieveDTO.getBusinessType())){
                for (String key : businessTypeValueDTOs.keySet()) {
                    if(reportArchieveDTO.getBusinessType().equals(key)){
                        zsReportArchieve.setBusinessType(String.valueOf(businessTypeValueDTOs.get(key)));
                        break;
                    }
                }
            }
            //报告文号类型
            try {
                String reportNo = reportArchieveDTO.getReportNo();
                String type = "";
                if(reportNo.contains("字")){
                    type = reportNo.substring(reportNo.indexOf("环")+1, reportNo.indexOf("字")+1);
                }else if(reportNo.contains("水")){
                    type = reportNo.substring(reportNo.indexOf("环")+1, reportNo.indexOf("水")+1);
                }
                if (StringUtils.isNotBlank(type)){
                    for (String key : reportNoTypeDTOs.keySet()) {
                        if(type.equals(key)){
                            zsReportArchieve.setReportNoType(String.valueOf(reportNoTypeDTOs.get(key)));
                            break;
                        }
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }

            //流水号生成
            String currentToken = TokenProvider.getCurrentToken();
            OfficeDTO officeDTO = reportArchieveMapper.getOfficeDTOByName("中审江苏分所");
            String documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(officeDTO.getId(), ZsReportArchieve.BIZ_CODE,currentToken);
            zsReportArchieve.setArchieveNo(documentNo);
            //存放地点
            if(StringUtils.isNotBlank(reportArchieveDTO.getStoragePlace())){
                String place = reportArchieveDTO.getStoragePlace().replace(" ", "");
                if (place.contains("江苏分所") && place.contains("区")){
                    String substring = place.substring(place.lastIndexOf("所") + 1, place.lastIndexOf("区"));
                    String placeValue = "";
                    //可能会存在多个区
                    if (substring.contains("区")){
                        String[] split = substring.split("区");
                        StringBuilder vaBuilder = new StringBuilder();
                        for (String s : split) {
                            String value = "";
                            if (StringUtils.isNotBlank(s)){
                                for (String key : storagePlaceValueDTOs.keySet()) {
                                    if(s.equals(key)){
                                        value = String.valueOf(storagePlaceValueDTOs.get(key));
                                        break;
                                    }
                                }
                            }
                            if (StringUtils.isNotBlank(value)) {
                                if (vaBuilder.length() > 0) {
                                    vaBuilder.append(",");  // 用逗号分隔每个拼接的值
                                }
                                vaBuilder.append(value);  // 拼接 value
                            }
                        }
                        placeValue = vaBuilder.toString();
                    }else {
                        if (StringUtils.isNotBlank(substring)){
                            for (String key : storagePlaceValueDTOs.keySet()) {
                                if(substring.equals(key)){
                                    placeValue = String.valueOf(storagePlaceValueDTOs.get(key));
                                    break;
                                }
                            }
                        }
                    }
                    zsReportArchieve.setStoragePlace(placeValue);
                }else {
                    zsReportArchieve.setSpecialPlace(place);
                    zsReportArchieve.setStoragePlace("");
                }
            }

            //归档接收人
            zsReportArchieve.setArchieveResever("");

            String id = UUID.randomUUID().toString().replace("-", "");
            zsReportArchieve.setId(id);
            zsReportArchieve.setCreateTime(new Date());
            zsReportArchieve.setUpdateTime(new Date());
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            zsReportArchieve.setCreateById(userDTO.getId());
            zsReportArchieve.setUpdateById(userDTO.getId());
            zsReportArchieve.setStatus("0");
            zsReportArchieve.setTenantId(userDTO.getTenantDTO().getId());
            zsReportArchieve.setDelFlag(0);
            zsReportArchieves.add(zsReportArchieve);
        }

//        reportArchieveMapper.insert(zsReportArchieve);
        return zsReportArchieves;
    }


    /**
     * 根据id查询
     * @param id
     * @return
     */
    public ZsReportArchieve findById(String id) {
        ZsReportArchieve zsReportArchieve = reportArchieveMapper.findById(id);
        ArrayList<String> strings = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(zsReportArchieve)){
            if (StringUtils.isNotBlank(zsReportArchieve.getStoragePlace())){
                if (zsReportArchieve.getStoragePlace().contains(",")){
                    String[] split = zsReportArchieve.getStoragePlace().split(",");
                    for (String s : split) {
                        strings.add(s);
                    }
                }else {
                    strings.add(zsReportArchieve.getStoragePlace());
                }
            }
        }
        zsReportArchieve.setStoragePlaces(strings);
        return zsReportArchieve;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public String remove(String id) {
        reportArchieveMapper.deleteById(id);
        return "删除成功";
    }

    /**
     * 根据报告文号类型查询最新的报告文号
     * @param reportNoType
     * @return
     */
    public ZsReportArchieve findByReportNoType(String reportNoType) {
        ZsReportArchieve reportArchieve = reportArchieveMapper.findByReportNoType(reportNoType);

        if (StringUtils.isNotBlank(reportArchieve.getStoragePlace())){
            if (reportArchieve.getStoragePlace().contains(",")){
                String[] split = reportArchieve.getStoragePlace().split(",");
                StringBuilder vaBuilder = new StringBuilder();
                for (String s : split) {
                    String placeValue = SpringUtil.getBean(IDictApi.class).getDictLabel(s, "storage_place", "");
                    if (StringUtils.isNotBlank(placeValue)) {
                        if (vaBuilder.length() > 0) {
                            vaBuilder.append(",");  // 用逗号分隔每个拼接的值
                        }
                        vaBuilder.append(placeValue);  // 拼接 label
                    }
                }
                reportArchieve.setStoragePlace(vaBuilder.toString());
            }else {
                String placeValue = SpringUtil.getBean(IDictApi.class).getDictLabel(reportArchieve.getStoragePlace(), "storage_place", "");
                reportArchieve.setStoragePlace(placeValue);
            }

        }

        if(com.jeeplus.utils.StringUtils.isNotBlank(reportArchieve.getStoragePlace())){
            String replace = reportArchieve.getStoragePlace().replace(",", "区");
            String place = "江苏分所 "+replace+"区";
            reportArchieve.setStoragePlace(place);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(reportArchieve.getSpecialPlace())){
            reportArchieve.setStoragePlace(reportArchieve.getSpecialPlace());
        }
        return reportArchieve;
    }

    /**
     * 根据盒号查询修改人
     * @param fileBoxNumber
     * @param reportNoType
     * @return
     */
    public boolean findByFileBoxNumber(String fileBoxNumber, String reportNoType) {
        if (StringUtils.isNotBlank(fileBoxNumber) && StringUtils.isNotBlank(reportNoType)){
            List<ZsReportArchieve> reportArchieves = reportArchieveMapper.findByFileBoxNumber(fileBoxNumber,reportNoType);
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            if (CollectionUtils.isNotEmpty(reportArchieves)){
                for (ZsReportArchieve reportArchieve : reportArchieves) {
                    if (!reportArchieve.getUpdateById().equals(userDTO.getId())){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 根据报告文号查询最新盒号
     * @param reportNo
     * @return
     */
    public ZsReportArchieve findByReportNo(String reportNo) {
        if (StringUtils.isNotBlank(reportNo)){
            String type = "";
            if(reportNo.contains("字")){
                type = reportNo.substring(reportNo.indexOf("环")+1, reportNo.indexOf("字")+1);
            }else if(reportNo.contains("水")){
                type = reportNo.substring(reportNo.indexOf("环")+1, reportNo.indexOf("水")+1);
            }
            String noType = SpringUtil.getBean(IDictApi.class).getDictValue(type, "report_no_type", "");
            if (StringUtils.isNotBlank(noType)){
                ZsReportArchieve reportArchieve = reportArchieveMapper.findByReportNoType(noType);
                return reportArchieve;
            }
        }
        return null;
    }

    /**
     * 校验报告文号类型与报告文号是否一致
     * @param reportNoType
     * @param reportNo
     * @return
     */
    public boolean checkReportTypeAndReportNo(String reportNoType, String reportNo) {
        String type = "";
        if(reportNo.contains("字")){
            type = reportNo.substring(reportNo.indexOf("环")+1, reportNo.indexOf("字")+1);
        }else if(reportNo.contains("水")){
            type = reportNo.substring(reportNo.indexOf("环")+1, reportNo.indexOf("水")+1);
        }
        String noType = SpringUtil.getBean(IDictApi.class).getDictValue(type, "report_no_type", "");
        if (StringUtils.isNotBlank(noType)){
            if (noType.equals(reportNoType)){
                return true;
            }
        }
        return false;
    }

    /**
     * 修改数据
     * @param reportArchieve
     * @return
     */
    public String saveForm(ZsReportArchieve reportArchieve) {
        ZsReportArchieve zsReportArchieve = new ZsReportArchieve();
        BeanUtils.copyProperties(reportArchieve,zsReportArchieve);
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        zsReportArchieve.setArchieveResever(userDTO.getId());
        zsReportArchieve.setStatus("1");
        //将存放区域转化
        String result = String.join(",", reportArchieve.getStoragePlaces());
        zsReportArchieve.setStoragePlace(result);
        reportArchieveMapper.updateById(zsReportArchieve);
        return "操作成功";
    }


}
