package com.engine.organization.service.impl;

import com.api.browser.bean.BrowserBean;
import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.core.impl.Service;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.DeleteParam;
import com.engine.organization.entity.TopTab;
import com.engine.organization.entity.TreeData;
import com.engine.organization.entity.scheme.dto.LevelDTO;
import com.engine.organization.entity.scheme.param.LevelSearchParam;
import com.engine.organization.entity.scheme.po.LevelPO;
import com.engine.organization.entity.scheme.vo.LevelTableVO;
import com.engine.organization.mapper.scheme.LevelMapper;
import com.engine.organization.mapper.scheme.SchemeMapper;
import com.engine.organization.service.LevelService;
import com.engine.organization.util.*;
import com.engine.organization.util.db.DBType;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.StringUtil;
import weaver.general.Util;

import java.util.*;


/**
 * @description:
 * @author:dxfeng
 * @createTime: 2022/05/10
 * @version: 1.0
 */
public class LevelServiceImpl extends Service implements LevelService {

    private static final String RIGHT_NAME = "Level:All";

    private LevelMapper getLevelMapper() {
        return MapperProxyFactory.getProxy(LevelMapper.class);
    }

    private SchemeMapper getSchemeMapper() {
        return MapperProxyFactory.getProxy(SchemeMapper.class);
    }

    @Override
    public Map<String, Object> listPage(Map<String, Object> params) {
        Map<String, Object> resultMap = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        resultMap.put("hasRight", hasRight);
        if (!hasRight) {
            return resultMap;
        }
        // 刷新引用状态
        RefreshIsUsedUtil.RefreshLevel("jcl_org_level");
        OrganizationWeaTable<LevelTableVO> table = new OrganizationWeaTable<>(user, LevelTableVO.class);
        String sqlWhere = buildSqlWhere(params);
        table.setSqlwhere(sqlWhere);
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();
        resultMap.putAll(result.getResultMap());
        return resultMap;
    }


    @Override
    public int saveLevel(LevelSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        List<LevelPO> list = getLevelMapper().listByNo(Util.null2String(param.getLevelNo()));
        OrganizationAssert.isTrue(checkRepeatNo(param.getSchemeId(), param.getLevelNo(), null), "同一等级方案下编号不能重复");
        LevelPO levelPO = LevelDTO.convertParamToPO(param, (long) user.getUID());
        return getLevelMapper().insertIgnoreNull(levelPO);
    }

    @Override
    public int updateLevel(LevelSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        LevelPO levelPO = LevelDTO.convertParamToPO(param, (long) user.getUID());
        OrganizationAssert.isTrue(checkRepeatNo(levelPO.getSchemeId(), levelPO.getLevelNo(), levelPO.getId()), "同一等级方案下编号不能重复");
        return getLevelMapper().updateLevel(levelPO);
    }

