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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuchen.saas.integration.feign.api.feign.CommonHikClient;
import com.yuchen.saas.integration.feign.api.util.HikApiUtil;
import com.yuchen.saas.park.api.dto.park.PmgBatPeopleTypeDTO;
import com.yuchen.saas.park.api.dto.park.PmgBatPersonSysconfigDto;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorPerson;
import com.yuchen.saas.park.api.entity.park.PmgBatPeopleType;
import com.yuchen.saas.park.api.entity.park.PmgBatPersonSysconfig;
import com.yuchen.saas.park.api.vo.park.PmgBatPeopleTypeDataVO;
import com.yuchen.saas.park.api.vo.park.PmgBatPeopleTypeVO;
import com.yuchen.saas.park.service.mapper.PmgBatPeopleTypeMapper;
import com.yuchen.saas.park.service.service.IPmgBatPersonSysconfigService;
import com.yuchen.saas.park.service.service.PmgBatPeopleTypeService;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.tool.api.R;
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.*;

/**
 * @ClassName PmgBatPeopleTypeServiceImpl
 * @Description 人员类型操作接口实现
 * @Author 刘通
 * @Date 2020/12/14 15:14
 */
@Service
public class PmgBatPeopleTypeServiceImpl extends BaseServiceImpl<PmgBatPeopleTypeMapper, PmgBatPeopleType> implements PmgBatPeopleTypeService {

    /**
     * 注入海康ISC远程调用接口
     */
    @Resource
    private CommonHikClient commonHikClient;


    @Resource
    private IPmgBatPersonSysconfigService iPmgBatPersonSysconfigService;

    @Override
    public R submit(PmgBatPeopleType pmgBatPeopleType) {
        // 拼接查询，保证类型名称唯一
        LambdaQueryWrapper<PmgBatPeopleType> peopleTypeWrapper = Wrappers.lambdaQuery();
        peopleTypeWrapper.eq(PmgBatPeopleType::getParkId, pmgBatPeopleType.getParkId());
        peopleTypeWrapper.eq(PmgBatPeopleType::getName, pmgBatPeopleType.getName());
        peopleTypeWrapper.ne(Func.isNotEmpty(pmgBatPeopleType.getId()), PmgBatPeopleType::getId,
                pmgBatPeopleType.getId());
        Integer cnt = count(peopleTypeWrapper);
        if (cnt > 0) {
            return R.error("名称或标识重复！");
        }
        // 判断ID是否存在
        if (Func.isEmpty(pmgBatPeopleType.getId())) {
            // 如果没有ID 则为新增 新增的时候 赋予 Y 可以修改的参数
            pmgBatPeopleType.setAllowingChanges("Y");
            pmgBatPeopleType = handleFaceGroup(pmgBatPeopleType, "add");
        } else {
            // 调用海康接口进行修改人脸分组
            pmgBatPeopleType = handleFaceGroup(pmgBatPeopleType, "update");
        }
        return R.status(saveOrUpdate(pmgBatPeopleType));
    }

    @Override
    public R del(Long id) {
        PmgBatPeopleType peopleType = getById(id);
        handleFaceGroup(peopleType, "del");
        return R.status(removeById(id));
    }

