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.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.EquipmentMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectMapper;
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.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.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 设备信息表服务实现类
 *
 * @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
    SuperviseRuleServiceImpl superviseRuleService;

    @Autowired
    CompanyServiceImpl companyService;


    /**
     * 分页查询
     */
    public Page<EquipmentDto> queryForEquipmentPage(Page<EquipmentDto> page, String name, String code, String verifyStatus)   {
        return this.queryForPage(page, null, 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);
        }

    }



    @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);
    }


}