package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProjectResourceEnum;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProjectMaterialDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.WelderEquipmentDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.ugp.api.mapper.EquipmentMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.MaterialMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectResourceMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IProjectResourceService;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProjectResourceDto;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import org.aspectj.weaver.ast.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.*;

import static com.yeejoin.amos.boot.module.ugp.api.Enum.ProjectResourceEnum.*;

/**
 * 项目资源表（包括焊工、管材、设备）服务实现类
 *
 * @author system_generator
 * @date 2022-09-22
 */
@Service
public class ProjectResourceServiceImpl extends BaseService<ProjectResourceDto,ProjectResource,ProjectResourceMapper> implements IProjectResourceService {

    @Autowired
    ProjectResourceMapper projectResourceMapper;

    @Autowired
    EquipmentMapper equipmentMapper;

    @Autowired
    OrgServiceImpl orgService;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleService;

    @Autowired
    MaterialServiceImpl materialService;

    @Autowired
    MaterialMapper materialMapper;
    @Autowired
    EquipmentServiceImpl equipmentService;

    /**
     * 分页查询
     */
    public Page<ProjectResourceDto> queryForProjectResourcePage(Page<ProjectResourceDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<ProjectResourceDto> queryForProjectResourceList() {
        return this.queryForList("", false);
    }

    @Override
    public Page<WelderEquipmentDto> installNoticeMsgList(Page<WelderEquipmentDto> page, String name, String type) {
        return this.projectResourceMapper.WelderEquipment(page, name, type);
    }

    @Override
    public WelderEquipmentDto selectByName(Long sequenceNbr) {
        return this.projectResourceMapper.customSelectById(sequenceNbr);
    }

    @Override
    public Page<WelderEquipmentDto> selectByInfo(Page<WelderEquipmentDto> page, Test info, String unit) {
        return null;
    }

    @Override
    public WelderEquipmentDto customSelectById(Long sequenceNbr) {
        return null;
    }

    /**
     * 项目设备新增
     */
    @Transactional()
    public void welderSave(WelderEquipmentDto welderEquipmentDto) {
        // 保存设备
        Equipment equipment = new Equipment();
        BeanUtils.copyProperties(welderEquipmentDto, equipment);
        equipmentMapper.insert(equipment);

        // 处理附件
        MultipartFile[] files = welderEquipmentDto.getFiles();

        // 保存项目与设备对应关系
        ProjectResource projectResource = new ProjectResource();
        projectResource.setProjectId(welderEquipmentDto.getProjectId());
        projectResource.setName(equipment.getName());
        projectResource.setType("equipment");
        projectResource.setResourceId(equipment.getSequenceNbr());
        projectResourceMapper.insert(projectResource);
    }

//    /**
//     * 项目设备删除
//     * @param ids
//     */
//    @Transactional
//    public void welderDelete(String ids) {
//        this.list(new QueryWrapper<ProjectResource>().lambda().in(
//                ProjectResource::getSequenceNbr,
//                Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList()))
//        ).forEach(item -> {
//          this.equipmentMapper.deleteById(item.getResourceId());
//          this.projectResourceMapper.deleteById(item.getSequenceNbr());
//        });
//    }

    /**
     * 绑定项目所用到的设备管材
     */
    public ProjectResource saveIds(JSONObject jsonObject) throws Exception {
        JSONArray subForm = jsonObject.getJSONArray("subForm");
        ProjectResource Resource = new ProjectResource();

        for (Object json2 : subForm) {
            ProjectResource projectResource = new ProjectResource();

            String select = JSON.parseObject(JSON.toJSONString(json2)).getString("select");

            Long SequenceNbr = Long.valueOf(jsonObject.getString("sequenceNbr"));
            String type = jsonObject.getString("type");
            LambdaQueryWrapper<ProjectResource> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProjectResource::getResourceId,select);
            wrapper.eq(ProjectResource::getProjectId,SequenceNbr);
            ProjectResource projectResourceVerify = projectResourceMapper.selectOne(wrapper);
            if (ValidationUtil.isEmpty(projectResourceVerify)){
            //判断资源类型并插入
            if (type.equals(设备资源.getName())) {
                projectResource.setType(设备资源.getCode());
                Equipment equipment = equipmentMapper.selectById(select);
                projectResource.setName(equipment.getName());
            }
            if (type.equals(焊工资源.getName())) {
                projectResource.setType(焊工资源.getCode());
                OrgUsr orgUsrById = orgService.getOrgUsrById(select);
                projectResource.setName(orgUsrById.getBizOrgName());
            }
            if (type.equals(管材资源.getName())) {
                projectResource.setType(管材资源.getCode());
                Material material = materialMapper.selectById(select);
                projectResource.setName(material.getName());
            }

            projectResource.setProjectId(SequenceNbr);
            projectResource.setResourceId(Long.valueOf(select));
            BeanUtils.copyProperties(projectResource,Resource);
            this.save(projectResource);
                }else {
               throw new Exception("该资源已存在");
            }
        }
        return Resource;
    }


    /**
     * 根据项目id获取项目使用到的设备
     * @param projectId
     * @return
     */
    public List<ProjectResource> getProjectEquipment(String projectId){

        return getProjectResources(projectId, 设备资源);
    }

