package com.yuchen.saas.park.service.service.door.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuchen.saas.park.api.dto.door.DoorHolidayGroupDTO;
import com.yuchen.saas.park.api.dto.door.DoorHolidayPlanDTO;
import com.yuchen.saas.park.api.entity.device.PmgBatSmartEquipment;
import com.yuchen.saas.park.api.entity.door.DoorHolidayGroup;
import com.yuchen.saas.park.api.entity.door.DoorHolidayGroupSet;
import com.yuchen.saas.park.api.entity.door.DoorTemplateHolidayPlan;
import com.yuchen.saas.park.api.vo.door.DoorHolidayGroupVO;
import com.yuchen.saas.park.api.vo.door.DoorIotHolidayGroupPlanVO;
import com.yuchen.saas.park.api.vo.door.DoorIotHolidayPlanCfgVO;
import com.yuchen.saas.park.api.vo.door.DoorIotHolidayPlanVO;
import com.yuchen.saas.park.service.iot.IoTRemoteService;
import com.yuchen.saas.park.service.mapper.door.DoorHolidayGroupMapper;
import com.yuchen.saas.park.service.mapper.door.DoorHolidayGroupSetMapper;
import com.yuchen.saas.park.service.service.PmgBatSmartEquipmentService;
import com.yuchen.saas.park.service.service.door.DoorHolidayGroupService;
import com.yuchen.saas.park.service.service.door.DoorHolidayGroupSetService;
import com.yuchen.saas.park.service.service.door.DoorTemplateHolidayPlanService;
import com.yuchen.saas.parking.api.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.tool.utils.BeanUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 节假日组 服务实现类
 * </p>
 *
 * @author miaoqs
 * @since 2023-12-14
 */
@Slf4j
@Service
public class DoorHolidayGroupServiceImpl extends BaseServiceImpl<DoorHolidayGroupMapper, DoorHolidayGroup> implements DoorHolidayGroupService {

    @Resource
    private DoorHolidayGroupSetService holidayGroupSetService;
    @Resource
    private IoTRemoteService ioTRemoteService;
    @Resource
    private PmgBatSmartEquipmentService pmgBatSmartEquipmentService;
    @Resource
    private DoorHolidayGroupMapper doorHolidayGroupMapper;
    @Resource
    private DoorHolidayGroupSetMapper doorHolidayGroupSetMapper;
    @Resource
    private DoorTemplateHolidayPlanService doorTemplateHolidayPlanService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdate(DoorHolidayGroupDTO doorHolidayGroupDTO) {
        DoorHolidayGroup doorHolidayGroup = new DoorHolidayGroup();
        BeanUtil.copyProperties(doorHolidayGroupDTO,doorHolidayGroup);
        Long id = doorHolidayGroup.getId();
        //设置num
        if(Func.isEmpty(id)){
            QueryWrapper<DoorHolidayGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper .select("max(num) as num");
            DoorHolidayGroup holidayGroup = doorHolidayGroupMapper.selectOne(queryWrapper);
            if(Func.isNotEmpty(holidayGroup) && holidayGroup.getNum()>0){
                doorHolidayGroup.setNum(holidayGroup.getNum()+1);
            }else{
                doorHolidayGroup.setNum(1);
            }
        }
        saveOrUpdate(doorHolidayGroup);

        if(Func.isNotEmpty(doorHolidayGroupDTO.getDoorHolidayGroupSetList())){
            //移除原有假日设置
            if(Func.isNotEmpty(id)){
                holidayGroupSetService.remove(new LambdaQueryWrapper<DoorHolidayGroupSet>()
                        .eq(DoorHolidayGroupSet::getPmgHolidayGroupId, id));
            }
            //新增
            List<DoorHolidayGroupSet> doorHolidayGroupSetList = doorHolidayGroupDTO.getDoorHolidayGroupSetList();
            for (DoorHolidayGroupSet groupSet : doorHolidayGroupSetList) {
                groupSet.setPmgHolidayGroupId(doorHolidayGroup.getId());
                //设置num
                QueryWrapper<DoorHolidayGroupSet> queryWrapper = new QueryWrapper<>();
                queryWrapper .select("max(num) as num");
                DoorHolidayGroupSet doorHolidayGroupSet = doorHolidayGroupSetMapper.selectOne(queryWrapper);
                if(Func.isNotEmpty(doorHolidayGroupSet) && doorHolidayGroupSet.getNum()>0){
                    groupSet.setNum(doorHolidayGroupSet.getNum()+1);
                }else{
                    groupSet.setNum(1);
                }
            }
            holidayGroupSetService.saveBatch(doorHolidayGroupSetList);
        }
        return true;
    }