    /**
     * 根据园区id获取人员类型
     *
     * @param parkId
     * @return
     */
    @Override
    public List<PmgBatPeopleTypeVO> getPeopleTypeByParkId(Long parkId) {

        //初始化添加人员类型
        judgeAndAdd(parkId, "1", "业主", "房源人员");
        judgeAndAdd(parkId, "2", "租客", "房源人员");
        judgeAndAdd(parkId, "3", "家属", "房源人员");
        judgeAndAdd(parkId, "4", "家政", "房源人员");
        judgeAndAdd(parkId, "5", "成员", "房源人员");
        judgeAndAdd(parkId, "6", "其他", "房源人员");
        judgeAndAdd(parkId, "7", "物业管理", "物业人员");
        judgeAndAdd(parkId, "8", "物业人员", "物业人员");
        judgeAndAdd(parkId, "9", "安保人员", "物业人员");
        judgeAndAdd(parkId, "10", "保洁人员", "物业人员");
        judgeAndAdd(parkId, "11", "维修人员", "物业人员");
        judgeAndAdd(parkId, "12", "其他", "物业人员");
        judgeAndAdd(parkId, "13", "外卖/快递", "外部人员");
        judgeAndAdd(parkId, "14", "家政人员", "外部人员");
        judgeAndAdd(parkId, "15", "装修人员", "外部人员");
        judgeAndAdd(parkId, "16", "临时人员", "外部人员");
        judgeAndAdd(parkId, "17", "白名单人员", "特殊人员");
        judgeAndAdd(parkId, "18", "黑名单人员", "特殊人员");


        judgeAndAddConfig(parkId, "0", "isSyncDoor", "智慧门禁系统", "1");
        judgeAndAddConfig(parkId, "0", "isSyncElevator", "智慧梯控系统", "1");
        judgeAndAddConfig(parkId, "0", "isSyncFangYuanRenYuan", "房源人员", "2");
        judgeAndAddConfig(parkId, "0", "isSyncTeShuRenYuan", "物业人员", "2");
        judgeAndAddConfig(parkId, "0", "isSyncWaiBuDengJi", "外部登记", "2");
        judgeAndAddConfig(parkId, "0", "isSyncWuYeRenYuan", "特殊登记", "2");


        List<PmgBatPeopleTypeVO> listPmgBatPeopleTypeVO = new ArrayList<>();
        PmgBatPeopleTypeVO voFangYuan = getVo(parkId, "房源人员", "switchFangYuanRenYuan");
        listPmgBatPeopleTypeVO.add(voFangYuan);
        PmgBatPeopleTypeVO voWuYe = getVo(parkId, "物业人员", "switchWuYeRenYuan");
        listPmgBatPeopleTypeVO.add(voWuYe);
        PmgBatPeopleTypeVO voWaiBu = getVo(parkId, "外部人员", "switchWaiBuRenYuan");
        listPmgBatPeopleTypeVO.add(voWaiBu);
        PmgBatPeopleTypeVO voTeShu = getVo(parkId, "特殊人员", "switchTeShuRenYuan");
        listPmgBatPeopleTypeVO.add(voTeShu);


        //初始化添加自动同步


        return listPmgBatPeopleTypeVO;
    }

    private void judgeAndAddConfig(Long parkId, String paramValue, String paramCode, String paramName, String paramType) {
        LambdaQueryWrapper<PmgBatPersonSysconfig> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(PmgBatPersonSysconfig::getParkId, parkId);
        queryWrapper.eq(PmgBatPersonSysconfig::getParamCode, paramCode);
        List<PmgBatPersonSysconfig> listPmgBatPersonSysconfig = iPmgBatPersonSysconfigService.list(queryWrapper);


        if (listPmgBatPersonSysconfig != null && listPmgBatPersonSysconfig.size() > 0) {
            for (PmgBatPersonSysconfig pmgBatPersonSysconfig : listPmgBatPersonSysconfig) {
                PmgBatPersonSysconfigDto pmgBatPersonSysconfigDto = new PmgBatPersonSysconfigDto();
                BeanUtil.copyProperties(pmgBatPersonSysconfig, pmgBatPersonSysconfigDto);
                pmgBatPersonSysconfigDto.setParamName(paramName);
                pmgBatPersonSysconfigDto.setParamType(paramType);
                iPmgBatPersonSysconfigService.saveValueByKey(pmgBatPersonSysconfigDto);
            }
        } else {

            PmgBatPersonSysconfigDto pmgBatPersonSysconfigDto = new PmgBatPersonSysconfigDto();
            pmgBatPersonSysconfigDto.setParamValue(paramValue);
            pmgBatPersonSysconfigDto.setParamName(paramName);
            pmgBatPersonSysconfigDto.setParamCode(paramCode);
            pmgBatPersonSysconfigDto.setParkId(parkId + "");
            pmgBatPersonSysconfigDto.setParamType(paramType);
            iPmgBatPersonSysconfigService.saveValueByKey(pmgBatPersonSysconfigDto);

        }
    }


