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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.*;
import com.yeejoin.amos.boot.module.ugp.api.mapper.CompanyMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.EquipmentMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.SuperviseRuleMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IEquipmentService;
import com.yeejoin.amos.boot.module.ugp.api.dto.EquipmentDto;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
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.*;

/**
 * 设备信息表服务实现类
 *
 * @author system_generator
 * @date 2022-09-22
 */
@Service
public class EquipmentServiceImpl extends BaseService<EquipmentDto, Equipment, EquipmentMapper> implements IEquipmentService {
    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    ProjectMapper projectMapper;

    @Autowired
    AttachmentServiceImpl attachmentServiceImpl;

    @Autowired
    OrgServiceImpl orgService;

    @Autowired
    SuperviseRuleMapper superviseRuleMapper;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleService;

    @Autowired
    CompanyServiceImpl companyService;

    @Autowired
    CompanyMapper companyMapper;


    /**
     * 分页查询
     */
    public Page<EquipmentDto> queryForEquipmentPage(Page<EquipmentDto> page, String name, String code, String verifyStatus)   {
        return this.queryForPage(page, "recDate", false,name,code,verifyStatus);
    }

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


    }

    /**
     * 设备数据名称查询
     *
     * @return
     */
    @BusinessIdentify
    public List<JSONObject> selectName() {
        List<JSONObject> names = new ArrayList<>();
        Long companySequenceNbr = orgService.getReginParams().getBusinessInfo().getCompanySequenceNbr();
        LambdaQueryWrapper<Equipment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Equipment::getCompanyId,companySequenceNbr);
        List<Equipment> equipment = equipmentMapper.selectList(wrapper);
        //添加查询条件
//        QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
//        wrapper.eq("company_id", installationUnitId);
        //获取项目的安装单位id
//        LambdaQueryWrapper<Project> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(Project::getCode,code);
//        Project project = projectMapper.selectOne(wrapper);
//        //获取项目的安装单位id进行查询
//        QueryWrapper<Equipment> wrapperEquipment= new QueryWrapper<>();
//        wrapperEquipment.eq("company_id", project.getInstallationUnitId());
//        List<Equipment> equipment = equipmentMapper.selectList(wrapperEquipment);

        for (Equipment i : equipment) {
            JSONObject name = new JSONObject();
            name.put("name", i.getName());
            name.put("SequenceNbr", i.getSequenceNbr());
            names.add(name);
        }

        return names;
    }

    /**
     * 根据sourceId添加附件
     * @param subForm
     * @param SequenceNbr
     *
     */
    public void saveAttachment(JSONArray subForm,Long SequenceNbr){
        AttachmentDto attachmentDto = new AttachmentDto();
        attachmentDto.setInfo(JSON.toJSONString(subForm));
        attachmentDto.setSourceId(SequenceNbr);
        if (!subForm.isEmpty()){
            for(Object o:subForm){
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(o));
                jsonObject.getString("Symbol_key");
                JSONArray jsonArray = jsonObject.getJSONArray("info");
                if(!ValidationUtil.isEmpty(jsonArray)) {
                    for (Object j : jsonArray) {
                        JSONObject info = JSON.parseObject(JSON.toJSONString(j));
                        String name = info.getString("name");
                        attachmentDto.setName(info.getString("name"));
                        attachmentDto.setType(name.substring(name.lastIndexOf(".")+1));
                        break;
                    }
                    break;
                }
            }
            attachmentServiceImpl.createWithModel(attachmentDto);
        }

    }

    public void saveProjectAttachment(JSONObject subForm,Long SequenceNbr){
        AttachmentDto attachmentDto = new AttachmentDto();
        attachmentDto.setInfo(JSON.toJSONString(subForm));
        attachmentDto.setSourceId(SequenceNbr);
        attachmentDto.setType("project");
        attachmentServiceImpl.createWithModel(attachmentDto);
    }



    @Override
    @BusinessIdentify
    public EquipmentDto saveEI(JSONObject object) {
        EquipmentDto model = new EquipmentDto();
        model.setName(object.getString("name"));
        model.setType(object.getString("type"));
        model.setCode(object.getString("code"));
        model.setManufacturer(object.getString("manufacturer"));
        model.setManufactureDate(object.getDate("manufactureDate"));
        model.setServiceLife(object.getString("serviceLife"));
        model.setInspectionDate(object.getDate("inspectionDate"));
        model.setUseStatus(object.getString("useStatus"));
        model.setVerifyStatus(object.getString("verifyStatus"));
        model.setRemark(object.getString("remark"));
        model.setCompanyId(orgService.getReginParams().getBusinessInfo().getCompanySequenceNbr());
        EquipmentDto result = this.createWithModel(model);

        return result;
    }

    /**
     * 修改设备+附件信息
     * @param sequenceNbr
     * @param object
     */
    public void updateEI(Long sequenceNbr,JSONObject object){

        Equipment model = this.getById(sequenceNbr);
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getSourceId,sequenceNbr);
        Attachment attachment = attachmentServiceImpl.getOne(wrapper);
//		AttachmentDto attachmentDto = attachmentMapper.selectAttBySeq(sequenceNbr);
        model.setName(object.getString("name"));
        model.setType(object.getString("type"));
        model.setCode(object.getString("code"));
        model.setManufacturer(object.getString("manufacturer"));
        model.setManufactureDate(object.getDate("manufactureDate"));
        model.setServiceLife(object.getString("serviceLife"));
        model.setInspectionDate(object.getDate("inspectionDate"));
        model.setUseStatus(object.getString("useStatus"));
        model.setVerifyStatus(object.getString("verifyStatus"));
        updateById(model);
        JSONArray subForm = object.getJSONArray("subForm");
        if(ValidationUtil.isEmpty(attachment)){
            saveAttachment(subForm,sequenceNbr);
        }else {
            attachment.setInfo(JSON.toJSONString(subForm));
            attachmentServiceImpl.updateById(attachment);
        }
