package com.eversec.dynamic;

import com.eversec.common.PageBean;
import com.eversec.dynamic.entity.DnyAttr;
import com.eversec.dynamic.entity.DnyCate;
import com.eversec.dynamic.entity.DnyV;

import java.util.List;
import java.util.Map;

/**
 * Created by liangxianyou at 2018/09/21
 */
public class DnyService {

    private DnyMapper dnyMapper;

    /**
     * 保存类型及属性值
     */
    public void save(DnyCate dnyCate){
        dnyMapper.save(dnyCate);

        List<DnyV> vs = dnyMapper.findAttrV(dnyCate);

        //save attr
        Map<String, Object> attach = dnyCate.getAttach();
        for (String k : attach.keySet()) {
            String v = dnyCate.get(k);

            DnyAttr attr = dnyCate.getAttr(k);

            if (attr == null){
                continue;
            }

            DnyV dnyV = vs.stream().filter(x -> x.getAttrId() == attr.getAttrId()).findFirst().get();
            if (dnyV != null && dnyV.getV().equals(v)) {
                continue;
            }

            if (dnyV == null){
                dnyV = dnyCate.createDnyV(attr, v);
            }else {
                dnyV.setV(v);
            }

            dnyMapper.saveAttrV(dnyV);
        }
    }

    /**
     * 查询列表数据
     * @param dnyCate
     * @param pn
     * @param ps
     * @return
     */
    public PageBean findList(DnyCate dnyCate, int pn, int ps) {
        List<DnyCate> list = dnyMapper.findList(dnyCate, pn, ps);
        int count = dnyMapper.findCount(dnyCate);

        list.forEach(x-> setAttr(x));
        return new PageBean(list, count);
    }

    /**
     *
     * @param dnyCate
     * @return
     */
    public DnyCate findFirst(DnyCate dnyCate){
        List<DnyCate> list = dnyMapper.findList(dnyCate, 0, 1);
        DnyCate cate = list.size() > 0 ? list.get(0) : null;
        return setAttr(cate);
    }

    //通用设置属性 方法
    private DnyCate setAttr(DnyCate dnyCate){
        if (dnyCate == null) return null;

        List<DnyV> vs = dnyMapper.findAttrV(dnyCate);

        List<DnyAttr> attrs = dnyCate.getAttrs();
        vs.forEach(x->{
            DnyAttr dnyAttr = dnyCate.getAttr(x.getAttrId());
            if (dnyAttr != null){
                dnyCate.set(dnyAttr.getAttr(), x.getV());
            }
        });
        return dnyCate;
    }


    public void saveAttr(DnyAttr dnyAttr) {
        dnyMapper.saveAttr(dnyAttr);
    }
}