    @Override
    public int updateForbiddenTagById(LevelSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        LevelPO levelPO = LevelPO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).build();
        return getLevelMapper().updateForbiddenTagById(levelPO);
    }

    @Override
    public int deleteByIds(Collection<Long> ids) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notEmpty(ids, "请选择要删除的数据");
        return getLevelMapper().deleteByIds(ids);
    }


    @Override
    public Map<String, Object> getSearchCondition(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> conditionItems = new ArrayList<>();
        SearchConditionItem browserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "等级方案", "161", "schemeId", "schemeBrowser");
        SearchConditionItem levelNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "名称", "levelName");
        conditionItems.add(browserItem);
        conditionItems.add(levelNameCondition);
        addGroups.add(new SearchConditionGroup("高级搜索条件", true, conditionItems));
        apiDatas.put("conditions", addGroups);
        return apiDatas;
    }


    @Override
    public Map<String, Object> getLevelForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionItem> selectItems = new ArrayList<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        String id = Util.null2String(params.get("id"));
        String schemeId = Util.null2String(params.get("schemeId"));
        SearchConditionItem levelNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "名称", "levelName");
        levelNameCondition.setRules("required|string");
        SearchConditionItem levelNoCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "编号", "levelNo");
        levelNoCondition.setRules("required|string");
        SearchConditionItem descriptionCondition = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 200, "描述说明", "description");
        SearchConditionItem browserItem = OrganizationFormItemUtil.browserItem(user, 2, 17, 3, false, "等级方案", "161", "schemeId", "schemeBrowser");
        BrowserBean browserBean = browserItem.getBrowserConditionParam();
        if (StringUtils.isNotBlank(schemeId) && !"-1".equals(schemeId) && StringUtil.isEmpty(id)) {
            browserItem.setValue(schemeId);
            List<Map<String, Object>> maps = getSchemeMapper().listSchemesByIds(DeleteParam.builder().ids(schemeId).build().getIds());
            browserBean.setReplaceDatas(maps);
            browserItem.setBrowserConditionParam(browserBean);
        }
        browserItem.setRules("required|string");
        // 编辑状态下赋值操作
        if (!StringUtil.isEmpty(id)) {
            LevelPO levelPO = getLevelMapper().getLevelByID(Integer.parseInt(id));
            OrganizationAssert.notNull(levelPO, "选择的数据不存在，或数据已删除");

            levelNameCondition.setValue(levelPO.getLevelName());
            levelNoCondition.setValue(levelPO.getLevelNo());
            descriptionCondition.setValue(levelPO.getDescription());
            browserItem.setValue(levelPO.getSchemeId());

            List<Map<String, Object>> maps = getSchemeMapper().listSchemesByIds(DeleteParam.builder().ids(levelPO.getSchemeId().toString()).build().getIds());

            browserBean.setReplaceDatas(maps);
            browserItem.setBrowserConditionParam(browserBean);
            // 编辑状态下,编号只读
            // levelNoCondition.setViewAttr(1);
        }

        selectItems.add(levelNoCondition);
        selectItems.add(levelNameCondition);
        selectItems.add(descriptionCondition);
        selectItems.add(browserItem);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

    @Override
    public Map<String, List<MenuBtn>> getTableBtn() {
        return MenuBtn.getCommonBtnDatas();
    }

    @Override
    public Map<String, Object> getTabInfo() {
        Map<String, Object> apiDatas = new HashMap<>();
        List<TopTab> topTabs = new ArrayList<>();
        topTabs.add(TopTab.builder().color("#000000").groupId("flowAll").showcount(true).title("全部").viewCondition("-1").build());
        topTabs.add(TopTab.builder().color("#ff3232").groupId("enable").showcount(true).title("启用").viewCondition("0").build());
        topTabs.add(TopTab.builder().color("#fea468").groupId("disable").showcount(true).title("禁用").viewCondition("1").build());
        apiDatas.put("topTabs", topTabs);

        HashMap<String, Integer> countMap = new HashMap<>();
        countMap.put("flowAll", getLevelMapper().getCountByTag(-1));
        countMap.put("enable", getLevelMapper().getCountByTag(0));
        countMap.put("disable", getLevelMapper().getCountByTag(1));

        apiDatas.put("topTabCount", countMap);
        return apiDatas;
    }

    @Override
    public TreeData getTreeData() {
        ArrayList<TreeData> treeDataList = getLevelMapper().getTreeData();
        return TreeData.builder().children(treeDataList).title("职等").key("-1").build();
    }

    /**
     * 查询条件
     *
     * @param params
     * @return
     */
    private String buildSqlWhere(Map<String, Object> params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where t.delete_type ='0' ";
        String levelName = (String) params.get("levelName");
        if (StringUtils.isNotBlank(levelName)) {
            sqlWhere += " AND t.level_name " + dbType.like(levelName);
        }
        String schemeId = (String) params.get("schemeId");
        if (StringUtils.isNotBlank(schemeId) && !"-1".equals(schemeId)) {
            sqlWhere += " AND t.scheme_id = '" + schemeId + "'";
        }
        String viewCondition = (String) params.get("viewCondition");
        // -1:全部、0:启用、1:禁用
        if (StringUtils.isNotBlank(viewCondition) && !"-1".equalsIgnoreCase(viewCondition)) {
            sqlWhere += " AND t.forbidden_tag = '" + viewCondition + "'";
        }
        return sqlWhere;
    }

    /**
     * 校验重复编号
     */
    private boolean checkRepeatNo(Long schemeId, String no, Long id) {
        return 0 == getLevelMapper().checkRepeatNo(schemeId, no, id);
    }
}
