package com.jeeplus.finance.projectReport.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.finance.projectRecords.domain.CwProjectRecords;
import com.jeeplus.finance.projectReport.domain.*;
import com.jeeplus.finance.projectReport.mapper.CwProjectInfoMapper;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportNumberApplyMapper;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportReviewMapper;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.service.dto.ReportNoDto;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-12-12 17:02
 */
@Service
@Transactional
public class CwProjectReportNumberApplyService extends ServiceImpl<CwProjectReportNumberApplyMapper, CwProjectReportNumberApply> {

    @Resource
    private CwProjectReportNumberApplyMapper mapper;

    @Resource
    private CwProjectReportReviewMapper reviewMapper;

    @Resource
    private CwProjectInfoMapper infoMapper;

    @Resource
    private CwProjectReportService cwProjectReportService;

    public CwProjectReportData queryByReportId(String id) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        CwProjectReportData data = mapper.selectByPortId(id);
        //查询复核相关信息

        return data;
    }

    /**
     * 修改状态
     * @param data
     * @return
     */
    public String updateReviewStatysByReportId(CwProjectReportData data) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        mapper.updateReviewStatysByReportId(data.getApplyStatus(),data.getId());

        return "操作成功";
    }

    /**
     * 保存项目以及其他相关信息
     * @param reportData
     * @return
     * @throws Exception
     */
    public String saveForm(CwProjectReportData reportData) throws Exception{
        if (StringUtils.isNotEmpty(reportData.getId())){

            CwProjectReportNumberApply detail = mapper.selectById(reportData.getId());
            if (detail != null){
                reportData.setCreateBy(reportData.getCreateBy());
                return update(reportData,detail);
            } else {
                //传过来的是报告表id
                detail = mapper.selectByReportId(reportData.getId());
                if (detail != null){
                    reportData.setCreateBy(reportData.getCreateBy());
                    return update(reportData,detail);
                }
            }
        }
        return add(reportData);

    }

    /**
     * 报告号修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(CwProjectReportData reportData,CwProjectReportNumberApply detail) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        CwProjectReportNumberApply review = new CwProjectReportNumberApply();
        BeanUtils.copyProperties(reportData, review);
        review.setCreateById(detail.getCreateById());
        review.setCreateTime(detail.getCreateTime());
        review.setUpdateById(userDTO.getId());
        review.setUpdateTime(new Date());
        review.setId(detail.getId());
        String currentToken = TokenProvider.getCurrentToken();


        if (reportData.getReviewStatus().equals("5")){
            //设置报告文号、报告流水号
            CwProjectInfoData infoData = new CwProjectInfoData();
            //报告文号生成
            String documentNo = "";
            if(StringUtils.isNotBlank(reportData.getReportNo())){
                infoData.setReportNo(reportData.getReportNo());
            }else{
                if(StringUtils.isNotBlank(reportData.getReportType())) {
                    ReportNoDto projectReportByNumber = new ReportNoDto();
                    switch (reportData.getReportType()) {
                        case "1":   //基字
                            do{
                                documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.BIZ_CODE,currentToken);
                                //根据报告号查询诗剧苦中是否存在
                                projectReportByNumber = reviewMapper.getProjectReportByNumber(documentNo);
                            }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                            break;
                        case "2":   //咨字
                            do{
                                documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CONSULT_BIZ_CODE,currentToken);
                                //根据报告号查询诗剧苦中是否存在
                                projectReportByNumber = reviewMapper.getProjectReportByNumber(documentNo);
                            }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                            break;
                        case "3":   //审字
                            do{
                                documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.EXAMINE_BIZ_CODE,currentToken);
                                //根据报告号查询诗剧苦中是否存在
                                projectReportByNumber = reviewMapper.getProjectReportByNumber(documentNo);
                            }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                            break;
                        case "4":   //验字
                            do{
                                documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CHECK_BIZ_CODE,currentToken);
                                //根据报告号查询诗剧苦中是否存在
                                projectReportByNumber = reviewMapper.getProjectReportByNumber(documentNo);
                            }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                            break;
                        case "5":   //特字
                            do{
                                documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.SPECIAL_BIZ_CODE,currentToken);
                                //根据报告号查询诗剧苦中是否存在
                                projectReportByNumber = reviewMapper.getProjectReportByNumber(documentNo);
                            }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                            break;
                    }
                }

                if(StringUtils.isNotBlank(reportData.getReportNumber())){
                    infoData.setReportNumber(reportData.getReportNumber());
                }else {
                    //报告流水号生成  根据项目编号去new_line表查询
                    String reportNumber = infoMapper.selectReportNumberByProjectNo(reportData.getProjectNumber());
                    if (null != reportNumber) {
                        int stress = 0;
                        stress = reportNumber.indexOf("-");//分隔符位置
                        String substring = reportNumber.substring(stress + 1, reportNumber.length());
                        int integer = Integer.parseInt(substring);

                        String newReportNumber = "";
                        if (integer < 10) {
                            if (integer == 9) {
                                newReportNumber = reportData.getProjectNumber() + "-010";
                            } else {
                                newReportNumber = reportData.getProjectNumber() + "-00" + (integer + 1);
                            }
                        } else {
                            if (integer < 100) {
                                if (integer == 99) {
                                    newReportNumber = reportData.getProjectNumber() + "-100";
                                } else {
                                    newReportNumber = reportData.getProjectNumber() + "-0" + (integer + 1);
                                }
                            } else {
                                newReportNumber = reportData.getProjectNumber() + "-" + (integer + 1);
                            }
                        }

                        infoData.setReportNumber(newReportNumber);
                    } else {
                        infoData.setReportNumber(reportData.getProjectNumber() + "-001");
                    }
                }
                infoData.setReportId(detail.getReportId());
                infoData.setReportNo(documentNo);
                // 如果数据已经生成报告文号，则不重复生成
                CwProjectInfoData byReportId = infoMapper.getByReportId(detail.getReportId());
                if(ObjectUtil.isNotEmpty(byReportId)) {
                    if (StringUtils.isNotBlank(byReportId.getReportNo())) {
                        infoData.setReportNo(byReportId.getReportNo());
                    }
                }
                infoMapper.updateByReportId(detail.getReportId(),infoData.getReportNumber(),infoData.getReportNo());
            }

            if (ObjectUtil.isNotEmpty(reportData)) {
                if (ObjectUtil.isNotEmpty(reportData.getReportDate())) {
                    CwProjectInfoData line = new CwProjectInfoData();
                    line.setReportDate(reportData.getReportDate());
                    line.setReportId(reportData.getId());
                    infoMapper.update(line, new QueryWrapper<CwProjectInfoData>().lambda().eq(CwProjectInfoData::getReportId,reportData.getId()));
                }
                CwProjectReport report = new CwProjectReport();
                if (StringUtils.isNotBlank(reportData.getRegisterAddress())){
                    report.setRegisterAddress(reportData.getRegisterAddress());
                }
                if (StringUtils.isNotBlank(reportData.getBusinessLocation())){
                    report.setBusinessLocation(reportData.getBusinessLocation());
                }
                if (StringUtils.isNotBlank(reportData.getSecurityBusiness())){
                    report.setSecurityBusiness(reportData.getSecurityBusiness());
                }
                if (StringUtils.isNotBlank(reportData.getIndustry())){
                    report.setIndustry(reportData.getIndustry());
                }
                if (StringUtils.isNotBlank(reportData.getBusinessObjects())){
                    report.setBusinessObjects(reportData.getBusinessObjects());
                }
                if (ObjectUtil.isNotEmpty(report)) {
                    cwProjectReportService.updateCwProjectReportDataById(report);
                }
            }
        }
        mapper.updateReviewById(review);
        //对复核数据进行持久化操作
        //保存复核信息  只保存一个下一节点审核人信息
        CwProjectReview cwProjectReview = reviewMapper.selectByReportId(reportData.getId());
        cwProjectReview.setReviewBy(reportData.getReviewBy());
        reviewMapper.updateReviewById(cwProjectReview);
        return review.getId();
    }

    public String add(CwProjectReportData dto) throws Exception{

        //生成主键id值
        String id = UUID.randomUUID().toString().replace("-", "");
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        //保存基本信息
        CwProjectReportNumberApply info = new CwProjectReportNumberApply();
        BeanUtils.copyProperties(dto, info);

        info.setId(id);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setReportId(dto.getId());
        mapper.insert(info);
        //保存复核信息  只保存一个下一节点审核人信息
        CwProjectReview cwProjectReview = reviewMapper.selectByReportId(dto.getId());
        cwProjectReview.setReviewBy(dto.getReviewBy());
        reviewMapper.updateReviewById(cwProjectReview);

        return info.getId();
    }
}
