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.sequence.dto.SequenceDTO;
import com.engine.organization.entity.sequence.param.SequenceSearchParam;
import com.engine.organization.entity.sequence.po.SequencePO;
import com.engine.organization.entity.sequence.vo.SequenceTableVO;
import com.engine.organization.mapper.scheme.SchemeMapper;
import com.engine.organization.mapper.sequence.SequenceMapper;
import com.engine.organization.service.SequenceService;
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/12
 * @version: 1.0
 */
public class SequenceServiceImpl extends Service implements SequenceService {

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

    private SequenceMapper getSequenceMapper() {
        return MapperProxyFactory.getProxy(SequenceMapper.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.RefreshSequence("jcl_org_sequence");
        OrganizationWeaTable<SequenceTableVO> table = new OrganizationWeaTable<>(user, SequenceTableVO.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 saveSequence(SequenceSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        List<SequencePO> list = getSequenceMapper().listByNo(Util.null2String(param.getSequenceNo()));
        OrganizationAssert.isEmpty(list, "编号不允许重复");
        SequencePO sequencePO = SequenceDTO.convertParamToPO(param, (long) user.getUID());
        return getSequenceMapper().insertIgnoreNull(sequencePO);
    }

    @Override
    public int updateSequence(SequenceSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        SequencePO sequencePO = SequenceDTO.convertParamToPO(param, (long) user.getUID());
        String oldSequenceNo = getSequenceMapper().getSequenceByID(sequencePO.getId()).getSequenceNo();
        if (!oldSequenceNo.equals(sequencePO.getSequenceNo())) {
            List<SequencePO> list = getSequenceMapper().listByNo(Util.null2String(sequencePO.getSequenceNo()));
            OrganizationAssert.isEmpty(list, "编号不允许重复");
        }
        return getSequenceMapper().updateSequence(sequencePO);
    }

    @Override
    public int updateForbiddenTagById(SequenceSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        SequencePO sequencePO = SequencePO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).build();
        return getSequenceMapper().updateForbiddenTagById(sequencePO);
    }

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


    @Override
    public Map<String, Object> getSequenceForm(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<>();
        SearchConditionItem sequenceNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "名称", "sequenceName");
        sequenceNameCondition.setRules("required|string");
        SearchConditionItem sequenceNoCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "编号", "sequenceNo");
        sequenceNoCondition.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");
        browserItem.setRules("required|string");

        // 编辑状态下赋值操作
        String id = Util.null2String(params.get("id"));
        if (!StringUtil.isEmpty(id)) {
            SequencePO sequencePO = getSequenceMapper().getSequenceByID(Integer.parseInt(id));
            OrganizationAssert.notNull(sequencePO, "选择的数据不存在，或数据已删除");

            sequenceNameCondition.setValue(sequencePO.getSequenceName());
            sequenceNoCondition.setValue(sequencePO.getSequenceNo());
            descriptionCondition.setValue(sequencePO.getDescription());
            browserItem.setValue(sequencePO.getSchemeId());

            BrowserBean browserBean = browserItem.getBrowserConditionParam();
            List<Map<String, Object>> maps = getSchemeMapper().listSchemesByIds(DeleteParam.builder().ids(sequencePO.getSchemeId().toString()).build().getIds());

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

        selectItems.add(sequenceNoCondition);
        selectItems.add(sequenceNameCondition);
        selectItems.add(descriptionCondition);
        selectItems.add(browserItem);
        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", getSequenceMapper().getCountByTag(-1));
        countMap.put("enable", getSequenceMapper().getCountByTag(0));
        countMap.put("disable", getSequenceMapper().getCountByTag(1));

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

    @Override
    public Map<String, Object> getSchemeInfo(Map<String, Object> params) {
        String sequenceId = Util.null2String(params.get("sequenceId"));
        SequencePO sequencePO = getSequenceMapper().getSequenceByID(Long.parseLong(sequenceId));
        List<Map<String, Object>> maps = getSchemeMapper().listSchemesByIds(DeleteParam.builder().ids(sequencePO.getSchemeId().toString()).build().getIds());
        return maps.get(0);
    }

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

}