    /**
     * 根据项目ID获取项目使用到的管材
     * @param projectId
     * @return
     */
    public List<ProjectResource> getProjectMaterial(String projectId){
        return getProjectResources(projectId, 管材资源);
    }

    /**
     * 根据项目id获取项目公共接口
     * @param projectId
     * @param 资源
     * @return
     */
    private final String 是否删除="0";
    private List<ProjectResource> getProjectResources(String projectId, ProjectResourceEnum 资源) {
        LambdaQueryWrapper<ProjectResource> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(ProjectResource::getProjectId,projectId);
        wrapper.eq(ProjectResource::getType, 资源.getCode());
        wrapper.eq(BaseEntity::getIsDelete,是否删除);
        List<ProjectResource> projectResources = projectResourceMapper.selectList(wrapper);
        return projectResources;
    }


    /**
     * 获取当前登录人所在单位下的所有项目列表
     * @return
     */
    @BusinessIdentify
   public List<Project> getProjectList(){
        ReginParams reginParams = orgService.getReginParams();
        ReginParams.BusinessInfo businessInfo = reginParams.getBusinessInfo();
        String companyId = String.valueOf(businessInfo.getCompanySequenceNbr());
        String roleName = reginParams.getRole().getRoleName();
        LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
        List<Project> projectList = new ArrayList<>();
        Set<String> codes = new HashSet<>();
        if(OrgEnum.监察部门.getName().equals(roleName)){
            wrapper.eq(SuperviseRule::getSuperviseDeptId,companyId);
            List<SuperviseRule> superviseRuleList = superviseRuleService.list(wrapper);
            for (SuperviseRule superviseRule :superviseRuleList){
                codes.add(String.valueOf(superviseRule.getAdminRegionCode()));
            }
        } else if(OrgEnum.监检机构.getName().equals(roleName)){
            wrapper.eq(SuperviseRule::getInspectionUnitId,companyId);
            List<SuperviseRule> superviseRuleList = superviseRuleService.list(wrapper);
            for (SuperviseRule superviseRule :superviseRuleList){
                codes.add(String.valueOf(superviseRule.getAdminRegionCode()));
            }
        } else {
            projectList = projectResourceMapper.getProjectPage(roleName,companyId,codes);
        }
        if(!ValidationUtil.isEmpty(codes)){
            projectList = projectResourceMapper.getProjectPage(roleName,companyId,codes);
        }
        return projectList;
    }


    /**
     * 获取当前登录所在单位下的项目中的所有资源列表
     * @return
     */
    @BusinessIdentify
    public IPage getResourceInfo(String type,IPage page,ProjectResourceDto projectResourceinfo){
        List<Project> projectList = this.getProjectList();
        List<Long> projectIdList = new ArrayList<>();
        List<Long> idList = new ArrayList<>();
        List<ProjectResourceDto> list = new ArrayList<>();
        Set<String> codes = new HashSet<>();
        Map map = new HashMap();
        for(Project project:projectList){
            //获取项目id
            projectIdList.add(project.getSequenceNbr());
            codes.add(project.getSequenceNbr().toString());
            map.put(project.getSequenceNbr(),project.getName());
        }
        for(Long projectId:projectIdList){
            LambdaQueryWrapper<ProjectResource> projectResourceWrapper = new LambdaQueryWrapper<>();
            projectResourceWrapper.eq(ProjectResource::getType, type)
                    .eq(ProjectResource::getProjectId,projectId);
            IPage<ProjectResource> projectResourceList = this.page(page,projectResourceWrapper);
            for(ProjectResource projectResource : projectResourceList.getRecords()){
                //获取资源ID
                idList.add(projectResource.getResourceId());

                map.put(projectResource.getResourceId(),map.get(projectId));
            }
        }
        if(焊工资源.getCode().equals(type)){
            List<Map> mapList = new ArrayList<>();
            for(Long welderId:idList){
                Map detailMap = orgService.getdetialInfo(String.valueOf(welderId));
                detailMap.put("projectName",map.get(welderId));
                mapList.add(detailMap);
            }
            page.setRecords(mapList);
        }else if(管材资源.getCode().equals(type)){
//            for(Long id:idList){
//                ProjectResourceDto projectMaterialDto = new ProjectResourceDto();
                List<ProjectResourceDto> projectResource1 = projectResourceMapper.getProjectMaterial(type, codes, projectResourceinfo);


                //获取项目创建时间
//                LambdaQueryWrapper<ProjectResource> wrapper = new LambdaQueryWrapper<>();
//                wrapper.eq(ProjectResource::getResourceId,id);
//                ProjectResource projectResource = projectResourceMapper.selectOne(wrapper);
//                projectMaterialDto.setRecDate(projectResource.getRecDate());
//                projectMaterialDto.setProjectName(String.valueOf(map.get(id)));
//                projectMaterialDto.setProjectResourceId(id);

//            }
            page.setRecords(projectResource1);
        }else {
//            for(Long id:idList){
//                ProjectResourceDto projectResourceDto = new ProjectResourceDto();
                List<ProjectResourceDto> projectResource1 = projectResourceMapper.getProjectEquipment(type, codes, projectResourceinfo);
//                for (ProjectResourceDto i:projectResource1) {
//                    BeanUtils.copyProperties(i,projectResourceDto);
//                    list.add(projectResourceDto);
//                }
            page.setRecords(projectResource1);

            }

//        }


        return page;
    }
}