package com.yeejoin.equipmanage.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.mapper.SignalClassifyMapper;
import com.yeejoin.equipmanage.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.yeejoin.equipmanage.common.entity.dto.PerfQuotaIotDTO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentIndexVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


/**
 * 消防装备/消防车指标
 *
 * @author wujiang
 * @date 2020-07-07
 */
@RestController
@Api(tags = "消防装备/消防车指标Api")
@RequestMapping(value = "/perf-quota", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class EquipmentIndexController {

    @Autowired
    IEquipmentIndexService equipmentIndexService;
    @Autowired
    IEquipmentSpecificIndexSerivce equipmentSpecificIndexSerivce;
    @Autowired
    IEquipmentService equipmentService;
    @Autowired
    ICarPropertyService carPropertyService;
    @Autowired
    private Sequence sequence;
    @Autowired
    IEquipmentDetailService iEquipmentDetailService;
    @Autowired
    SignalClassifyMapper signalClassifyMapper;

    /**
     * 新增消防装备/消防车指标
     *
     * @return
     */
    @PostMapping(value = "/savePerfQuota")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "新增消防装备/消防车指标", notes = "新增消防装备/消防车指标")
    public boolean savePerfQuota(@RequestBody EquipmentIndex equipmentIndex ) {
        if (equipmentIndex.getIsImportentParameter()) {
            equipmentIndex.setId(sequence.nextId());
            return equipmentIndexService.savePerfQuota(equipmentIndex);
        } else {
            Equipment equipment = equipmentService.getById(equipmentIndex.getEquipmentId());
            equipment.setPrefQuota(equipmentIndex.getPerfQuotaStr());
            return equipmentService.updateById(equipment);
        }
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @PostMapping(value = "/delete")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean deleteById(@RequestBody List<Long> id) {
        for (Long a:id) {
            boolean b = equipmentIndexService.removeById(a);
            if (!b){
                equipmentIndexService.updateE(a);
            }else{
                QueryWrapper<EquipmentSpecificIndex> equipmentSpecificIndexQueryWrapper = new QueryWrapper<>();
                equipmentSpecificIndexQueryWrapper.eq("equipment_index_id",a);
                equipmentSpecificIndexSerivce.remove(equipmentSpecificIndexQueryWrapper);
            }
        }
        return true;
    }

    /**
     * 修改消防装备/消防车指标
     *
     * @return
     */
    @PostMapping(value = "/updateById")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "修改消防装备/消防车指标", notes = "修改消防装备/消防车指标")
    public boolean updateByIdPerfQuota(HttpServletRequest request, @RequestBody EquipmentIndex equipmentIndex) {
        if (equipmentIndex.getIsImportentParameter()) {
            //如果不是物联指标项，清空物联指标项信息
            if(equipmentIndex.getIsIot()==false){
                QueryWrapper<EquipmentDetail> equipmentDetailQueryWrapper = new QueryWrapper<>();
                equipmentDetailQueryWrapper.eq("equipment_id", equipmentIndex.getEquipmentId());
                List<EquipmentDetail> equipDetailList = iEquipmentDetailService.list(equipmentDetailQueryWrapper);
                if (ObjectUtils.isEmpty(equipDetailList)) {
                    LambdaUpdateWrapper<CarProperty> carWrapper = new LambdaUpdateWrapper<>();
                    carWrapper.eq(CarProperty::getEquipmentIndexId, equipmentIndex.getId());
                    List<CarProperty> list = carPropertyService.list(carWrapper);
                    // 因为是非物联指标信息，所以此处手动定义了默认值（color:#49AA19[绿色];isAlarm:0;alarmDescribe:否;emergencyLevel:4;emergencyLevelDescribe:正常）
                    list.forEach(x -> {
                        x.setEmergencyLevelColor("#49AA19");
                        x.setIsAlarm(0);
                        x.setEmergencyLevel("4");
                        x.setEmergencyLevelDescribe("正常");
                    });
                    if(list.size() > 0){
                        carPropertyService.updateBatchById(list);
                    }
                } else {
                    LambdaUpdateWrapper<EquipmentSpecificIndex> equipWrapper = new LambdaUpdateWrapper<>();
                    equipWrapper.eq(EquipmentSpecificIndex::getEquipmentIndexId, equipmentIndex.getId());
                    List<EquipmentSpecificIndex> indexList = equipmentSpecificIndexSerivce.list(equipWrapper);
                    if (!ObjectUtils.isEmpty(indexList)) {
                        indexList.forEach(y -> {
                            y.setEmergencyLevelColor("#49AA19");
                            y.setIsAlarm(0);
                            y.setEmergencyLevel("4");
                            y.setEmergencyLevelDescribe("正常");
                        });
                        equipmentSpecificIndexSerivce.updateBatchById(indexList);
                    }
                }
                LambdaUpdateWrapper<EquipmentIndex> equipmentIndexLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                equipmentIndexLambdaUpdateWrapper.eq(EquipmentIndex::getId,equipmentIndex.getId());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getEquipmentId,equipmentIndex.getEquipmentId());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getPerfQuotaName,equipmentIndex.getPerfQuotaName());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getPerfQuotaDefinitionId,equipmentIndex.getPerfQuotaDefinitionId());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getUnitName,equipmentIndex.getUnitName());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getIsIot,equipmentIndex.getIsIot());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getTypeName,null);
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getGroupName,equipmentIndex.getGroupName());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getIndexId,equipmentIndex.getIndexId());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getSortNum,equipmentIndex.getSortNum());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getType,equipmentIndex.getType());
                equipmentIndexLambdaUpdateWrapper.set(EquipmentIndex::getPerfValue,equipmentIndex.getPerfValue());
                return equipmentIndexService.update(equipmentIndexLambdaUpdateWrapper);
            }else{
                AtomicBoolean bool = new AtomicBoolean(true);
                if (ValidationUtil.isEmpty(equipmentIndex.getTypeCode())) {
                    bool.set(false);
                }
                SignalClassify signalClassify = null;
                if (bool.get()) {
                    LambdaQueryWrapper<SignalClassify> queryWrapper = new LambdaQueryWrapper();
                    queryWrapper.inSql(SignalClassify::getTypeCode,
                            "SELECT type_code FROM wl_signal_classify WHERE UPPER(type_code) ='" + equipmentIndex.getTypeCode().toUpperCase() +"'");
                    signalClassify = signalClassifyMapper.selectOne(queryWrapper);
                    if(!ObjectUtils.isEmpty(signalClassify)){
                        equipmentIndex.setEmergencyLevelColor(signalClassify.getEmergencyLevelColor());
                        equipmentIndex.setIsAlarm(signalClassify.getIsAlarm());
                        equipmentIndex.setEmergencyLevel(signalClassify.getEmergencyLevel());
                        equipmentIndex.setEmergencyLevelDescribe(signalClassify.getEmergencyLevelDescribe());
                    }
                }
                QueryWrapper<EquipmentDetail> equipmentDetailQueryWrapper = new QueryWrapper<>();
                equipmentDetailQueryWrapper.eq("equipment_id", equipmentIndex.getEquipmentId());
                List<EquipmentDetail> equipDetailList = iEquipmentDetailService.list(equipmentDetailQueryWrapper);
                if (ObjectUtils.isEmpty(equipDetailList)) {
                    LambdaUpdateWrapper<CarProperty> carWrapper = new LambdaUpdateWrapper<>();
                    carWrapper.eq(CarProperty::getEquipmentIndexId, equipmentIndex.getId());
                    List<CarProperty> list = carPropertyService.list(carWrapper);
                    if (!ObjectUtils.isEmpty(list)) {
                        for (CarProperty x : list) {
                            x.setEquipmentIndexKey(equipmentIndex.getPerfQuotaDefinitionId());
                            x.setEquipmentIndexName(equipmentIndex.getPerfQuotaName());
                            if (bool.get()) {
                                x.setEmergencyLevelColor(signalClassify.getEmergencyLevelColor());
                                x.setIsAlarm(signalClassify.getIsAlarm());
                                x.setEmergencyLevel(signalClassify.getEmergencyLevel());
                                x.setEmergencyLevelDescribe(signalClassify.getEmergencyLevelDescribe());
                            }
                        }
                        carPropertyService.updateBatchById(list);
                    }
                } else {
                    LambdaUpdateWrapper<EquipmentSpecificIndex> equipWrapper = new LambdaUpdateWrapper<>();
                    equipWrapper.eq(EquipmentSpecificIndex::getEquipmentIndexId, equipmentIndex.getId());
                    List<EquipmentSpecificIndex> indexList = equipmentSpecificIndexSerivce.list(equipWrapper);
                    if (!ObjectUtils.isEmpty(indexList)) {
                        for (EquipmentSpecificIndex y : indexList) {
                            y.setEquipmentIndexKey(equipmentIndex.getPerfQuotaDefinitionId());
                            y.setEquipmentIndexName(equipmentIndex.getPerfQuotaName());
                            if (bool.get() && !ObjectUtils.isEmpty(signalClassify)) {
                                y.setEmergencyLevelColor(signalClassify.getEmergencyLevelColor());
                                y.setIsAlarm(signalClassify.getIsAlarm());
                                y.setEmergencyLevel(signalClassify.getEmergencyLevel());
                                y.setEmergencyLevelDescribe(signalClassify.getEmergencyLevelDescribe());
                            }
                        }
                        equipmentSpecificIndexSerivce.updateBatchById(indexList);
                    }
                }
                return equipmentIndexService.updateById(equipmentIndex);
            }
        } else {
            Equipment equipment = equipmentService.getById(equipmentIndex.getEquipmentId());
            if(StringUtils.isEmpty(equipmentIndex.getPerfQuotaStr())){
                equipment.setPrefQuota(null);
            }else{
                equipment.setPrefQuota(equipmentIndex.getPerfQuotaStr());
            }
            return equipmentService.updateById(equipment);
        }
    }


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public EquipmentIndex selectById(HttpServletRequest request, @PathVariable Long id) {
        return equipmentIndexService.getById(id);
    }


    /**
     * 列表分页查询
     *
     * @return
     */
    @PostMapping(value = "/list")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "列表分页查询", notes = "列表分页查询")
    public IPage<EquipmentIndexVO> listPage(@RequestBody PerfQuotaIotDTO perfQuotaIotDTO) {
        return equipmentIndexService.getPerfQutoaPage(perfQuotaIotDTO.getPage(), perfQuotaIotDTO.getEquipmentId(), perfQuotaIotDTO.getGroupName());
    }

    /**
     * 列表查询
     *
     * @return
     */
    @PostMapping(value = "/listAll")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "列表查询", notes = "列表查询")
    public ResponseModel<Object> listAll(@RequestBody PerfQuotaIotDTO perfQuotaIotDTO) {
        return ResponseHelper.buildResponse(equipmentIndexService.getPerfQutoaList(perfQuotaIotDTO.getEquipmentId()));
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/detail")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "详情", notes = "详情")
    public EquipmentIndexVO getOnePrefQuota(Long id, Long equipId) {
        if (id == null) {
            EquipmentIndexVO equipmentIndexVO = new EquipmentIndexVO();
            equipmentIndexVO.setIsImportentParameter(false);
            equipmentIndexVO.setPerfQuotaStr(equipmentService.getById(equipId).getPrefQuota());
            return equipmentIndexVO;
        } else {
            return equipmentIndexService.getOnePrefQuota(id);
        }

    }


    @GetMapping(value = "/checkName")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "名称去重", notes = "名称去重")
    public String  checkName(Long id,Long dataId,Long fId) {
        return equipmentIndexService.checkName(id,dataId,fId);
    }

}


