package com.skr.mdm.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.skr.mdm.api.user.service.AuLabelService;
import com.skr.mdm.bean.qo.controller.UserManagerQO;
import com.skr.mdm.bean.vo.aumanage.AuDepartmentVO;
import com.skr.mdm.bean.vo.aumanage.AuLabelMessageVO;
import com.skr.mdm.bean.vo.aumanage.AuLabelUserInfoVO;
import com.skr.mdm.dao.AuDepartmentDao;
import com.skr.mdm.dao.AuLabelDao;
import com.skr.mdm.dao.AuLabelUserDao;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.entity.AuDepartmentDO;
import com.skr.mdm.entity.AuLabelDO;
import com.skr.mdm.entity.AuLabelUserDO;
import com.skr.mdm.enums.LogAdminTypeEnum;
import com.skr.mdm.handle.LogAdminHandler;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @outher tty
 * @date 2020/7/10 17:24
 **/
@Service
public class AuLabelServiceImpl extends ServiceImpl<AuLabelDao, AuLabelDO> implements AuLabelService {

    private static final String MODULE = "标签管理";

    @Autowired
    private AuLabelDao auLabelDao;
    @Autowired
    private AuLabelUserDao auLabelUserDao;
    @Autowired
    private AuDepartmentDao auDepartmentDao;
    @Autowired
    private LogAdminHandler logAdminHandler;

    @Override
    public ResponseResult listAuLabelManagement(UserManagerQO userManagerQO, Integer companyId) {
        Integer pageNumber = userManagerQO.getPageNumber();
        Integer pageSize = userManagerQO.getPageSize();
        String searchValue = userManagerQO.getSearchValue();
        Integer searchType = userManagerQO.getSearchType();
        ResponseResult result = null;
        LambdaQueryWrapper<AuLabelDO> queryWrapper = new LambdaQueryWrapper<AuLabelDO>()
                .eq(AuLabelDO::getCompanyId, companyId);
        List<AuLabelMessageVO> auLableMessages = new ArrayList<>();
        List<AuLabelDO> auLabelDos = null;
        if (null == pageNumber) {
            queryWrapper.orderByDesc(AuLabelDO::getUpdateTime);
            auLabelDos = auLabelDao.selectList(queryWrapper);
        } else {
            if (null != searchType) {
                if (searchType == 1) {
                    queryWrapper.like(AuLabelDO::getLabelName, searchValue);
                }
            }
            pageSize = null == pageSize ? 10 : pageSize;
            queryWrapper.orderByDesc(AuLabelDO::getUpdateTime);
            PageHelper.startPage(pageNumber, pageSize);
            auLabelDos = auLabelDao.selectList(queryWrapper);
        }
        for (AuLabelDO auLabelDo : auLabelDos) {
            StringBuilder stringBuilder = new StringBuilder();
            AuLabelMessageVO aulabelMessageVo = new AuLabelMessageVO();
            //  标签类型
            String labelType = auLabelDo.getLabelType();
            Integer id = auLabelDo.getId();
            aulabelMessageVo.setId(id);
            aulabelMessageVo.setLabelType(Integer.valueOf(labelType));
            aulabelMessageVo.setName(auLabelDo.getLabelName());
            HashMap<String, Object> content = new HashMap<>();
            if ("1".equals(labelType)) {
                // 标签类型 静态
                List<String> names = auLabelDao.listUserNameByAuLabId(id);
                if (names.size() > 0) {
                    Iterator<String> iterator = names.iterator();
                    while (iterator.hasNext()) {
                        String next = iterator.next();
                        stringBuilder.append(next);
                        if (iterator.hasNext()) {
                            stringBuilder.append("、");
                        }
                    }
                }
                content.put("data", stringBuilder.toString());
            } else if ("2".equals(labelType)) {
                // 动态类型
                stringBuilder.append("部门名称： ");
                String departmentIds = auLabelDo.getDepartmentId();
                if (null == departmentIds) {
                    continue;
                }
                String[] departments = departmentIds.split(",");
                ArrayList<String> departmentList = new ArrayList<>(Arrays.asList(departments));
                List<AuDepartmentDO> departmentDoList = auDepartmentDao.selectList(new QueryWrapper<AuDepartmentDO>()
                        .select("department_name").eq("company_id", companyId)
                        .in("id", departmentList));
                for (AuDepartmentDO auDepartmentDO : departmentDoList) {
                    stringBuilder.append(auDepartmentDO.getDepartmentName());
                    stringBuilder.append(",");
                }
                int i = stringBuilder.lastIndexOf(",");
                if (i > 0) {
                    stringBuilder = stringBuilder.replace(i - 1, stringBuilder.length(), ";");
                }
                String deviceStatus = auLabelDo.getDeviceStatus();
                if (StringUtils.isNotBlank(deviceStatus)) {
                    stringBuilder.append("设备状态:  ");
                    ArrayList<String> statusList = new ArrayList<>();
                    if (deviceStatus.contains(",")) {
                        statusList = new ArrayList<>(Arrays.asList(deviceStatus.split(",")));
                    } else {
                        statusList.add(deviceStatus);
                    }
                    Iterator<String> iterator = statusList.iterator();
                    while (iterator.hasNext()) {
                        String status = iterator.next();
                        switch (status) {
                            case "1":
                                stringBuilder.append("在线设备");
                                break;
                            case "2":
                                stringBuilder.append("离线设备");
                                break;
                            case "3":
                                stringBuilder.append("未激活设备");
                                break;
                            case "4":
                                stringBuilder.append("已丢失设备");
                                break;
                            default:
                                break;
                        }
                        if (iterator.hasNext()) {
                            stringBuilder.append(",");
                        }
                    }
                }
                content.put("data", stringBuilder.toString());
            }
            aulabelMessageVo.setContent(content);
            auLableMessages.add(aulabelMessageVo);
        }
        if (pageNumber == null) {
            result = ResponseResult.success(auLableMessages);
        } else {
            result = ResponseResult.success(PageUtil.getPageResult(auLableMessages));
        }
        return result;
    }