    private PmgBatPeopleTypeVO getVo(Long parkId, String bigType, String isSwitch) {
        QueryWrapper<PmgBatPeopleType> queryWrapper = new QueryWrapper();
        queryWrapper.eq("park_id", parkId);
        queryWrapper.eq("big_type", bigType);
        List<PmgBatPeopleType> pmgBatPeopleTypeList = this.baseMapper.selectList(queryWrapper);

        PmgBatPeopleTypeVO pmgBatPeopleTypeVO = new PmgBatPeopleTypeVO();
        pmgBatPeopleTypeVO.setListPmgBatPeopleType(pmgBatPeopleTypeList);

        LambdaQueryWrapper<PmgBatPersonSysconfig> queryWrapperSwitch = new LambdaQueryWrapper();
        queryWrapperSwitch.eq(PmgBatPersonSysconfig::getParkId, parkId);
        queryWrapperSwitch.eq(PmgBatPersonSysconfig::getParamCode, isSwitch);
        PmgBatPersonSysconfig pmgBatPersonSysconfigSwitch = iPmgBatPersonSysconfigService.getOne(queryWrapperSwitch);

        if (pmgBatPersonSysconfigSwitch == null) {

            saveVBK(parkId, 0, bigType);

            pmgBatPeopleTypeVO.setIsSwitch(0);
        } else {
            if ("1".equals(pmgBatPersonSysconfigSwitch.getParamValue())) {
                pmgBatPeopleTypeVO.setIsSwitch(1);
            } else {
                pmgBatPeopleTypeVO.setIsSwitch(0);
            }
        }

        pmgBatPeopleTypeVO.setBigType(bigType);
        pmgBatPeopleTypeVO.setParkId(parkId);

        return pmgBatPeopleTypeVO;
    }

