package com.yeejoin.amos.boot.module.ymt.flc.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.SourceFileServiceImpl;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.EquipmentDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.EquipmentIndexDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.Equipment;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.EquipmentIndex;
import com.yeejoin.amos.boot.module.ymt.flc.api.enums.EquipmentStatusEnum;
import com.yeejoin.amos.boot.module.ymt.flc.api.mapper.EquipmentMapper;
import com.yeejoin.amos.boot.module.ymt.flc.api.service.IEquipmentService;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * 装备信息表服务实现类
 *
 * @author system_generator
 * @date 2021-11-25
 */
@Service
public class EquipmentServiceImpl extends BaseService<EquipmentDto, Equipment, EquipmentMapper> implements IEquipmentService {

    @Autowired
    SourceFileServiceImpl sourceFileService;

    @Autowired
    EquipFeignClient equipFeignClient;


    @Autowired
    EquipmentIndexServiceImpl equipmentIndexServiceImpl;

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;


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

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

    @Override
    public EquipmentDto createEquipment(EquipmentDto model) {
        model.setStatus(EquipmentStatusEnum.未安装.getCode()); // 0 未安装 1 已安装
        // 获取用户所在单位 保存设备所属单位
        OrgUsr myUnit = null;
        AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
        List<CompanyModel> companys = user.getCompanys();
        for(CompanyModel c : companys) {
            myUnit = iOrgUsrService.getOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete,false).eq(OrgUsr::getAmosOrgId,c.getSequenceNbr()));
        }
        if(myUnit == null) {
            throw  new BadRequest("该用户非企业人员无法添加设备");
        }
        model.setEquipUnitId(myUnit.getSequenceNbr());
        model.setEquipUnit(myUnit.getBizOrgName());
        model = this.createWithModel(model);
        // 保存设备参数信息
        List<EquipmentIndexDto> equipmentIndex = model.getEquipmentIndex();


        if(equipmentIndex != null && equipmentIndex.size()>0) {
            for(EquipmentIndexDto t : equipmentIndex) {
                t.setEquipmentId(model.getSequenceNbr());
                t.setEquipmentName(model.getName());
                equipmentIndexServiceImpl.createWithModel(t);
            }
        }

        saveSourceFile(model);
        return model;
    }

    @Override
    public EquipmentDto updateEquipment(EquipmentDto model) {
        this.updateWithModel(model);
        saveSourceFile(model);
        // 先删除参数信息 再添加新的参数信息
        equipmentIndexServiceImpl.remove(new LambdaQueryWrapper<EquipmentIndex>().eq(EquipmentIndex::getEquipmentId,model.getSequenceNbr()));
        // 保存设备参数信息
        List<EquipmentIndexDto> equipmentIndex = model.getEquipmentIndex();
        if(equipmentIndex != null && equipmentIndex.size()>0) {
            for(EquipmentIndexDto t : equipmentIndex) {
                t.setEquipmentId(model.getSequenceNbr());
                t.setEquipmentName(model.getName());
                equipmentIndexServiceImpl.createWithModel(t);
            }
        }
        Bean.copyExistPropertis(this.queryBySeq(model.getSequenceNbr()), model);
        return model;
    }

    @Override
    public Boolean deleteById(Long sequenceNbr) {
        EquipmentDto equipmentDto = this.queryBySeq(sequenceNbr);
        // 未安装设备可删除
        if (!ValidationUtil.isEmpty(equipmentDto) && EquipmentStatusEnum.未安装.getCode().equals(equipmentDto.getStatus())) {
            equipmentDto.setIsDelete(true);
            this.updateWithModel(equipmentDto);
            return true;
        }
        return false;
    }

    @Override
    public List<Object> getEquipmentType() {
        return equipFeignClient.getClassification().getResult();
    }

    @Override
    public List<Object> getEquipmentClass(String typeCode) {
        return equipFeignClient.getEquipmentList(typeCode).getResult();
    }

    @Override
    public EquipmentDto getEquipmentById(Long sequenceNbr) {
        // 获取基本信息
        Equipment equipment = this.getById(sequenceNbr);
        EquipmentDto result = new EquipmentDto();
        BeanUtils.copyProperties(equipment,result);
        // 封装附件
        result.setAttachments(sourceFileService.getAttachments(equipment.getSequenceNbr()));

        // 封装详细参数
        List<EquipmentIndex> indexList = equipmentIndexServiceImpl.list(new LambdaQueryWrapper<EquipmentIndex>().eq(EquipmentIndex::getEquipmentId,equipment.getSequenceNbr()));
        List<EquipmentIndexDto> dtoList = new ArrayList<>();
        indexList.stream().forEach(t -> {
            EquipmentIndexDto temp = new EquipmentIndexDto();
            BeanUtils.copyProperties(t,temp);
            dtoList.add(temp);
        });
        result.setEquipmentIndex(dtoList);
        return result;
    }

    @Transactional
    @Override
    public Boolean batchDelete(List<Long> sequenceNbrList) {
        for(Long sequenceNbr : sequenceNbrList) {
            EquipmentDto equipmentDto = this.queryBySeq(sequenceNbr);
            // 未安装设备可删除
            if (!ValidationUtil.isEmpty(equipmentDto) && EquipmentStatusEnum.未安装.getCode().equals(equipmentDto.getStatus())) {
                equipmentDto.setIsDelete(true);
                this.updateWithModel(equipmentDto);
            }
        }
        return true;
    }

    // 保存附件信息
    public void saveSourceFile(EquipmentDto model) {
        if (model.getAttachments() != null) {
            sourceFileService.saveAttachments(model.getSequenceNbr(), model.getAttachments());
        }
    }
}