    @Override
    public ResponseResult addAuLabel(AuLabelDO auLabelDo, LoginAdminDTO admin) {
        try {
            Integer companyId = admin.getCompanyId();
            auLabelDo.setCompanyId(companyId);
            String labelName = auLabelDo.getLabelName();
            Long count = auLabelDao.selectCount(new QueryWrapper<AuLabelDO>().eq("label_name", labelName).eq("company_id", companyId));
            if (count > 0) {
                ResponseResult result = ResponseResult.failure();
                result.setMsg("标签名称重复");
                return result;
            }
            auLabelDao.insert(auLabelDo);
            AuLabelUserDO auLabelUserDo = new AuLabelUserDO();
            String labelType = auLabelDo.getLabelType();
            auLabelUserDo.setLabelId(auLabelDo.getId());
            auLabelUserDo.setCreateTime(new Date());

            // 静态
            if ("1".equals(labelType)) {
                Integer[] userIds = auLabelDo.getUserIds();
                List<Integer> userList = new ArrayList<>(Arrays.asList(userIds));
                auLabelUserDao.insertAuLabUser(auLabelUserDo, userList);
            }
            // 动态标签不需要 添加用户信息
            // log
            String content = "添加标签:".concat(labelName);
            logAdminHandler.log(admin, LogAdminTypeEnum.USER_TYPE.getLogType(), content, MODULE, null);
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.failure();
        }
    }

    @Override
    public ResponseResult delAuLabel(String auLabelId, LoginAdminDTO admin) {
        ArrayList<Object> auLabelIdList = new ArrayList<>();
        if (null != auLabelId && auLabelId.contains(",")) {
            auLabelIdList = new ArrayList<>(Arrays.asList(auLabelId.split(",")));
        } else {
            auLabelIdList.add(auLabelId);
        }
        //  删除标签主体
        int successCount = auLabelDao.delete(new LambdaUpdateWrapper<AuLabelDO>()
                .in(AuLabelDO::getId, auLabelIdList));
        //  删除标签用户信息
        auLabelUserDao.delete(new LambdaUpdateWrapper<AuLabelUserDO>().in(AuLabelUserDO::getLabelId, auLabelIdList));
        // log
        String content = "删除标签";
        logAdminHandler.log(admin, LogAdminTypeEnum.USER_TYPE.getLogType(), content, MODULE, null);
        return successCount > 0 ? ResponseResult.success() : ResponseResult.failure();
    }