    @Override
    public List<PmgBatPeopleType> getPeopleTypeByParkIdAndBigType(PmgBatPeopleTypeDTO pmgBatPeopleType) {
        QueryWrapper<PmgBatPeopleType> queryWrapper = new QueryWrapper();
        queryWrapper.eq("park_id", pmgBatPeopleType.getParkId());
        queryWrapper.eq("big_type", pmgBatPeopleType.getBigType());
        List<PmgBatPeopleType> pmgBatPeopleTypeList = this.baseMapper.selectList(queryWrapper);
        return pmgBatPeopleTypeList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R submitPeopleType(PmgBatPeopleTypeDataVO pmgBatPeopleTypeDataVO) {

        if (pmgBatPeopleTypeDataVO.getData() == null) {
            throw new RuntimeException("缺少请求参数");
        }

        List<PmgBatPeopleTypeVO> listPmgBatPeopleTypeVO = pmgBatPeopleTypeDataVO.getData();

        boolean result = false;
        for (PmgBatPeopleTypeVO pmgBatPeopleTypeVO : listPmgBatPeopleTypeVO) {
            Integer isSwitch = pmgBatPeopleTypeVO.getIsSwitch();
            String bigType = pmgBatPeopleTypeVO.getBigType();
            Long parkId = pmgBatPeopleTypeVO.getParkId();

            saveVBK(parkId, isSwitch, bigType);


            List<PmgBatPeopleType> listPmgBatPeopleType = pmgBatPeopleTypeVO.getListPmgBatPeopleType();
            for (PmgBatPeopleType pmgBatPeopleType : listPmgBatPeopleType) {
                boolean update = this.saveOrUpdate(pmgBatPeopleType);
            }


        }


        return R.success();
    }

    private boolean saveVBK(Long parkId, Integer isSwitch, String bigType) {
        PmgBatPersonSysconfigDto pmgBatPersonSysconfigDto = new PmgBatPersonSysconfigDto();

        switch (bigType) {
            case "房源人员":
                pmgBatPersonSysconfigDto.setParamCode("switchFangYuanRenYuan");
                pmgBatPersonSysconfigDto.setParamName("是否开启房源人员");
                break;
            case "物业人员":
                pmgBatPersonSysconfigDto.setParamCode("switchWuYeRenYuan");
                pmgBatPersonSysconfigDto.setParamName("是否开启物业人员");
                break;
            case "外部人员":
                pmgBatPersonSysconfigDto.setParamCode("switchWaiBuRenYuan");
                pmgBatPersonSysconfigDto.setParamName("是否开启外部人员");
                break;
            case "特殊人员":
                pmgBatPersonSysconfigDto.setParamCode("switchTeShuRenYuan");
                pmgBatPersonSysconfigDto.setParamName("是否开启特殊人员");
                break;
            default:
                break;
        }

        pmgBatPersonSysconfigDto.setParkId(parkId + "");
        pmgBatPersonSysconfigDto.setParamValue(isSwitch + "");
        return iPmgBatPersonSysconfigService.saveValueByKey(pmgBatPersonSysconfigDto);
    }

    private void judgeAndAdd(Long parkId, String code, String name, String bigType) {
        QueryWrapper<PmgBatPeopleType> queryWrapper = new QueryWrapper();
        queryWrapper.eq("park_id", parkId);
        queryWrapper.eq("code", code);
        queryWrapper.eq("name", name);
        queryWrapper.eq("big_type", bigType);

        List<PmgBatPeopleType> pmgBatPeopleTypeList = this.baseMapper.selectList(queryWrapper);

        if (pmgBatPeopleTypeList != null && pmgBatPeopleTypeList.size() > 0) {

        } else {
            PmgBatPeopleType pmgBatPeopleType = new PmgBatPeopleType();
            pmgBatPeopleType.setCode(code);
            pmgBatPeopleType.setName(name);
            pmgBatPeopleType.setCreateTime(new Date());
            pmgBatPeopleType.setUpdateTime(new Date());
            pmgBatPeopleType.setParkId(parkId);
            pmgBatPeopleType.setBigType(bigType);

            pmgBatPeopleType.setIsCheck(0);
            pmgBatPeopleType.setIsOpen(0);

            if (bigType.equals("外部人员")) {
                pmgBatPeopleType.setUpdateType(0);
                pmgBatPeopleType.setUpdateDays(7);
                pmgBatPeopleType.setElevatorLimit("");
                pmgBatPeopleType.setDoorLimit("");
            }
            if (bigType.equals("特殊人员")) {
                pmgBatPeopleType.setIsCan(1);
                pmgBatPeopleType.setIsAlarm(0);
            }
            baseMapper.insert(pmgBatPeopleType);

        }
    }

    /**
     * 处理人脸分组
     *
     * @param pmgBatPeopleType 需要处理的数据
     * @param handleType       处理类型（add:添加、del:删除、update:修改）
     * @return
     */
    private PmgBatPeopleType handleFaceGroup(PmgBatPeopleType pmgBatPeopleType, String handleType) {
        // 组装调用数据
        Map<String, Object> requestMap = new HashMap<>(2);
        // 请求参数
        Map<String, Object> requestBody = new HashMap<String, Object>();
        if ("add".equals(handleType)) {
            requestMap.put("requestApi", HikApiUtil.ADD_FACE_GROUP);
            requestBody.put("name", pmgBatPeopleType.getName());
            requestBody.put("description", pmgBatPeopleType.getName());
            requestMap.put("body", requestBody);
            R<Map<String, String>> result = commonHikClient.commonHikMethod(requestMap);
            if (result.getCode() == 0) {
                pmgBatPeopleType.setCode(result.getData().get("indexCode"));
            }
        }
        if ("update".equals(handleType)) {
            requestMap.put("requestApi", HikApiUtil.UPDATE_FACE_GROUP);
            requestBody.put("indexCode", pmgBatPeopleType.getCode());
            requestBody.put("name", pmgBatPeopleType.getName());
            requestMap.put("body", requestBody);
            requestBody.put("description", pmgBatPeopleType.getName());
            R<Map<String, String>> result = commonHikClient.commonHikMethod(requestMap);
        }
        if ("del".equals(handleType)) {
            requestMap.put("requestApi", HikApiUtil.DEL_FACE_GROUP);
            String[] indexCodes = {pmgBatPeopleType.getCode()};
            requestBody.put("indexCodes", indexCodes);
            requestMap.put("body", requestBody);
            commonHikClient.commonHikMethod(requestMap);
        }
        return pmgBatPeopleType;
    }
}
