package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.equipmanage.common.entity.FormGroup;
import com.yeejoin.equipmanage.mapper.FormGroupMapper;
import com.yeejoin.equipmanage.service.IFormGroupService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author DELL
 */
@Service
public class FormGroupServiceImpl extends ServiceImpl<FormGroupMapper, FormGroup> implements IFormGroupService {

    @Value("${systemctl.dict.allow-operation}")
    private String allowOperation;

    /**
     * @param groupCode
     * @Description 根据groupCode查询
     * @Return FormGroup
     * @Date 2020/12/18 10:01
     */
    @Override
    public FormGroup allowOperationByGroupCode(String groupCode) {
        FormGroup formGroup = this.getOne(new QueryWrapper<FormGroup>()
                .lambda()
                .eq(FormGroup::getGroupCode, groupCode));
        Optional.ofNullable(formGroup).orElseThrow(() -> new BadRequest("分组CODE查询formGroup不存在"));
        return formGroup;
    }

    @Override
    public FormGroup getByUniqueKey(String groupCode) {
        QueryWrapper<FormGroup> wrapper = new QueryWrapper<>();
        wrapper.eq("group_code", groupCode);
        return this.getOne(wrapper);
    }

    @Override
    public Map<String, Object> getAllOperation() {
        //1.数据字典查询、并list 转 map
        FeignClientResult<List<DictionarieValueModel>> dictValues = Systemctl.dictionarieClient.dictValues(allowOperation);
        Optional.ofNullable(dictValues).orElseThrow(() -> new BadRequest("查询字段数据为空"));
        List<DictionarieValueModel> values = dictValues.getResult();
        Map<String, DictionarieValueModel> dictMap = values.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, Function.identity()));
        //2.查询分组表数据，进行右键菜单数据组装
        List<FormGroup> formGroupList = this.list();
        Map<String, Object> returnMap = new HashMap<>();
        formGroupList.forEach(f -> {
            List<Map<String, Object>> tempList = Arrays.stream(f.getAllowOperation().split(",")).map(s -> {
                Map<String, Object> temp = new LinkedHashMap<>();
                temp.put("id", dictMap.get(s) == null ? null : dictMap.get(s).getDictDataKey());
                temp.put("icon", this.buildIcon(s));
                temp.put("operationType", dictMap.get(s) == null ? null : dictMap.get(s).getDictDataDesc());
                temp.put("name", dictMap.get(s) == null ? null : dictMap.get(s).getDictDataValue());
                temp.put("groupType", this.buildGroupType(s, f.getGroupType(), formGroupList));
                temp.put("groupCode", this.buildGroupCode(s, f.getGroupCode(), formGroupList));
                return temp;
            }).collect(Collectors.toList());
            returnMap.put(f.getGroupCode(), tempList);
        });
        //3.进行房间数据组装
        List<Map<String, Object>> roomList = formGroupList.stream().filter(f -> "room".equals(f.getGroupType())).map(e -> {
            Map<String, Object> temp = new LinkedHashMap<>();
            temp.put("id", e.getId());
            temp.put("icon", e.getGroupCode());
            temp.put("name", e.getGroupName());
            //房间类型 数据全部为新增，所以固定add,前端用来判断当前操作是打开页面还是删除操作
            temp.put("operationType", "add");
            temp.put("groupType", e.getGroupType());
            temp.put("groupCode", e.getGroupCode());
            return temp;
        }).collect(Collectors.toList());
        returnMap.put("room_add", roomList);
        return returnMap;
    }

    private String buildGroupType(String operationCode, String groupType, List<FormGroup> formGroupList) {
        String split = "_";
        if (operationCode.contains(split)) {
            String groupCode = operationCode.substring(0, operationCode.lastIndexOf(split));
            Optional<FormGroup> op = formGroupList.stream().filter(f -> f.getGroupCode().equals(groupCode)).findFirst();
            if (op.isPresent()) {
                return op.get().getGroupType();
            } else {
                return "";
            }
        } else {
            return groupType;
        }
    }

    private String buildGroupCode(String operationCode, String groupCode, List<FormGroup> formGroupList) {
        String split = "_";
        if (operationCode.contains(split)) {
            return operationCode.substring(0, operationCode.lastIndexOf(split));
        } else {
            return groupCode;
        }
    }

    private String buildIcon(String operationCode) {
        String split = "_";
        if (operationCode.contains(split)) {
            return operationCode.substring(0, operationCode.lastIndexOf(split));
        } else {
            return operationCode;
        }
    }
}
