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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.biz.utils.CommonResponseUtil;
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.WelderDto;
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.mapper.WeldMapper;
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.apache.ibatis.annotations.Case;
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 org.typroject.tyboot.core.restful.utils.ResponseModel;

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 ResponseModel 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);
            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);
                boolean save = this.save(projectResource);
                //判断
                if (save && type.equals(设备资源.getName())) {
                    LambdaQueryWrapper<Equipment> wrapperEquipment = new LambdaQueryWrapper<>();
                    wrapperEquipment.eq(BaseEntity::getSequenceNbr, select);
                    Equipment equipment = new Equipment();
                    equipment.setUseStatus("已使用");
                    equipmentMapper.update(equipment, wrapperEquipment);

                }
            } else {
//               throw new Exception("该资源已存在");
                return CommonResponseUtil.failure("该资源已存在");
            }
        }
        return CommonResponseUtil.success();
    }


    /**
     * 根据项目id获取项目使用到的设备
     * @param projectId
     * @return
     */
    public List<JSONObject> getProjectEquipment(String projectId){
        List<ProjectResource> resourceList = getProjectResources(projectId, 设备资源);
        List<JSONObject> mapList = new ArrayList<>();
        for (ProjectResource projectResource : resourceList) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(projectResource));
            LambdaQueryWrapper<Equipment> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Equipment::getSequenceNbr,projectResource.getResourceId());
            jsonObject.putAll(equipmentService.getMap(wrapper));
            mapList.add(jsonObject);
        }
        return mapList;
    }

    /**
     * 根据项目ID获取项目使用到的管材
     * @param projectId
     * @return
     */
    public List<JSONObject> getProjectMaterial(String projectId){
        List<ProjectResource> resourceList = getProjectResources(projectId, 管材资源);
        List<JSONObject> mapList = new ArrayList<>();
        for (ProjectResource projectResource : resourceList) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(projectResource));
            LambdaQueryWrapper<Equipment> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Equipment::getSequenceNbr,projectResource.getResourceId());
            jsonObject.putAll(equipmentService.getMap(wrapper));
            mapList.add(jsonObject);
        }
        return mapList;
    }

    /**
     * 根据项目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();
        //判断普通人员在哪个单位
        if(OrgEnum.普通人员.getName().equals(roleName)){
            if(OrgEnum.安装单位.getKey().equals(orgService.getOrgUsrById(companyId).getOrgExpandAttr1())){
                roleName = OrgEnum.安装单位.getName();
            }
        }
        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;
    }

    public ProjectResource getprojectResource(Long resourceId,Long sequenceNbr,String type){
        LambdaQueryWrapper<ProjectResource> wrapper = new LambdaQueryWrapper<>();
        ProjectResource projectResource =null;
        if (sequenceNbr == null) {
            wrapper.eq(resourceId!=null,ProjectResource::getResourceId,resourceId)
                    .eq(!ValidationUtil.isEmpty(type),ProjectResource::getType,type);
            projectResource=projectResourceMapper.selectOne(wrapper);
            return projectResource;
        }
        if (resourceId == null) {
            wrapper.eq(resourceId!=null,ProjectResource::getSequenceNbr,sequenceNbr)
                    .eq(!ValidationUtil.isEmpty(type),ProjectResource::getType,type);
            projectResource=projectResourceMapper.selectOne(wrapper);
            return projectResource;
        }
       return projectResource;
    }
}