package com.bonus.sgzb.base.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.sgzb.base.api.domain.MaLabelBind;
import com.bonus.sgzb.base.api.domain.MaMachine;
import com.bonus.sgzb.base.api.domain.MaType;
import com.bonus.sgzb.base.api.domain.SltAgreementApply;
import com.bonus.sgzb.base.domain.MaPropSet;
import com.bonus.sgzb.base.domain.vo.IotRecordVo;
import com.bonus.sgzb.base.mapper.*;
import com.bonus.sgzb.base.service.ISysConfigService;
import com.bonus.sgzb.base.service.MaMachineService;
import com.bonus.sgzb.common.core.constant.Constants;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.utils.HttpHelper;
import com.bonus.sgzb.common.core.utils.RsaUtil;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.exception.ExceptionDict;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MaMachineServiceImpl implements MaMachineService {
    private String zlptUrl;
    @Resource
    private MaMachineMapper maMachineMapper;

    @Resource
    private MaTypeMapper typeMapper;
    @Autowired
    private ISysConfigService configService;

    @Resource
    private MaLabelBindMapper labelBindMapper;

    @Resource
    private MaPropInfoMapper maPropInfoMapper;

    @Resource
    private BaseIotMachineMapper baseIotMachineMapper;


    @Override
    public List<MaMachine> getMaMachine(MaMachine maMachine) {
        List<MaMachine> listMaMachine = new ArrayList<>();
        listMaMachine = maMachineMapper.getMaMachine(maMachine);
        if (listMaMachine.size() > 0) {
            for (MaMachine ma : listMaMachine) {
                //根据机具编码查询iot设备
                List<IotRecordVo> iotRecordVoList = baseIotMachineMapper.selectList(ma.getMaCode());
                ma.setIotNum(iotRecordVoList.size());
                //判断是否绑定了iot设备
                if (iotRecordVoList.size() > 0) {
                    for (int i = 0; i < iotRecordVoList.size(); i++) {
                        //保存定位iot设备编码
                        if ("125".equals(iotRecordVoList.get(i).getIotType())) {
                            ma.setIotCode(iotRecordVoList.get(i).getIotCode());
                        }
                    }
                }
            }
        }
        return listMaMachine;
    }

    /**
     * 添加查询物品种类,设备类型,规格型号
     *
     * @param machine
     * @return
     */

    private void getType(MaMachine machine) {
        long typeId = machine.getTypeId();
        // 规格型号
        MaType maType = typeMapper.selectTypeByTypeId(typeId);
        // 设备类型
        machine.setSpecificationType(maType.getTypeName());
        MaType maType1 = typeMapper.selectTypeByTypeId(maType.getParentId());
        // 物品种类
        machine.setDeviceType(maType1.getTypeName());
        MaType maType2 = typeMapper.selectTypeByTypeId(maType1.getParentId());
        machine.setItemType(maType2.getTypeName());
    }

    /**
     * 新增机具设备
     *
     * @param maMachine 机具设备信息
     * @return 结果
     */
    @Override
    @Transactional
    public int maMachineAdd(MaMachine maMachine) {
        int i = maMachineMapper.maMachineAdd(maMachine);
        // 新增标签绑定
        MaLabelBind maLabelBind = new MaLabelBind();
        String labelCode = maMachine.getLabelCode();
        maLabelBind.setLabelCode(labelCode);
        maLabelBind.setMaId(maMachine.getMaId());
        maLabelBind.setTypeId(maMachine.getTypeId());
        labelBindMapper.insertLabelBind(maLabelBind);

        // 新增机具和资产属性绑定关系
        MaPropSet maPropSet = new MaPropSet();
        maPropSet.setTypeId(maMachine.getTypeId());
        maPropSet.setPropId(maMachine.getPropId());
        maPropSet.setCreateTime(new Date());
        maPropSet.setCreateBy(SecurityUtils.getUsername());
        maPropSet.setCompanyId(maMachine.getCompanyId());
        maPropInfoMapper.insertMaPropSet(maPropSet);

        return i;
    }

    @Override
    @Transactional
    public int remove(Long[] maIds) {
        int res = 0;
        if (maIds != null || maIds.length > 0) {
            for (Long maId : maIds) {
                MaMachine maMachine = maMachineMapper.selectMaMachineByMaId(maId);
                if (maMachine.getTypeId() != 0 && ("15").equals(maMachine.getMaStatus())) {
                    res = maMachineMapper.updateNum(maMachine.getTypeId());
                }
            }
        }
        res += maMachineMapper.remove(maIds);
        return res;
    }

    @Override
    @Transactional
    public int updateMaMachine(MaMachine maMachine) {
        // 删除类型和资产属性绑定关系
        maPropInfoMapper.deleteMaPropSetByPropIds(maMachine.getTypeId());
        // 新增机具和资产属性绑定关系
        MaPropSet maPropSet = new MaPropSet();
        maPropSet.setTypeId(maMachine.getTypeId());
        maPropSet.setPropId(maMachine.getPropId());
        maPropSet.setCreateTime(new Date());
        maPropSet.setCreateBy(SecurityUtils.getUsername());
        maPropSet.setCompanyId(maMachine.getCompanyId());
        maPropInfoMapper.insertMaPropSet(maPropSet);
        return maMachineMapper.updateMaMachine(maMachine);
    }

    /**
     * 查询机具设备管理ma_machine
     *
     * @param maId 机具设备管理ma_machine主键
     * @return 机具设备管理ma_machine
     */
    @Override
    public MaMachine selectMaMachineByMaId(Long maId) {
        return maMachineMapper.selectMaMachineByMaId(maId);
    }

    @Override
    public MaMachine getMachineByQrCode(MaMachine maMachine) {
        MaMachine ma = maMachineMapper.getMachineByQrCode(maMachine);
        if (ma != null) {
            SltAgreementApply leaseProject = maMachineMapper.getLeaseProject(ma);
            SltAgreementApply backProject = maMachineMapper.getBackProject(ma);
            if (leaseProject != null) {
                ma.setLeaseUnit(leaseProject.getUnitName());
                ma.setLeasePro(leaseProject.getProjectName());
                ma.setLeaseTime(leaseProject.getCreateTime());
            }
            if (backProject != null) {
                ma.setBackUnit(backProject.getUnitName());
                ma.setBackPro(backProject.getProjectName());
                ma.setBackTime(backProject.getCreateTime());
            }
        } else {
            throw new ServiceException("二维码对应机具信息无效");
        }
        return ma;
    }

    @Override
    public AjaxResult pushNotifications(List<MaMachine> maMachineList) {
        zlptUrl = configService.selectConfigByKey("zlptUrl");
        log.info("MaMachineServiceImpl pushNotifications 开始处理设备推送逻辑==={}，地址{}", maMachineList, zlptUrl);
        if (maMachineList.isEmpty()) {
            throw new ServiceException(String.format(ExceptionDict.PARAM_IS_NULL_ERROR_MSG, "maMachineList"), ExceptionDict.PARAM_IS_NULL_ERROR);
        }

        //获取当前登录用户的企业机构代码
        if ( SecurityUtils.getLoginUser().getSysUser()==null && SecurityUtils.getLoginUser().getSysUser().getDept()==null){
            throw new ServiceException(ExceptionDict.PERMISSION_ERROR_MSG, ExceptionDict.PERMISSION_ERROR);
        }
        String socialCreditCode = SecurityUtils.getLoginUser().getSysUser().getDept().getSocialCreditCode();
        maMachineList.forEach(maMachine -> maMachine.setSocialCreditCode(socialCreditCode));
        String content = JSONObject.toJSONString(maMachineList);
        String encrypt;
        try {
            //encrypt = RsaUtil.encryptByPublicKey(content, Constants.publicKey);
            Map<String, String> map = new HashMap<>();
            map.put("body", content);
            String body = JSONObject.toJSONString(map);
            String data = HttpHelper.sendHttpPost(zlptUrl, body);
            log.info("dataString-=========:" + data);
            //对返回的结果进行处理
            // resultDataHandler(data);
            //修改设备状态，防止重复推送
            for (MaMachine maMachine : maMachineList) {
                MaMachine maMachine1 = new MaMachine();
                maMachine1.setMaId(maMachine.getMaId());
                maMachine1.setPushStatus(1);
                maMachineMapper.updateMaMachine(maMachine1);
            }
        } catch (Exception e) {
            // throw new RuntimeException(e);
            return AjaxResult.error("推送失败！");
        }
        return AjaxResult.success("请求成功！");
    }

    private void resultDataHandler(String data) throws Exception {
        JSONObject object = JSONObject.parseObject(data);
        System.err.println(data);
        String code = object.getString("code");
        if ("0".equals(code)) {
            String dataResultString = object.getString("data");
            // 数据解密
            String dataArrayString = RsaUtil.decryptByPrivateKey(dataResultString, Constants.publicKey);
            log.info("dataArrayString-=========:" + dataArrayString);
        } else {
            throw new Exception("推送失败！");
        }
    }
}