//		 new Attachment();
//		BeanUtils.copyProperties(attachmentDto,attachment);

    }
    //设备模糊筛选
    @BusinessIdentify
    public IPage<EquipmentDto> queryEquipmentPage(IPage<EquipmentDto> page, Equipment equipment) {
        ReginParams reginParams = orgService.getReginParams();
        ReginParams.BusinessInfo businessInfo = reginParams.getBusinessInfo();
        String companyId = String.valueOf(businessInfo.getCompanySequenceNbr());
        String roleName = reginParams.getRole().getRoleName();
        Set<String> companyIds = new HashSet<>();
        if(OrgEnum.监检机构.getName().equals(roleName)){
            LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SuperviseRule::getInspectionUnitId,companyId);
            List<SuperviseRule> superviseRules = superviseRuleService.list(wrapper);
            for(SuperviseRule superviseRule : superviseRules){
                LambdaQueryWrapper<Company> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Company::getRegionCode,superviseRule.getAdminRegionCode());
                List<Company> companyList = companyService.list(wrapper1);
                for(Company company : companyList){
                   companyIds.add(String.valueOf(company.getSequenceNbr()));
                }
            }
        }else if(OrgEnum.监察部门.getName().equals(roleName)){
            LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SuperviseRule::getSuperviseDeptId,companyId);
            List<SuperviseRule> superviseRules = superviseRuleService.list(wrapper);
            for(SuperviseRule superviseRule : superviseRules){
                LambdaQueryWrapper<Company> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Company::getRegionCode,superviseRule.getAdminRegionCode());
                List<Company> companyList = companyService.list(wrapper1);
                for(Company company : companyList){
                   companyIds.add(String.valueOf(company.getSequenceNbr()));
                }
            }
        }
        companyIds.add(companyId);
//        equipment.setCompanyId(orgService.getReginParams().getBusinessInfo().getCompanySequenceNbr());
        return equipmentMapper.queryEquipmentPage(page,equipment,companyIds);
    }


    public Equipment getEquipment(Long e){
        return equipmentMapper.selectById(e);
    }


    //设备管理->信息统计
    @BusinessIdentify
    public List<Map<String,Long>> informationStatistics() {
        Set<String> companyIds = new HashSet<>();
        Long companySequenceNbr = orgService.getReginParams().getBusinessInfo().getCompanySequenceNbr();
        String companyKey = companyMapper.selectById(companySequenceNbr).getType();
        if(companyKey.equals(OrgEnum.安装单位.getKey())){
            companyIds.add(String.valueOf(companySequenceNbr));
        } else if (companyKey.equals(OrgEnum.监检机构.getKey())) {
            LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SuperviseRule::getInspectionUnitId,companySequenceNbr);
            List<SuperviseRule> inspectionLists = superviseRuleMapper.selectList(wrapper);
            for (SuperviseRule inspectionList : inspectionLists){
                LambdaQueryWrapper<Company> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Company::getRegionCode,inspectionList.getAdminRegionCode());
                List<Company> codeLists = companyMapper.selectList(wrapper1);
                for(Company codeList : codeLists){
                    companyIds.add(String.valueOf(codeList.getSequenceNbr()));
                }

            }
        } else if (companyKey.equals(OrgEnum.监察部门.getKey())) {
            LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SuperviseRule::getSuperviseDeptId, companySequenceNbr);
            List<SuperviseRule> superviseLists = superviseRuleMapper.selectList(wrapper);
            for (SuperviseRule inspectionList : superviseLists) {
                LambdaQueryWrapper<Company> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Company::getRegionCode, inspectionList.getAdminRegionCode());
                List<Company> codeLists = companyMapper.selectList(wrapper1);
                for (Company codeList : codeLists) {
                    companyIds.add(String.valueOf(codeList.getSequenceNbr()));
                }

            }
        }

        return equipmentMapper.informationStatistics(companyIds);
    }


    @BusinessIdentify
    public Page<Map<String, Object>> boundWelder(String projectId, Integer current, Integer size, String name, String type) {
        ReginParams reginParams = orgService.getReginParams();
        Long companySequenceNbr = reginParams.getBusinessInfo().getCompanySequenceNbr();
        if (!ObjectUtils.isEmpty(current) || !ObjectUtils.isEmpty(size)) {
            Page<Map<String, Object>> result;
            Page<Map<String, Object>> page = new Page<>(current, size);
            if (!ObjectUtils.isEmpty(type) && "all".equals(type)) {
                result = equipmentMapper.boundWelder(page, projectId, companySequenceNbr, name, null);
            } else {
                result = equipmentMapper.boundWelder(page, projectId, companySequenceNbr, name, "bound");
            }
            result.getRecords().forEach(item -> {
                List<JSONObject> files = attachmentServiceImpl.getFilesBySourceId(Long.valueOf(String.valueOf(item.get("sequence_nbr"))));
                item.put("files", files);
            });
            return result;
        } else {
            // 不分页时返回全部、定制组件格式统一
            Page<Map<String, Object>> listPage = new Page<>();
            List<Map<String, Object>> equipmentDtos = equipmentMapper.boundWelderList(projectId, companySequenceNbr, name);
            listPage.setRecords(equipmentDtos);
            return listPage;
        }
    }
}