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.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.Equipment;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProjectResource;
import com.yeejoin.amos.boot.module.ugp.api.entity.SuperviseRule;
import com.yeejoin.amos.boot.module.ugp.api.mapper.EquipmentMapper;
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 io.swagger.annotations.Api;
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 java.util.stream.Collectors;

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
    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) {
        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");
            //判断资源类型并插入
            if (type.equals(设备资源.getName())) {
                projectResource.setType(设备资源.getCode());
            }
            if (type.equals(焊工资源.getName())) {
                projectResource.setType(焊工资源.getCode());
            }
            if (type.equals(管材资源.getName())) {
                projectResource.setType(管材资源.getCode());
            }

            projectResource.setProjectId(SequenceNbr);
            projectResource.setResourceId(Long.valueOf(select));
            Equipment equipment = equipmentMapper.selectById(Long.valueOf(select));
            projectResource.setName(equipment.getName());
            BeanUtils.copyProperties(projectResource,Resource);

            this.save(projectResource);
        }
        return Resource;
    }


    /**
     * 获取当前登录人所在单位下的所有项目列表
     * @return
     */
    @BusinessIdentify
    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<>();
        String reginCode = "";
        if(OrgEnum.监察部门.getName().equals(roleName)){
            wrapper.eq(SuperviseRule::getSuperviseDeptId,companyId);
            reginCode = superviseRuleService.getOne(wrapper).getAdminRegion();
        } else if(OrgEnum.监检机构.getName().equals(roleName)){
            wrapper.eq(SuperviseRule::getInspectionUnitId,companyId);
            reginCode = superviseRuleService.getOne(wrapper).getAdminRegion();
        } else {
            projectList = projectResourceMapper.getProjectPage(roleName,companyId);
        }

        if(!ValidationUtil.isEmpty(reginCode)){
            projectList = projectResourceMapper.getProjectPage(roleName,reginCode);
        }
        return projectList;
    }


    /**
     * 获取当前登录所在单位下的项目中的所有资源列表
     * @return
     */
    @BusinessIdentify
    public IPage getResourceInfo(String type,IPage page){
        List<Project> projectList = this.getProjectList();
        List<Long> projectIdList = new ArrayList<>();
        List<Long> idList = new ArrayList<>();
        List list = new ArrayList<>();
        Map map = new HashMap();
        for(Project project:projectList){
            projectIdList.add(project.getSequenceNbr());
            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()){
                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){
                ProjectMaterialDto projectMaterialDto = new ProjectMaterialDto();
                BeanUtils.copyProperties(materialService.getById(id),projectMaterialDto);
                projectMaterialDto.setProjectName(String.valueOf(map.get(id)));
                projectMaterialDto.setProjectResourceId(id);
                list.add(projectMaterialDto);
            }
            page.setRecords(list);
        }else {
            for(Long id:idList){
                WelderEquipmentDto welderEquipmentDto = new WelderEquipmentDto();
                BeanUtils.copyProperties(equipmentService.getById(id),welderEquipmentDto);
                welderEquipmentDto.setProjectName(String.valueOf(map.get(id)));
                welderEquipmentDto.setProjectResourceId(String.valueOf(id));
                list.add(welderEquipmentDto);
            }
            page.setRecords(list);
        }
        return page;
    }
}