package com.jeeplus.test.projectRecords.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.jeeplus.sys.utils.StringUtils;
import com.jeeplus.security.util.SecurityUtils;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.projectRecords.domain.Project;
import com.jeeplus.test.projectRecords.mapper.ProjectMapper;
import com.jeeplus.test.projectRecords.service.dto.FileUploadListDTO;
import com.jeeplus.test.projectRecords.service.dto.ProjectDTO;
import com.mchange.lang.IntegerUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Transactional
public class ProjectService extends ServiceImpl<ProjectMapper, Project> {

    @Autowired
    private ProjectMapper projectMapper;

    public IPage<Project> selectPage(Page<Project> page, QueryWrapper queryWrapper){
        queryWrapper.eq ("pr.del_flag", 0 ); // 排除已经删除
        return projectMapper.findList(page, queryWrapper);
    }

    /**
     * 通过项目id查询项目信息
     * @param projectId
     * @return
     */
    public Project selectByProjectId(String projectId){
        Project project = projectMapper.selectByProjectId(projectId);

        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        Boolean bmzrRoleFlag = false;
        if(null != currentUserDTO.getRoleDTOList() && currentUserDTO.getRoleDTOList().size()>0){
            for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
                if("bmzr".equals(roleDTO.getEnName())){
                    bmzrRoleFlag = true;
                    break;
                }
            }
        }
        if(project.getProjectHead().equals(currentUserDTO.getId()) || bmzrRoleFlag){
            project.setPermissionFlag(true);
        }else{
            project.setPermissionFlag(false);
        }
        return project;
    }

    /**
     * 用于将ProjectDTO类中的DateUi属性转换为时间格式存储到Project类中的Date属性中
     * @param project
     * @param projectDTO
     * @return
     */
    public Project projectDtoToDate(Project project, ProjectDTO projectDTO){
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        try {
            if(StringUtils.isNotBlank(projectDTO.getEvaluationBaseDateUi())){
                project.setEvaluationBaseDate(sdf.parse(projectDTO.getEvaluationBaseDateUi()));
            }

            if(StringUtils.isNotBlank(projectDTO.getEvaluationReportDateUi())){
                project.setEvaluationReportDate(sdf.parse(projectDTO.getEvaluationReportDateUi()));
            }

            if(StringUtils.isNotBlank(projectDTO.getInvoiceDateUi())){
                project.setInvoiceDate(sdf.parse(projectDTO.getInvoiceDateUi()));
            }

            if(StringUtils.isNotBlank(projectDTO.getReimbursementDateUi())){
                project.setReimbursementDate(sdf.parse(projectDTO.getReimbursementDateUi()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return project;
    }

    /**
     * mp的update()方法，如果将参数设为null的，mp会默认不修改的
     * 所以通过这种方式，使用wrapper将你要设置为null的手动set为null，这样update()方法就会按你的想法执行了
     * @param project
     * @return
     */
    public LambdaUpdateWrapper getLambdaUpdateWrapper(ProjectDTO project){
        LambdaUpdateWrapper<Project> wrapper = new LambdaUpdateWrapper<Project>();

        if(StringUtils.isNotBlank(project.getId())){
            wrapper.eq(Project::getId,project.getId());
        }

        if(StrUtil.isEmpty(project.getEvaluationBaseDateUi())){
            wrapper.set(Project::getEvaluationBaseDate, null);
        }

        if(StrUtil.isEmpty(project.getEvaluationReportDateUi())){
            wrapper.set(Project::getEvaluationReportDate, null);
        }

        if(StrUtil.isEmpty(project.getInvoiceDateUi())){
            wrapper.set(Project::getInvoiceDate, null);
        }

        if(StrUtil.isEmpty(project.getReimbursementDateUi())){
            wrapper.set(Project::getReimbursementDate, null);
        }

        return wrapper;
    }

    /**
     * 根据文号查询项目信息
     * @param projectDTO
     * @return
     */
    public Project selectByDocumentNum(ProjectDTO projectDTO){
        return projectMapper.selectByDocumentNum(projectDTO);
    }

    /**
     * 项目文件上传完成比例
     * @param queryWrapper
     * @return
     */
    public String proportion(QueryWrapper queryWrapper) {
        // 排除已经删除
        queryWrapper.eq ("pr.del_flag", 0 );
        int all = projectMapper.proportion(queryWrapper);
        if (all == 0) {
            return "0.00%";
        }
        queryWrapper.eq("pr.file_upload_type", "1");
        int on = projectMapper.proportion(queryWrapper);
        DecimalFormat df = new DecimalFormat("0.00");
        String s = df.format((float)on*100/(float)all) + "%";
        return s;
    }

    public List<FileUploadListDTO> exportFileUploadList(ProjectDTO projectDTO) {
        //queryWrapper.eq("su.del_flag", 0);
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        projectDTO.setOfficeDTO(currentUserDTO.getOfficeDTO());
        List<FileUploadListDTO> allList = projectMapper.projectAllList(projectDTO);
        //queryWrapper.eq("pr.file_upload_type", "1");
        List<FileUploadListDTO> list = projectMapper.projectList(projectDTO);
        if (CollectionUtil.isNotEmpty(allList)) {
            DecimalFormat df = new DecimalFormat("0.00");
            for (FileUploadListDTO dto : allList) {
                if(null != list && list.size()>0){
                    for (FileUploadListDTO i : list) {
                        if (dto.getName().equals(i.getName())) {
                            dto.setNum(i.getNum());
                            String s = df.format((float) i.getNum() * 100 / (float) dto.getAllNum());
                            dto.setProportion(s+"%");
                        }
                    }
                }
            }
            allList.stream().forEach(i -> {
                //如果没有找到或没有完成数量，则填入默认完成数量0，完成比例0
                if (StringUtils.isBlank(i.getProportion())) {
                    i.setProportion("0.00%");
                }
                if (null == i.getNum()) {
                    i.setNum(0);
                }
            });
        }
        return allList;
    }
}
