package com.artfess.manage.base;


import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.context.BaseContext;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.StringUtil;
import com.artfess.uc.dao.OrgDao;
import com.artfess.uc.dao.UserDao;
import com.artfess.uc.manager.OrgManager;
import com.artfess.uc.model.Org;
import com.artfess.uc.model.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.api.client.util.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物资分类 前端控制器
 *
 * @author 超级管理员
 * @company 阿特菲斯信息技术有限公司
 * @email wujl
 * @since 2022-07-21
 */
@Service
public class ManageCommonService implements ApplicationContextAware {

    private ApplicationContext ctx;
    @Resource
    private BaseContext baseContext;


    public static final String orgRoot = "96240625-934F-490B-8AA6-0BC775B18468";

    @Resource
    OrgDao orgDao;


    @Resource
    UserDao userDao;

    @Autowired
    OrgManager orgService;

    public List<Object> findSelectOptions(String name, String query) {
        String beanName = name.substring(0, name.indexOf("."));
        String methodName = name.substring(name.indexOf(".") + 1);
        Object bean = ctx.getBean(beanName);
        if (bean != null) {
            if (query != null) {
                return ReflectUtil.invoke(bean, methodName, query);
            } else {
                return ReflectUtil.invoke(bean, methodName);
            }
        }
        return new ArrayList<Object>();
    }

    public Object getfindSelectOptionsLabel(String name, String valueAttribute, String labelAttribute, Object val) {
        List<Object> options = this.findSelectOptions(name, null);
        for (Object o : options) {
            Object v = null;

            if (o instanceof JSONObject) {
                v = ((JSONObject) o).get(valueAttribute);
            } else {
                v = ReflectUtil.getFieldValue(o, valueAttribute);
            }
            if (v != null && v.equals(val)) {
                if (o instanceof JSONObject) {
                    return ((JSONObject) o).get(labelAttribute);
                } else {
                    return ReflectUtil.getFieldValue(o, labelAttribute);
                }

            }
        }
        return null;
    }


    /**
     * 查询综管局组织
     *
     * @return
     */
    public List<Org> findZGJOrg() {
        QueryWrapper<Org> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PARENT_ID_", orgRoot);
        return orgDao.selectList(queryWrapper);
    }

    public List<TreeNode<String>> getAllOrgTreeNodeList() {
        List<TreeNode<String>> r = new ArrayList<>();
        List<Org> rootOrgList = orgService.getOrgsByparentId("1");
        if (rootOrgList.size() == 0) {
            rootOrgList = orgService.getOrgsByparentId("0");
        }
        Org d = rootOrgList.get(0);
        TreeNode<String> root = new TreeNode(d.getId(), "0", d.getName(), (d.getOrderNo() != null ? d.getOrderNo().intValue() : 999));
        r.add(root);
        r.addAll(findchildrenNode(root.getId()));
        return r;
    }

    /**
     * 根据父ID查找下级节点
     *
     * @param pid
     * @return
     */
    public List<TreeNode<String>> findchildrenNode(String pid) {
        List<Org> childrenOrg = orgService.getOrgsByparentId(pid);
        List<TreeNode<String>> children = new ArrayList();
        childrenOrg.stream().forEach(child -> {
            TreeNode<String> c = new TreeNode(child.getId(), pid, child.getName(), (child.getOrderNo() != null ? child.getOrderNo().intValue() : 999));
            children.add(c);
            children.addAll(findchildrenNode(child.getId()));
        });
        return children;
    }


    public JSONArray getAllUsers(String orgId) {
        JSONArray r = JSONUtil.createArray();
        List<User> users = Lists.newArrayList();
        if(StringUtil.isEmpty(orgId)) {
            users = userDao.selectList(null);
        }else{
            Map<String, String> map = Maps.newHashMap();
            map.put("orgId", orgId);
            users = userDao.getOrgUsers(map);
        }

        for (User u : users) {
            List<Org> uOrgs = orgDao.getOrgListByUserId(u.getId());
            System.out.println(uOrgs + "===========uOrgs===========" + u.getUserId());
            Org uOrg = null;
            if (uOrgs.size() > 0) {
                uOrg = uOrgs.get(0);
            } else {
                uOrg = new Org();
            }
            r.add(JSONUtil.createObj().putOpt("id", u.getId())
                    .putOpt("fullname", u.getFullname())
                    .putOpt("account", u.getAccount())
                    .putOpt("orgId", uOrg.getId())
                    .putOpt("orgName", uOrg.getName())
            );
        }
        return r;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }
}
