package com.bocloud.ims.service.config;

import com.bocloud.cmp.model.DictionaryBean;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.entity.common.Dictionary;
import com.bocloud.ims.interfaces.config.DictService;
import com.bocloud.ims.repository.resource.DictionaryRepository;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 字典服务实现类
 *
 * @author dmw
 */
@Service("dictService")
public class DictServiceImpl implements DictService {

    private static Logger logger = LoggerFactory.getLogger(DictServiceImpl.class);
    @Autowired
    private DictionaryRepository dictionaryRepository;
    @Autowired
    private LockFactory lockFactory;

    @Override
    public BocloudResult<List<Map<String, Object>>> list(String value) {
        try {
            List<Map<String, Object>> data = Lists.newArrayList();
            List<Dictionary> dicts = dictionaryRepository.dictionaries(value);
            for (Dictionary dict : dicts) {
                Map<String, Object> map = Maps.newHashMap();
                map.put(Common.ID, dict.getId());
                map.put(Common.NAME, dict.getName());
                map.put(Common.VALUE, dict.getValue());
                map.put("pvalue", dict.getPvalue());
                List<Dictionary> children = dictionaryRepository.dictionaries(dict.getValue());
                if (null != children && !children.isEmpty()) {
                    map.put("children", "[]");
                }
                data.add(map);
            }
            return new BocloudResult<>(true, data, "查询成功");
        } catch (Exception e) {
            logger.error("list dictionary fail:", e);
            return new BocloudResult<>(false, "查询失败", "", "");
        }
    }

    @Override
    public BocloudResult<List<Dictionary>> listChild(String pid) {
        try {
            List<Dictionary> dicts = this.dictionaryRepository.listChildren(pid);
            return new BocloudResult<>(true, dicts, "success");
        } catch (Exception e) {
            logger.error("List Children Dictionary exception:", e);
            return new BocloudResult<>(false, "查询失败", "505", "");
        }
    }

    @Override
    public BocloudResult create(Dictionary dictionary) {
        try {
            boolean existValue = dictionaryRepository.existValue(dictionary.getValue(), dictionary.getPvalue());
            if (existValue) {
                return new BocloudResult<>(false, "内容已存在，添加失败");
            }
            dictionaryRepository.save(dictionary);
            return new BocloudResult<>(true, dictionary, "保存成功!");
        } catch (Exception e) {
            logger.error("create dictionary failure:", e);
            return new BocloudResult<>(false, "保存失败!");
        }
    }

    @Override
    public BocloudResult remove(Long id) {
        String path = Dictionary.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Dictionary dictionary = dictionaryRepository.query(id);
            if (null == dictionary) {
                return new BocloudResult<>(false, "数据不存在!");
            }
            List<Dictionary> list = dictionaryRepository.dictionaries(dictionary.getValue());
            if (!ListTool.isEmpty(list)) {
                return new BocloudResult<>(false, "存在子项无法删除");
            }
            Boolean result = dictionaryRepository.delete(Dictionary.class, dictionary.getId());
            return result ? new BocloudResult<>(true, "删除成功!") : new BocloudResult<>(false, "删除失败!");
        } catch (Exception e) {
            logger.error("Remove dictionary error:", e);
            return new BocloudResult<>(false, "删除失败");
        }
    }

    @Override
    public BocloudResult modify(DictionaryBean bean) {
        String path = Dictionary.class.getSimpleName() + "_" + bean.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Dictionary dictionary = dictionaryRepository.query(bean.getId());
            if (null == dictionary) {
                return new BocloudResult<>(false, "数据不存在!");
            }
            BeanUtils.copyProperties(bean, dictionary);
            dictionaryRepository.update(dictionary);
            return new BocloudResult<>(true, dictionary, "修改成功!");
        } catch (Exception e) {
            logger.error("Modify server fail:", e);
            return new BocloudResult<>(false, "修改失败");
        }
    }

    @Override
    public BocloudResult<List<Dictionary>> childTree(String pid) {
        try {
            List<Dictionary> dicts = this.dictionaryRepository.listChildren(pid);
            List<Dictionary> result = Lists.newArrayList();
            for (Object object : dicts) {
                Dictionary dictionary = (Dictionary) object;
                List<Dictionary> list = dictionaryRepository.listChildren(dictionary.getValue());
                if (!list.isEmpty()) {
                    dictionary.setChildren(new ArrayList());
                }
                result.add(dictionary);
            }
            return new BocloudResult<>(true, result, "success");
        } catch (Exception e) {
            logger.error("List Children Dictionary exception:", e);
            return new BocloudResult<>(false, "查询失败", "505", "");
        }
    }
}