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.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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@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.eq("a.storage_place",zsReportArchieve.getStoragePlace());
        }
        //状态
        if (StringUtils.isNotBlank(zsReportArchieve.getStatus())){
            queryWrapper.eq("a.status",zsReportArchieve.getStatus());
        }
        IPage<ZsReportArchieve> list = reportArchieveMapper.findList(page,queryWrapper);


        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);


        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) {
            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)){
            for (ZsReportArchieveExport reportArchieveDTO : arrayList) {
                add(reportArchieveDTO);
            }
        }
        return null;
    }

    public void add(ZsReportArchieveExport reportArchieveDTO) throws Exception {
        ZsReportArchieve zsReportArchieve = new ZsReportArchieve();
        BeanUtils.copyProperties(reportArchieveDTO,zsReportArchieve);
        //业务类型
        if (StringUtils.isNotBlank(reportArchieveDTO.getBusinessType())){
            String dictValue = SpringUtil.getBean(IDictApi.class).getDictValue(reportArchieveDTO.getBusinessType(), "business_type", "");
            if (StringUtils.isNotBlank(dictValue)){
                zsReportArchieve.setBusinessType(dictValue);
            }
        }
        //报告文号类型
        String reportNo = reportArchieveDTO.getReportNo();
        String type = reportNo.substring(2, reportNo.lastIndexOf("("));
        String noType = SpringUtil.getBean(IDictApi.class).getDictValue(type, "report_no_type", "");
        if (StringUtils.isNotBlank(noType)){
            zsReportArchieve.setReportNoType(noType);
        }
        //流水号生成
        String currentToken = TokenProvider.getCurrentToken();
        OfficeDTO officeDTO = reportArchieveMapper.getOfficeDTOByName("中审江苏分所");
        String documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(officeDTO.getId(), ZsReportArchieve.BIZ_CODE,currentToken);
        zsReportArchieve.setArchieveNo(documentNo);
        //存放地点
        String place = reportArchieveDTO.getStoragePlace().replace(" ", "");
        String substring = place.substring(place.lastIndexOf("所") + 1, place.lastIndexOf("区"));
        String placeValue = SpringUtil.getBean(IDictApi.class).getDictValue(substring, "storage_place", "");
        zsReportArchieve.setStoragePlace(placeValue);
        //归档接收人
        zsReportArchieve.setArchieveResever("");

        String id = UUID.randomUUID().toString().replace("-", "");
        zsReportArchieve.setId(id);

        reportArchieveMapper.insert(zsReportArchieve);


    }


    /**
     * 根据id查询
     * @param id
     * @return
     */
    public ZsReportArchieve findById(String id) {
        ZsReportArchieve zsReportArchieve = reportArchieveMapper.findById(id);
        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);
        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 = reportNo.substring(2, reportNo.lastIndexOf("("));
            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 = reportNo.substring(2, reportNo.lastIndexOf("("));
        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");
        reportArchieveMapper.updateById(zsReportArchieve);
        return "操作成功";
    }


}