    @Override
    public DoorHolidayGroupVO detail(Long id) {
        DoorHolidayGroupVO holidayGroupVO = new DoorHolidayGroupVO();
        DoorHolidayGroup holidayGroup = getById(id);
        List<DoorHolidayGroupSet> setList = holidayGroupSetService.list(new LambdaQueryWrapper<DoorHolidayGroupSet>()
                .eq(DoorHolidayGroupSet::getPmgHolidayGroupId, id));
        BeanUtil.copyProperties(holidayGroup,holidayGroupVO);
        holidayGroupVO.setDoorHolidayGroupSetList(setList);
        return holidayGroupVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteById(Long id) {
        String msg = "";
        List<DoorTemplateHolidayPlan> planList = doorTemplateHolidayPlanService.list(new LambdaQueryWrapper<DoorTemplateHolidayPlan>()
                .eq(DoorTemplateHolidayPlan::getHolidayGroupId, id));
        if(Func.isNotEmpty(planList)){
            msg = "假日组已经被引用，无法删除";
            return msg;
        }
        removeById(id);
        holidayGroupSetService.remove(new LambdaQueryWrapper<DoorHolidayGroupSet>()
                .eq(DoorHolidayGroupSet::getPmgHolidayGroupId, id));
        return msg;
    }

    @Override
    public List<DoorHolidayGroup> getList() {
        return list(new LambdaQueryWrapper<DoorHolidayGroup>()
                .orderByDesc(DoorHolidayGroup::getCreateTime));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchRemoveId(List<Long> idList) {
        String msg = "";
        if(Func.isNotEmpty(idList)){
            for (Long id : idList) {
                msg = deleteById(id);
                if(Func.isNotEmpty(msg)){
                    return msg;
                }
            }
        }
        return msg;
    }

    @Override
    public boolean setIotHolidayPlan(DoorHolidayPlanDTO doorHolidayPlanDTO) throws Exception {
        Long id = doorHolidayPlanDTO.getId();
        DoorHolidayGroup holidayGroup = getById(id);
        List<DoorHolidayGroupSet> setList = holidayGroupSetService.list(new LambdaQueryWrapper<DoorHolidayGroupSet>()
                .eq(DoorHolidayGroupSet::getPmgHolidayGroupId, id));

        if(Func.isNotEmpty(setList)){
            for (DoorHolidayGroupSet groupSet : setList) {
                DoorIotHolidayPlanVO doorIotHolidayPlanVO = new DoorIotHolidayPlanVO();
                String startDateStr = DateUtils.dateFormat(groupSet.getStartDate(), "yyyy-MM-dd");
                String endDateStr = DateUtils.dateFormat(groupSet.getEndData(), "yyyy-MM-dd");
                groupSet.getStartDate();
                doorIotHolidayPlanVO.setBeginDate(startDateStr);
                doorIotHolidayPlanVO.setEndDate(endDateStr);
                doorIotHolidayPlanVO.setHolidayPlanID(holidayGroup.getNum().toString());
                doorIotHolidayPlanVO.setDeleteHolidayPlan(1);
                doorIotHolidayPlanVO.setHolidayPlanName(holidayGroup.getHolidayGroupName());
                doorIotHolidayPlanVO.setEnable(1);

                String timeGroup = groupSet.getTimeGroup();
                if(Func.isNotEmpty(timeGroup)){
                    List<DoorIotHolidayPlanCfgVO> HolidayPlanCfgList = new ArrayList<>();
                    String[] groups = timeGroup.split(";");
                    for (int i = 1; i <= groups.length; i++) {
                        DoorIotHolidayPlanCfgVO doorIotHolidayPlanCfgVO = new DoorIotHolidayPlanCfgVO();
                        String[] times = groups[i-1].split(",");
                        doorIotHolidayPlanCfgVO.setBeginTime(times[0]);
                        doorIotHolidayPlanCfgVO.setEndTime(times[1]);
                        doorIotHolidayPlanCfgVO.setId(i);
                        doorIotHolidayPlanCfgVO.setEnable(1);
                        doorIotHolidayPlanCfgVO.setAuthenticationTimesEnabled(1);
                        doorIotHolidayPlanCfgVO.setAuthenticationTimes(10);
                        HolidayPlanCfgList.add(doorIotHolidayPlanCfgVO);
                    }
                    doorIotHolidayPlanVO.setHolidayPlanCfg(HolidayPlanCfgList);
                }
                PmgBatSmartEquipment equipment = pmgBatSmartEquipmentService.getById(doorHolidayPlanDTO.getEquipmentId());
                //调用iot接口
                Map<String,Object> params = new HashMap<>();
                Map<String,Object> body = Func.toMap(doorIotHolidayPlanVO);
                params.put("params", body);
                params.put("productKey", equipment.getProductKey());  //设备编号
                params.put("deviceName", equipment.getDeviceName());  //设备名字
                params.put("identify", "holidayPlan");  //标识符
                if(ioTRemoteService.callService(params)){
                    log.info("====== 调用iot接口 配置人员权限假日计划 成功:{} ======", JSON.toJSONString(params));
                }else {
                    log.error("====== 调用iot接口 配置人员权限假日计划 失败:{} ======", JSON.toJSONString(params));
                    throw new Exception("调用iot接口失败");
                }
            }
        }

        return true;
    }

    @Override
    public DoorIotHolidayPlanVO getIotHolidayPlan(DoorHolidayPlanDTO doorHolidayPlanDTO) throws Exception {
        PmgBatSmartEquipment equipment = pmgBatSmartEquipmentService.getById(doorHolidayPlanDTO.getEquipmentId());
        DoorHolidayGroupSet doorHolidayGroupSet = holidayGroupSetService.getById(doorHolidayPlanDTO.getId());
        //调用iot接口
        Map<String,Object> params = new HashMap<>();
        Map<String,Object> body = new HashMap<>();
        body.put("holidayPlanID", doorHolidayGroupSet.getNum());
        params.put("params", body);
        params.put("productKey", equipment.getProductKey());  //设备编号
        params.put("deviceName", equipment.getDeviceName());  //设备名字
        params.put("identify", "getHolidayPlan");  //标识符
        if(ioTRemoteService.callService(params)){
            log.info("====== 调用iot接口 获取人员权限假日计划 成功:{} ======", JSON.toJSONString(params));
        }else {
            log.error("====== 调用iot接口 获取人员权限假日计划 失败:{} ======", JSON.toJSONString(params));
            throw new Exception("调用iot接口失败");
        }
        return null;
    }

    @Override
    public boolean setIotHolidayGroupPlan(DoorHolidayPlanDTO doorHolidayPlanDTO) throws Exception {
        DoorIotHolidayGroupPlanVO doorIotHolidayGroupPlanVO = new DoorIotHolidayGroupPlanVO();
        Long id = doorHolidayPlanDTO.getId();
        DoorHolidayGroup holidayGroup = getById(id);
        List<DoorHolidayGroupSet> setList = holidayGroupSetService.list(new LambdaQueryWrapper<DoorHolidayGroupSet>().eq(DoorHolidayGroupSet::getPmgHolidayGroupId, id));
        if(Func.isNotEmpty(holidayGroup) && Func.isNotEmpty(setList)){
            for (DoorHolidayGroupSet groupSet : setList) {
                doorIotHolidayGroupPlanVO.setHolidayGroupID(holidayGroup.getNum().toString());
                doorIotHolidayGroupPlanVO.setGroupName(holidayGroup.getHolidayGroupName());
                doorIotHolidayGroupPlanVO.setEnable(1);
                doorIotHolidayGroupPlanVO.setHolidayPlanNo(groupSet.getNum().toString());
                PmgBatSmartEquipment equipment = pmgBatSmartEquipmentService.getById(doorHolidayPlanDTO.getEquipmentId());
                //调用iot接口
                Map<String,Object> params = new HashMap<>();
                Map<String,Object> body = Func.toMap(doorIotHolidayGroupPlanVO);
                params.put("params", body);
                params.put("productKey", equipment.getProductKey());  //设备编号
                params.put("deviceName", equipment.getDeviceName());  //设备名字
                params.put("identify", "holidayGroupPlan");  //标识符
                if(ioTRemoteService.callService(params)){
                    log.info("====== 调用iot接口 配置人员权限假日组 成功:{} ======", JSON.toJSONString(params));
                }else {
                    log.error("====== 调用iot接口 配置人员权限假日组 失败:{} ======", JSON.toJSONString(params));
                    throw new Exception("调用iot接口失败");
                }
            }

        }
        return true;
    }

    @Override
    public DoorIotHolidayGroupPlanVO getHolidayGroupPlan(DoorHolidayPlanDTO doorHolidayPlanDTO) throws Exception {
        PmgBatSmartEquipment equipment = pmgBatSmartEquipmentService.getById(doorHolidayPlanDTO.getEquipmentId());
        DoorHolidayGroup holidayGroup = getById(doorHolidayPlanDTO.getId());
        //调用iot接口
        Map<String,Object> params = new HashMap<>();
        Map<String,Object> body = new HashMap<>();
        body.put("holidayGroupID", holidayGroup.getNum().toString());
        params.put("params", body);
        params.put("productKey", equipment.getProductKey());  //设备编号
        params.put("deviceName", equipment.getDeviceName());  //设备名字
        params.put("identify", "getHolidayGroupPlan");  //标识符
        if(ioTRemoteService.callService(params)){
            log.info("====== 调用iot接口 获取人员权限假日组 成功:{} ======", JSON.toJSONString(params));
        }else {
            log.error("====== 调用iot接口 获取人员权限假日组 失败:{} ======", JSON.toJSONString(params));
            throw new Exception("调用iot接口失败");
        }
        return null;
    }




}
