package com.zhongshu.card.server.core.service.devices.permiss;

import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.zhongshu.card.client.model.devices.permiss.*;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.client.type.device.TimeSlotType;
import com.zhongshu.card.server.core.dao.devices.PermissSettingDao;
import com.zhongshu.card.server.core.dao.devices.PermissTimeSlotDao;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.domain.devices.permiss.PermissSetting;
import com.zhongshu.card.server.core.domain.devices.permiss.PermissTimeSlot;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.service.base.CommonService;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限时间段管理
 *
 * @author TRX
 * @date 2024/12/19
 */
@Slf4j
@Service
public class PermissTimeSlotService extends SuperService {

    @Autowired
    private PermissTimeSlotDao permissTimeSlotDao;

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private PermissSettingDao permissSettingDao;

    @Autowired
    private CommonService commonService;

    public ResultContent saveInfo(PermissTimeSlotParam param) {
        Assert.hasText(param.getProjectOid(), "projectOid不能为空");
        if (param.getType() == null) {
            param.setType(TimeSlotType.Week);
        }
        PermissTimeSlot entity = null;
        if (StringUtils.isNotEmpty(param.getId())) {
            entity = permissTimeSlotDao.findTopById(param.getId());
            if (ObjectUtils.isEmpty(entity)) {
                return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
            }
            initUpdateEntity(entity);
        } else {
            if (param.getState() == null) {
                param.setState(DataState.Enable);
            }
            entity = new PermissTimeSlot();
            initEntityNoCheckOid(entity);
        }
        BeanUtils.copyProperties(param, entity);

        List<TimeSlotWeekModel> timeSlotWeekModels = param.getTimeSlotWeekModels();
        if (ObjectUtils.isNotEmpty(timeSlotWeekModels)) {
            timeSlotWeekModels.stream().forEach(timeSlotWeekModel -> {
                List<TimeSlotModel> timeSlots = timeSlotWeekModel.getTimeSlots();
                if (ObjectUtils.isNotEmpty(timeSlots)) {
                    timeSlots.stream().forEach(timeSlotModel -> {
                        if (StringUtils.isNotEmpty(timeSlotModel.getStartTime())) {
                            timeSlotModel.setStartTimeNumber(Integer.parseInt(timeSlotModel.getStartTime().replace(":", "")));
                        }
                        if (StringUtils.isNotEmpty(timeSlotModel.getEndTime())) {
                            timeSlotModel.setEndTimeNumber(Integer.parseInt(timeSlotModel.getEndTime().replace(":", "")));
                        }
                    });
                }
            });
        }
        permissTimeSlotDao.save(entity);
        return ResultContent.buildSuccess();
    }

    public ResultContent<Page<PermissTimeSlotModel>> page(PermissTimeSlotSearch param, Pageable pageable) {
        String projectOid = param.getProjectOid();
        Organization organization = organizationDao.findTopByOid(projectOid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail("projectOid不存在");
        }
        Page<PermissTimeSlot> page = permissTimeSlotDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    public ResultContent<Page<PermissTimeSlotSimpleModel>> pageSelect(PermissTimeSlotSearch param, Pageable pageable) {
        String projectOid = param.getProjectOid();
        Organization organization = organizationDao.findTopByOid(projectOid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail("projectOid不存在");
        }
        Page<PermissTimeSlot> page = permissTimeSlotDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toSimpleModel));
    }

    public ResultContent deleteInfo(String id) {
        PermissTimeSlot entity = permissTimeSlotDao.findTopById(id);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        permissTimeSlotDao.delete(entity);
        return ResultContent.buildSuccess();
    }

    public ResultContent<PermissTimeSlotModel> getDetailInfo(String id) {
        PermissTimeSlot entity = permissTimeSlotDao.findTopById(id);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        return ResultContent.buildSuccess(toModel(entity));
    }

    public ResultContent changeState(String id, DataState state) {
        PermissTimeSlot entity = permissTimeSlotDao.findTopById(id);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        entity.setState(state);
        permissTimeSlotDao.save(entity);
        return ResultContent.buildSuccess();
    }

    public void updateTimeSlotAboutPermiss(PermissTimeSlot timeSlot) {
        if (ObjectUtils.isNotEmpty(timeSlot)) {
            List<PermissSetting> permissSettingList = permissSettingDao.findByTimeSlot(timeSlot);
            List<String> permissSettingIds = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(permissSettingList)) {
                permissSettingIds = permissSettingList.stream().map(it -> it.getId()).collect(Collectors.toList());
            }
            Map<String, Object> standardData = new HashMap<>();
            standardData.put("permissSettingIds", permissSettingIds);
            commonService.updateData(timeSlot.getId(), standardData, PermissTimeSlot.class.getSimpleName());
        }
    }

    private PermissTimeSlotModel toModel(PermissTimeSlot entity) {
        PermissTimeSlotModel model = new PermissTimeSlotModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }

    public PermissTimeSlotSimpleModel toSimpleModel(PermissTimeSlot entity) {
        PermissTimeSlotSimpleModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new PermissTimeSlotSimpleModel();
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }

}
