package com.sptg.estate.biz.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.device.api.dto.DeviceDto;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.dto.DeviceInstallationDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.UnitFeign;
import com.sptg.estate.biz.mapper.DeviceInstallationMapper;
import com.sptg.estate.biz.service.DeviceInstallationServiceInterface;
import com.sptg.estate.biz.service.InstallationReviewServiceInterface;
import com.sptg.estate.biz.service.PositionRecordServiceInterface;
import com.sptg.estate.biz.service.PositionServiceInterface;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.OrgFeign;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * title: ProjectServiceImpl
 * package: com.sptg.estate.biz.security
 * description: 设备安装-服务层实现层
 *
 *               
 *                     
 */
@Service
@RequiredArgsConstructor
public class DeviceInstallationServiceImpl extends ServiceImpl<DeviceInstallationMapper, DeviceInstallation> implements DeviceInstallationServiceInterface {

    private final DeviceFeign deviceFeign;
    private final PositionRecordServiceInterface positionRecordServiceInterface;
    private final InstallationReviewServiceInterface installationReviewServiceInterface;
    private final OrgFeign orgFeign;
    private final UnitFeign unitFeign;

    @Override
    public Page<DeviceInstallation> showList(DeviceInstallationDto dto){
        Page<DeviceInstallation> page = dto.getPage();
        Wrapper<DeviceInstallation> wrapper = new EntityWrapper<DeviceInstallation>();
        wrapper.eq("i_status", OperationConstant.ZERO);
        //设备序列号
        String serialNumber = dto.getSerialNumber();
        if(StringUtils.isNotBlank(serialNumber)){
            wrapper.like("is_serial_number", serialNumber);
        }
        //楼盘名字
        String residentialName = dto.getResidentialName();
        if(StringUtils.isNotBlank(residentialName)){
            wrapper.like("s_residential_name", residentialName);
        }
        //小区id
        Long residentialId = dto.getResidentialId();
        if(residentialId!=null){
            wrapper.eq("l_residential_id", residentialId);
        }
        //安装人
        String createName = dto.getCreateName();
        if(StringUtils.isNotBlank(createName)){
            wrapper.like("s_create_name", createName);
        }
        //开始安装时间
        Date beginDate = dto.getBeginDate();
        if(beginDate!=null){
            wrapper.ge("t_create_date",beginDate);
        }
        //结束安装时间
        Date endDate = dto.getEndDate();
        if(endDate!=null){
            wrapper.le("t_create_date",endDate);
        }
        //机构位置
        String orgPosition = dto.getOrgPosition();
        if(StringUtils.isNotBlank(orgPosition)){
            wrapper.like("s_org_position", orgPosition, SqlLike.RIGHT);
        }
        //小程序端条件查询
        if(StringUtils.isNotBlank(dto.getConditionName())){
            wrapper.like("s_serial_number", dto.getConditionName()).or().like("s_create_name",dto.getConditionName()).or().like("s_unit_name",dto.getConditionName()).or().like("s_install_path",dto.getConditionName());
        }
        //排序
        wrapper.orderBy("t_create_date",false);
        return this.selectPage(dto.getPage(),wrapper);
    }

    @Override
    public DeviceInstallation findById(long id){
       return this.selectById(id);
    }

    @Override
    @LcnTransaction
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkState(DeviceInstallationDto dto) {
        if(dto==null||dto.getId()==null||dto.getCheckState()==null){
            return false;
        }
        //判断是否可审核
        DeviceInstallation currentDeviceInstallation = this.selectById(dto.getId());
        //审核通过不能重复审核
        if(currentDeviceInstallation==null||currentDeviceInstallation.getCheckState()==1){
            return false;
        }
        DeviceInstallation deviceInstallation=new DeviceInstallation();
        deviceInstallation.setId(dto.getId());
        boolean result = true;
        //审核不通过
        if(dto.getCheckState()== OperationConstant.TWO){
            deviceInstallation.setCheckOpinion(dto.getCheckOpinion());
            //审核通过 --向设备表插入信息
        }else if(dto.getCheckState()==1){
            DeviceDto deviceDto = new DeviceDto();
            InstallationReview installationReview = this.installationReviewServiceInterface.selectById(currentDeviceInstallation.getInstallationReviewId());
            PositionRecord positionRecord = this.positionRecordServiceInterface.selectById(installationReview.getPositionRecordId());
            //  获取小区信息
            Organization xqOrg = this.orgFeign.getOrgById(currentDeviceInstallation.getResidentialId());
            if(xqOrg==null){
                return false;
            }
            Organization rootOrg = this.orgFeign.getOrgById(xqOrg.getRootOrgId());
            // 设备序列号
            deviceDto.setSerialNumber(currentDeviceInstallation.getSerialNumber());
            deviceDto.setXqId(currentDeviceInstallation.getResidentialId());
            // 设备安装位置
            deviceDto.setInstallPath(positionRecord.getInstallPath());
            deviceDto.setInstallPathId(positionRecord.getInstallPathId());
            // 紧急开门密码
            deviceDto.setOpenDoorPwd("888888");
            // 管理密码
            deviceDto.setAdminPwd("115200");
            // 脸识别度
            deviceDto.setFaceResolution(80);
            // 是否启用时间策略
            deviceDto.setTimeStrategyIsEnable(1);
            // 开启活体检测,默认开启
            deviceDto.setLiveDetect(0);
            // 设备类型：{1：门禁机，2：管理机}
            deviceDto.setTypeNumber(1);
            // 省市区
            deviceDto.setRegionProvince(xqOrg.getRegionProvince());
            deviceDto.setRegionCity(xqOrg.getRegionCity());
            deviceDto.setRegionArea(xqOrg.getRegionArea());
            // 创建人
            deviceDto.setCreateAccountId(deviceInstallation.getCreateAccountId());
            // 设备朝向 { 1：进,2：出 }
            deviceDto.setIsOut(positionRecord.getIsOut());
            // 设备开门时长
            deviceDto.setDelay(5);
            deviceDto.setDiscernBoxPosition(1);
            deviceDto.setPlayModel(2);
            deviceDto.setIsShowUsername(2);

            //  设置小区名称
            deviceDto.setXqName(xqOrg.getName());
            deviceDto.setOrgPosition(xqOrg.getPosition());
            //  位置信息
            deviceDto.setRegionProvince(xqOrg.getRegionProvince());
            deviceDto.setRegionCity(xqOrg.getRegionCity());
            deviceDto.setRegionArea(xqOrg.getRegionArea());
            //  跟组织信息
            deviceDto.setRootOrgId(rootOrg.getId());
            deviceDto.setRootOrgName(rootOrg.getName());
            //  设备名称 = 小区名称 + 单元名称 + 安装位置 + 序号
            StringBuilder name = new StringBuilder(xqOrg.getName());
            if(null != positionRecord.getUnitId()){
                Unit unit = this.unitFeign.findUnitById(positionRecord.getUnitId());
                name.append(unit.getName());
                deviceDto.setUnitId(unit.getId());
                deviceDto.setDyName(unit.getName());
                deviceDto.setOrgPosition(unit.getOrgPosition());
            }
            name.append(deviceDto.getInstallPath());
            deviceDto.setName(name.toString());
            ResultBean<Boolean> resultBean=this.deviceFeign.addEntity(deviceDto);
            result = resultBean.getData();
        }
        deviceInstallation.setCheckDate(new Date());
        deviceInstallation.setCheckAccountId(dto.getCheckAccountId());
        deviceInstallation.setCheckName(dto.getCheckName());
        deviceInstallation.setCheckState(dto.getCheckState());
        if(result){
            result = this.updateById(deviceInstallation);
        }
        return result;
    }

