package com.zd.laboratory.service.impl;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.LongAdder;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.utils.SaveUtil;
import com.zd.laboratory.domain.LabHardware;
import com.zd.laboratory.domain.LabSubject;
import com.zd.laboratory.domain.vo.LabBigViewGroupVO;
import com.zd.laboratory.domain.vo.LabControlVO;
import com.zd.laboratory.domain.vo.LabHardwareVO;
import com.zd.laboratory.domain.vo.LabRiskPlanListVO;
import com.zd.laboratory.service.ILabSubjectService;
import com.zd.laboratory.socket.command.Symbol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zd.laboratory.mapper.LabControlMapper;
import com.zd.laboratory.domain.LabControl;
import com.zd.laboratory.service.ILabControlService;

/**
 * 控制记录Service业务层处理
 *
 * @author zd
 * @date 2021-09-07
 */
@Service
public class LabControlServiceImpl implements ILabControlService {
    @Autowired
    private LabControlMapper labControlMapper;

    @Autowired
    private ILabSubjectService labSubjectService;

    private final String operation = "{}:{}";

    /**
     * 查询控制记录
     *
     * @param id 控制记录主键
     * @return 控制记录
     */
    @Override
    public LabControl selectLabControlById(Long id) {
        return labControlMapper.selectLabControlById(id);
    }

    /**
     * 查询控制记录列表
     *
     * @param labControl 控制记录
     * @return 控制记录
     */
    @Override
    @DataScope(deptAlias = "xx",userAlias = "xx", permi = PerPrefix.LABORATORY_CONTROL)
    public List<LabControlVO> selectLabControlList(LabControlVO labControl) {
        return labControlMapper.selectLabControlList(labControl);
    }

    /**
     * 创建一个控制记录并且报错:手动方式
     * @param hardwareVO
     * @return
     */
    public void  manualCreateLabControlAndSave(LabHardware hardwareVO,Symbol.order order , Symbol.command command)
    {
        LabControl lab = createLab(hardwareVO, order, command);
        lab.setTriggerModes(2);
        String userName=SecurityUtils.getUsername();
        if(StringUtils.isNotEmpty(userName)){
            SaveUtil.setCommonAttr(lab);
            lab.setUserName(userName);
        }else{
            lab.setUserName("预案自动执行");
        }

        insertLabControl(lab);
    }
    /**
     * 创建一个控制记录并且报错:自动
     * @param hardwareVO
     * @return
     */
    public void   autoCreateLabControlAndSave(LabHardware hardwareVO,Symbol.order order , Symbol.command command)
    {
        LabControl lab = createLab(hardwareVO, order, command);
        lab.setTriggerModes(1);
        lab.setUserName("预案自动执行");
        insertLabControl(lab);
    }
    private LabControl createLab(LabHardware hardwareVO, Symbol.order order, Symbol.command command) {
        LabControl control = new LabControl();
        control.setOperation(StrUtil.format(operation, order.getTip(), command.getTip()));
        control.setControlType(command ==Symbol.command.close?0:1);
        control.setHardwareType(hardwareVO.getType());
        control.setHardwareId(hardwareVO.getId());
        control.setSubjectId(hardwareVO.getSubjectId());
        if(hardwareVO.getId()!=null)
        {
            LabSubject subject = labSubjectService.selectLabSubjectById(hardwareVO.getId());
            control.setDeptId(Optional.ofNullable(subject).map(a->a.getDeptId()).orElse(null));
        }
        return control;
    }

    /**
     * 新增控制记录
     *
     * @param labControl 控制记录
     * @return 结果
     */
    @Override
    public int insertLabControl(LabControl labControl) {
        labControl.setCreateTime(DateUtils.getNowDate());
        return labControlMapper.insertLabControl(labControl);
    }

    /**
     * 修改控制记录
     *
     * @param labControl 控制记录
     * @return 结果
     */
    @Override
    public int updateLabControl(LabControl labControl) {
        labControl.setUpdateTime(DateUtils.getNowDate());
        return labControlMapper.updateLabControl(labControl);
    }

    /**
     * 批量删除控制记录
     *
     * @param ids 需要删除的控制记录主键
     * @return 结果
     */
    @Override
    public int deleteLabControlByIds(Long[] ids) {
        return labControlMapper.deleteLabControlByIds(ids);
    }

    /**
     * 删除控制记录信息
     *
     * @param id 控制记录主键
     * @return 结果
     */
    @Override
    public int deleteLabControlById(Long id) {
        return labControlMapper.deleteLabControlById(id);
    }


    /**
     * 查询根据年倒推12个月的信息统计
     *
     * @return 控制记录
     */
    @Override
    @DataScope(deptAlias = "x2")
    public LinkedHashMap <String,Object> getYearControlInfo(LabControl labControl) {
        List<LabBigViewGroupVO> bigViewGroupVOList = labControlMapper.getYearControlInfo(labControl);
        LongAdder result = new LongAdder();
        Optional.ofNullable(bigViewGroupVOList).orElseGet(Collections::emptyList).stream().forEach(a->{
            result.add(a.getNum());
        });
        LinkedHashMap <String,Object> allList = new LinkedHashMap<>();
        allList.put("resultCount",result.sum());
        allList.put("list",bigViewGroupVOList);
        return allList;
    }


    /**
     * 查询预案统计次数列表
     *
     * @return 控制记录
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<LabRiskPlanListVO> getRiskPlanList(LabControlVO labControlVO) {
        List<LabRiskPlanListVO> planList = labControlMapper.getRiskPlanList(labControlVO);
        Optional.ofNullable(planList).orElseGet(Collections::emptyList).stream().forEach(a->{
            JSONArray data = JSONArray.parseArray(a.getSensorJson());
            if (data != null) {
                String content = "";
                for (int i = 0; i < data.size(); i++) {
                    JSONObject dataItem = data.getJSONObject(i);
                    content+=","+dataItem.getString("describe")+"异常";

                }
                a.setSesorContent(content.substring(1,content.length()));
            }
        });
        return planList;
    }
}
