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.scheme.dto.GradeDTO;
import com.engine.organization.entity.scheme.param.GradeSearchParam;
import com.engine.organization.entity.scheme.po.GradePO;
import com.engine.organization.entity.scheme.vo.GradeTableVO;
import com.engine.organization.mapper.scheme.GradeMapper;
import com.engine.organization.mapper.scheme.LevelMapper;
import com.engine.organization.mapper.scheme.SchemeMapper;
import com.engine.organization.service.GradeService;
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/11
 * @version: 1.0
 */
public class GradeServiceImpl extends Service implements GradeService {

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

    private GradeMapper getGradeMapper() {
        return MapperProxyFactory.getProxy(GradeMapper.class);
    }

    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.RefreshGrade("jcl_org_grade");
        OrganizationWeaTable<GradeTableVO> table = new OrganizationWeaTable<>(user, GradeTableVO.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 saveGrade(GradeSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.isTrue(checkRepeatNo(param.getSchemeId(), param.getGradeNo(), null), "同一等级方案下编号不能重复");
        GradePO gradePO = GradeDTO.convertParamToPO(param, (long) user.getUID());
        return getGradeMapper().insertIgnoreNull(gradePO);
    }

    @Override
    public int updateGrade(GradeSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        GradePO gradePO = GradeDTO.convertParamToPO(param, (long) user.getUID());
        OrganizationAssert.isTrue(checkRepeatNo(gradePO.getSchemeId(), gradePO.getGradeNo(), gradePO.getId()), "同一等级方案下编号不能重复");
        return getGradeMapper().updateGrade(gradePO);
    }

    @Override
    public int updateForbiddenTagById(GradeSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        GradePO gradePO = GradePO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).build();
        return getGradeMapper().updateForbiddenTagById(gradePO);
    }

    @Override
    public int deleteByIds(Collection<Long> ids) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notEmpty(ids, "请选择要删除的数据");
        return getGradeMapper().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 gradeNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "名称", "gradeName");
        conditionItems.add(browserItem);
        conditionItems.add(gradeNameCondition);
        addGroups.add(new SearchConditionGroup("高级搜索条件", true, conditionItems));
        apiDatas.put("conditions", addGroups);
        return apiDatas;
    }


    @Override
    public Map<String, Object> getGradeForm(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 gradeNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "名称", "gradeName");
        gradeNameCondition.setRules("required|string");
        SearchConditionItem gradeNoCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "编号", "gradeNo");
        gradeNoCondition.setRules("required|string");
        SearchConditionItem descriptionCondition = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 200, "描述说明", "description");
        SearchConditionItem schemeBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 17, 3, false, "等级方案", "161", "schemeId", "schemeBrowser");
        schemeBrowserItem.setRules("required|string");
        BrowserBean schemeBrowserBean = schemeBrowserItem.getBrowserConditionParam();
        if (StringUtils.isNotBlank(schemeId) && !"-1".equals(schemeId) && StringUtil.isEmpty(id)) {
            schemeBrowserBean.setValue(schemeId);
            List<Map<String, Object>> maps = getSchemeMapper().listSchemesByIds(DeleteParam.builder().ids(schemeId).build().getIds());
            schemeBrowserBean.setReplaceDatas(maps);
            schemeBrowserItem.setBrowserConditionParam(schemeBrowserBean);
        }
        SearchConditionItem levelBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 17, 3, false, "职等", "162", "levelId", "LevelBrowser");
        levelBrowserItem.setRules("required|string");

        // 编辑状态下赋值操作
        if (!StringUtil.isEmpty(id)) {
            GradePO gradePO = getGradeMapper().getGradeByID(Integer.parseInt(id));
            OrganizationAssert.notNull(gradePO, "选择的数据不存在，或数据已删除");

            gradeNameCondition.setValue(gradePO.getGradeName());
            gradeNoCondition.setValue(gradePO.getGradeNo());
            descriptionCondition.setValue(gradePO.getDescription());
            schemeBrowserItem.setValue(gradePO.getSchemeId());
            levelBrowserItem.setValue(gradePO.getLevelId());

            List<Map<String, Object>> schemeMaps = getSchemeMapper().listSchemesByIds(DeleteParam.builder().ids(gradePO.getSchemeId().toString()).build().getIds());
            schemeBrowserBean.setReplaceDatas(schemeMaps);
            schemeBrowserItem.setBrowserConditionParam(schemeBrowserBean);

            BrowserBean levelBrowserBean = levelBrowserItem.getBrowserConditionParam();
            List<Map<String, Object>> levelMaps = getLevelMapper().listLevelsByIds(DeleteParam.builder().ids(gradePO.getLevelId()).build().getIds());
            levelBrowserBean.setReplaceDatas(levelMaps);
            long l = System.currentTimeMillis();
            Map<String, Object> completeParams = levelBrowserBean.getCompleteParams();
            completeParams.put("currenttime", l);
            completeParams.put("scheme_id_" + l, gradePO.getSchemeId());
            completeParams.put("level_id_" + l, "''");
            Map<String, Object> conditionDataParams = levelBrowserBean.getConditionDataParams();
            conditionDataParams.put("currenttime", l);
            conditionDataParams.put("scheme_id_" + l, gradePO.getSchemeId());
            conditionDataParams.put("level_id_" + l, "''");
            Map<String, Object> dataParams = levelBrowserBean.getDataParams();
            dataParams.put("currenttime", l);
            dataParams.put("scheme_id_" + l, gradePO.getSchemeId());
            dataParams.put("level_id_" + l, "''");
            Map<String, Object> destDataParams = levelBrowserBean.getDestDataParams();
            destDataParams.put("currenttime", l);
            destDataParams.put("scheme_id_" + l, gradePO.getSchemeId());
            destDataParams.put("level_id_" + l, "''");

            levelBrowserItem.setBrowserConditionParam(levelBrowserBean);

            levelBrowserItem.setRelatekey("schemeId");

            // 编辑状态下,编号只读
            // gradeNoCondition.setViewAttr(1);
        }

        selectItems.add(gradeNoCondition);
        selectItems.add(gradeNameCondition);
        selectItems.add(descriptionCondition);
        selectItems.add(schemeBrowserItem);
        selectItems.add(levelBrowserItem);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

    @Override
    public Map<String, List<MenuBtn>> getHasRight() {
        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", getGradeMapper().getCountByTag(-1));
        countMap.put("enable", getGradeMapper().getCountByTag(0));
        countMap.put("disable", getGradeMapper().getCountByTag(1));

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

    @Override
    public String getLevelId(Long id) {
        return id != null ? MapperProxyFactory.getProxy(GradeMapper.class).getGradeByID(id).getLevelId() : "";
    }

    /**
     * 查询条件
     *
     * @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 gradeName = (String) params.get("gradeName");
        if (StringUtils.isNotBlank(gradeName)) {
            sqlWhere += " AND t.grade_name " + dbType.like(gradeName);
        }
        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 == getGradeMapper().checkRepeatNo(schemeId, no, id);
    }

}