    @Override
    public ResponseResult getAuLabelInfo(Integer aulabelId) {
        //获取标签信息
        AuLabelDO auLabelDo = auLabelDao.selectOne(new QueryWrapper<AuLabelDO>().eq("id", aulabelId));
        String labelType = auLabelDo.getLabelType();
        AuLabelMessageVO auLabelMessageVo = new AuLabelMessageVO();
        HashMap<String, Object> content = new HashMap<>();
        //静态标签
        if ("1".equals(labelType)) {
            List<AuLabelUserInfoVO> auLabelUserInfoBos = auLabelUserDao.ListUserByLabelId(aulabelId);
            content.put("msg", auLabelUserInfoBos);
        } else if ("2".equals(labelType)) {
            //动态标签
            String departmentId = auLabelDo.getDepartmentId();
            ArrayList<String> departmentList = new ArrayList<>();
            if (departmentId.contains(",")) {
                departmentList = new ArrayList<String>(Arrays.asList(departmentId.split(",")));
            } else {
                departmentList.add(departmentId);
            }
            List<AuDepartmentVO> departmentDoList = auDepartmentDao.selectDepartmentListByIds(departmentList);
            content.put("data", departmentDoList);
            String deviceStatus = auLabelDo.getDeviceStatus();
            if (null != deviceStatus) {
                content.put("msg", deviceStatus.contains(",") ? deviceStatus.split(",") : Collections.singletonList(deviceStatus));
            } else {
                content.put("msg", "");
            }

        }
        auLabelMessageVo.setContent(content);
        auLabelMessageVo.setId(aulabelId);
        auLabelMessageVo.setName(auLabelDo.getLabelName());
        auLabelMessageVo.setLabelType(Integer.valueOf(labelType));
        return ResponseResult.success(auLabelMessageVo);
    }

    @Override
    public ResponseResult updateAuLabel(AuLabelDO auLabelDo, LoginAdminDTO admin) {
        try {
            Long count = new LambdaQueryChainWrapper<>(auLabelDao)
                    .eq(AuLabelDO::getLabelName, auLabelDo.getLabelName())
                    .ne(AuLabelDO::getId, auLabelDo.getId())
                    .count();
            if (count > 0) {
                return ResponseResult.failure("标签名称重复");
            }
            String labelType = auLabelDo.getLabelType();
            Integer labelId = auLabelDo.getId();
            //查询出表现当前用户信息
            List<AuLabelUserInfoVO> auLabelUserInfoBos = auLabelUserDao.ListUserByLabelId(auLabelDo.getId());
            if ("1".equals(labelType)) {
                // 静态  获取前端选择是否有用户信息
                Integer[] userIds = auLabelDo.getUserIds();
                if (userIds.length > 0) {
                    List<Integer> userList = new ArrayList<>(Arrays.asList(userIds));
                    if (userIds != null && userList.size() > 0) {
                        auLabelUserDao.delete(new LambdaUpdateWrapper<AuLabelUserDO>()
                                .eq(AuLabelUserDO::getLabelId, auLabelDo.getId()));
                        AuLabelUserDO auLabelUserDo = new AuLabelUserDO();
                        auLabelUserDo.setLabelId(labelId);
                        auLabelUserDo.setCreateTime(new Date());
                        auLabelUserDao.insertAuLabUser(auLabelUserDo, userList);
                    }
                }
            } else if ("2".equals(labelType)) {
                // 修改为动态
                if (auLabelUserInfoBos.size() > 0) {
                    //之前有用户信息   删除
                    auLabelUserDao.delete(new QueryWrapper<AuLabelUserDO>().eq("label_id", labelId));
                }
            }
            auLabelDao.updateById(auLabelDo);
            // log
            String content = "修改标签:".concat(auLabelDo.getLabelName());
            logAdminHandler.log(admin, LogAdminTypeEnum.USER_TYPE.getLogType(), content, MODULE, null);
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.failure();
        }
    }
}
