package com.engine.organization.service.impl;

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.TreeData;
import com.engine.organization.entity.fieldset.vo.TypeTreeVO;
import com.engine.organization.entity.scheme.dto.SchemeDTO;
import com.engine.organization.entity.scheme.param.SchemeSearchParam;
import com.engine.organization.entity.scheme.po.SchemePO;
import com.engine.organization.entity.scheme.vo.SchemeTableVO;
import com.engine.organization.mapper.scheme.SchemeMapper;
import com.engine.organization.service.SchemeService;
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.*;
import java.util.stream.Collectors;

/**
 * @Author dxfeng
 * @description:
 * @Date 2022/5/9
 * @Version V1.0
 **/
public class SchemeServiceImpl extends Service implements SchemeService {

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

    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.RefreshScheme("jcl_org_scheme");
        OrganizationWeaTable<SchemeTableVO> table = new OrganizationWeaTable<>(user, SchemeTableVO.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 save(SchemeSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        List<SchemePO> list = getSchemeMapper().listByNo(Util.null2String(param.getSchemeNo()));
        OrganizationAssert.isEmpty(list, "编号不允许重复");
        SchemePO schemePO = SchemeDTO.convertParamToPO(param, (long) user.getUID());
        return getSchemeMapper().insertIgnoreNull(schemePO);
    }

    @Override
    public int updateScheme(SchemeSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        SchemePO schemePO = SchemeDTO.convertParamToPO(param, (long) user.getUID());
        // 更新前先查询下旧编号，
        String oldSchemeNo = getSchemeMapper().getSchemeByID(schemePO.getId()).getSchemeNo();
        if (!oldSchemeNo.equals(schemePO.getSchemeNo())) {
            List<SchemePO> list = getSchemeMapper().listByNo(Util.null2String(schemePO.getSchemeNo()));
            OrganizationAssert.isEmpty(list, "编号不允许重复");
        }
        return getSchemeMapper().updateScheme(schemePO);
    }

    @Override
    public int updateForbiddenTagById(SchemeSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        SchemePO schemePO = SchemePO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).build();
        return getSchemeMapper().updateForbiddenTagById(schemePO);
    }


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


    @Override
    public Map<String, Object> getSchemeForm(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 schemeNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "方案名称", "schemeName");
        schemeNameCondition.setRules("required|string");
        SearchConditionItem schemeNoCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "方案编号", "schemeNo");
        schemeNoCondition.setRules("required|string");
        SearchConditionItem textareaItem = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 200, "方案说明", "schemeDescription");

        // 编辑状态下赋值操作
        String id = Util.null2String(params.get("id"));
        if (!StringUtil.isEmpty(id)) {
            SchemePO schemePO = getSchemeMapper().getSchemeByID(Integer.parseInt(id));
            OrganizationAssert.notNull(schemePO, "选择的数据不存在，或数据已删除");
            schemeNameCondition.setValue(schemePO.getSchemeName());
            schemeNoCondition.setValue(schemePO.getSchemeNo());
            textareaItem.setValue(schemePO.getSchemeDescription());

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

        selectItems.add(schemeNoCondition);
        selectItems.add(schemeNameCondition);
        selectItems.add(textareaItem);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

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

    @Override
    public List<TypeTreeVO> getTreeData() {
        ArrayList<TreeData> treeDataList = getSchemeMapper().getTreeData();
        TypeTreeVO build = TypeTreeVO.builder()
                .childs(treeDataList.stream().map(e ->
                        TypeTreeVO.builder()
                                .domid(e.getKey())
                                .key(Long.parseLong(e.getKey()))
                                .name(e.getStatus() == 0 ? e.getTitle() : e.getTitle()+"(已禁用)")
                                .build()).collect(Collectors.toList()))
                .haschild(true)
                .domid("-1")
                .key(-1L)
                .name("全部方案").build();
        List<TypeTreeVO> typeTreeVOS = new ArrayList<>();
        typeTreeVOS.add(build);
        return typeTreeVOS;
    }


    /**
     * 查询条件
     *
     * @param params
     * @return
     */
    private String buildSqlWhere(Map<String, Object> params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where delete_type ='0' ";
        //String sqlWhere = " where 1 = 1 ";
        String name = (String) params.get("schemeName");
        if (StringUtils.isNotBlank(name)) {
            sqlWhere += " AND scheme_name " + dbType.like(name);
        }
        String no = (String) params.get("schemeNo");
        if (StringUtils.isNotBlank(no)) {
            sqlWhere += " AND scheme_no " + dbType.like(no);
        }
        return sqlWhere;
    }


}