    @Override
    public ResultBean<Integer> countByOrgPosition(String orgPosition) {
        Wrapper<DeviceInstallation> wrapper = new EntityWrapper<>();
        wrapper.like("s_org_position", orgPosition);
        wrapper.eq("i_status", OperationConstant.ZERO);
        return new ResultBean<>(ResultEnum.SUCCESS,this.selectCount(wrapper));
    }

    @Override
    public ResultBean<DeviceInstallation> findListByPosition(DeviceInstallationDto dto) {
        Wrapper<DeviceInstallation> wrapper = new EntityWrapper<>();
        //机构结构
        wrapper.like("idi.s_org_position", dto.getOrgPosition());
        wrapper.eq("idi.i_status", OperationConstant.ZERO);
        return new ResultBean<>(ResultEnum.SUCCESS,this.baseMapper.findListByPosition(wrapper));
    }

    @Override
    public ResultBean<Boolean> countBySerialNumber(String serialNumber) {
        Wrapper<DeviceInstallation> wrapper = new EntityWrapper<>();
        wrapper.like("s_serial_number", serialNumber);
        wrapper.eq("i_status", OperationConstant.ZERO);
        int count = this.selectCount(wrapper);
        if(count>0){
            return new ResultBean<>(ResultEnum.SUCCESS,true);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,false);
    }

    @Override
    public ResultBean<DeviceInstallation> findBySerialNumber(String serialNumber) {
        Wrapper<DeviceInstallation> wrapper = new EntityWrapper<>();
        wrapper.like("s_serial_number", serialNumber);
        wrapper.eq("i_status", OperationConstant.ZERO);
        return new ResultBean<>(ResultEnum.SUCCESS,this.selectOne(wrapper));
    }

    @Override
    public ResultBean<Boolean> edit(DeviceInstallation deviceInstallation) {
        //判断是否可修改
        DeviceInstallation currentDeviceInstallation = this.selectById(deviceInstallation.getId());
        if(currentDeviceInstallation==null||currentDeviceInstallation.getCheckState()==1){
            return new ResultBean<>(ResultEnum.SUCCESS,false);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,this.updateById(deviceInstallation));
    }

    @Override
    public ResultBean<Boolean> countByInstallationReviewId(Long installationReviewId) {
        Wrapper<DeviceInstallation> wrapper = new EntityWrapper<>();
        wrapper.eq("l_installation_review_id", installationReviewId);
        wrapper.eq("i_status", OperationConstant.ZERO);
        int count = this.selectCount(wrapper);
        if(count>0){
            return new ResultBean<>(ResultEnum.SUCCESS,true);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,false);
    }

    @Override
    public ResultBean<DeviceInstallation> findByCondition(DeviceInstallation deviceInstallation) {
        Wrapper<DeviceInstallation> wrapper = new EntityWrapper<>();
        wrapper.eq("i_status", OperationConstant.ZERO);
        Boolean isSelect = false;
        if(deviceInstallation.getCheckState()!=null){
            wrapper.eq("i_check_state", deviceInstallation.getCheckState());
            isSelect = true;
        }
        if(deviceInstallation.getResidentialId()!=null){
            wrapper.eq("l_residential_id",deviceInstallation.getResidentialId() );
            isSelect = true;
        }
        if(isSelect){
            return new ResultBean<>(ResultEnum.SUCCESS,this.selectList(wrapper));
        }else{
            return new ResultBean<>(ResultEnum.SUCCESS,new ArrayList<>());
        }
    }

    @Override
    public ResultBean<Boolean> deleteEntity(Long id) {
        DeviceInstallation d = new DeviceInstallation();
        d.setId(id);
        d.setStatus(OperationConstant.MINUS_ONE);
        return new ResultBean<>(ResultEnum.SUCCESS,this.updateById(d));
    }
}
