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.TreeData;
import com.engine.organization.entity.fieldset.vo.TypeTreeVO;
import com.engine.organization.entity.hrmresource.po.ResourceItemClassPO;
import com.engine.organization.entity.hrmresource.po.ResourceItemPO;
import com.engine.organization.entity.hrmresource.vo.ResourceBasicInfoVO;
import com.engine.organization.mapper.hrmresource.ResourceBasicInfoMapper;
import com.engine.organization.service.ResourceBasicInfoService;
import com.engine.organization.util.HasRightUtil;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.OrganizationFormItemUtil;
import com.engine.organization.util.db.DBType;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author weaver_cl
 * @Description:
 * @Date 2022/8/23
 * @Version V1.0
 **/
public class ResourceBasicInfoServiceImpl extends Service implements ResourceBasicInfoService {

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

    private ResourceBasicInfoMapper getResourceBasicInfoMapper() {
        return MapperProxyFactory.getProxy(ResourceBasicInfoMapper.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;
        }
        OrganizationWeaTable<ResourceBasicInfoVO> table = new OrganizationWeaTable<>(user, ResourceBasicInfoVO.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 List<TypeTreeVO> getTreeData() {
        ArrayList<TreeData> treeDataList = getResourceBasicInfoMapper().getTreeData();
        TypeTreeVO build = TypeTreeVO.builder()
                .childs(treeDataList.stream().map(e ->
                        TypeTreeVO.builder()
                                .domid(e.getKey())
                                .key(Long.parseLong(e.getKey()))
                                .name(e.getTitle())
                                .build()).collect(Collectors.toList()))
                .haschild(true)
                .domid("-1")
                .key(-1L)
                .name("全部类型").build();
        List<TypeTreeVO> typeTreeVOS = new ArrayList<>();
        typeTreeVOS.add(build);
        return typeTreeVOS;
    }

    @Override
    public List<SearchConditionGroup> getForm(Map<String, Object> params) {

        String id = Util.null2String(params.get("fid"));
        String fClassId = Util.null2String(params.get("fclassid"));
        List<SearchConditionItem> selectItems = new ArrayList<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        SearchConditionItem resourceTypeItem = OrganizationFormItemUtil.browserItem(user, 2, 17, 3, false, "类型", "161", "fclassid", "resourceTypeBrowser");
        resourceTypeItem.setRules("required|string");
        if (StringUtils.isNotBlank(fClassId) && !"-1".equals(fClassId)) {
            BrowserBean browserBean = resourceTypeItem.getBrowserConditionParam();
            List<Map<String, Object>> maps = getResourceBasicInfoMapper().browserDatas(DeleteParam.builder().ids(fClassId).build().getIds());
            browserBean.setReplaceDatas(maps);
            resourceTypeItem.setBrowserConditionParam(browserBean);
        }

        SearchConditionItem fNo = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "编号", "fno");
        fNo.setRules("required|string");
        SearchConditionItem fName = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "名称", "fname");
        fName.setRules("required|string");
        SearchConditionItem fMemo = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 60, "说明", "fmemo");

        if (StringUtils.isNotBlank(id)) {
            ResourceItemPO resourceItemPO = getResourceBasicInfoMapper().getResourceItemByFid(Integer.parseInt(id));
            OrganizationAssert.notNull(resourceItemPO, "选择的数据不存在");
            BrowserBean browserBean = resourceTypeItem.getBrowserConditionParam();
            List<Map<String, Object>> maps = getResourceBasicInfoMapper().browserDatas(DeleteParam.builder().ids(resourceItemPO.getFclassid().toString()).build().getIds());
            browserBean.setReplaceDatas(maps);
            resourceTypeItem.setBrowserConditionParam(browserBean);

            fNo.setValue(resourceItemPO.getFno());
            fNo.setViewAttr(1);
            fName.setValue(resourceItemPO.getFname());
            fMemo.setValue(resourceItemPO.getFmemo());
        }

        selectItems.add(resourceTypeItem);
        selectItems.add(fNo);
        selectItems.add(fName);
        selectItems.add(fMemo);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        return addGroups;
    }

    @Override
    public int deletByIds(Collection<Long> ids) {
        OrganizationAssert.notEmpty(ids, "请选择要删除的数据");
        return getResourceBasicInfoMapper().deleteByIds(ids);
    }

    @Override
    public int recoverByIds(Collection<Long> ids) {
        OrganizationAssert.notEmpty(ids, "请选择要恢复的数据");
        return getResourceBasicInfoMapper().recoverByIds(ids);
    }

    @Override
    public int save(ResourceItemPO resourceItemPO) {
        List<ResourceItemPO> list = getResourceBasicInfoMapper().selectItemByFNo(resourceItemPO.getFno(), resourceItemPO.getFclassid());
        OrganizationAssert.isEmpty(list, "编号不允许重复");
        return getResourceBasicInfoMapper().insertIgnoreNull(resourceItemPO);
    }

    @Override
    public ResourceItemPO selectById(Integer fid) {
        return getResourceBasicInfoMapper().getResourceItemByFid(fid);
    }

    @Override
    public int update(ResourceItemPO resourceItemPO) {
        return getResourceBasicInfoMapper().update(resourceItemPO);
    }

    @Override
    public List<SearchConditionGroup> getItemClassForm(Map<String, Object> params) {
        String id = Util.null2String(params.get("fid"));
        List<SearchConditionItem> selectItems = new ArrayList<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        SearchConditionItem fNo = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "编号", "fno");
        fNo.setRules("required|string");
        SearchConditionItem fName = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "名称", "fname");
        fName.setRules("required|string");
        SearchConditionItem fMemo = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 60, "说明", "fmemo");

        if (!"-1".equals(id) && StringUtils.isNotBlank(id)) {
            ResourceItemClassPO resourceItemClassPO = getResourceBasicInfoMapper().getResourceItemClassByFid(Integer.parseInt(id));
            OrganizationAssert.notNull(resourceItemClassPO, "选择的数据不存在");
            fNo.setValue(resourceItemClassPO.getFno());
            fNo.setViewAttr(1);
            fName.setValue(resourceItemClassPO.getFname());
            fMemo.setValue(resourceItemClassPO.getFmemo());
        }
        selectItems.add(fNo);
        selectItems.add(fName);
        selectItems.add(fMemo);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        return addGroups;
    }

    @Override
    public int saveResourceItemClass(ResourceItemClassPO itemClassPO) {
        List<ResourceItemClassPO> list = getResourceBasicInfoMapper().selectItemClassByFNo(itemClassPO.getFno(), null);
        OrganizationAssert.isEmpty(list, "编号不允许重复");
        itemClassPO.setCreator((long) user.getUID());
        itemClassPO.setCreateTime(new Date());
        return getResourceBasicInfoMapper().saveResourceItemClass(itemClassPO);
    }

    @Override
    public int updateResourceItemClass(ResourceItemClassPO itemClassPO) {
        itemClassPO.setUpdateTime(new Date());
        return getResourceBasicInfoMapper().updateResourceItemClass(itemClassPO);
    }

    @Override
    public int deleteResourceItemClass(Integer fid) {
        OrganizationAssert.notNull(fid, "选择的数据不存在");
        // 判断该分类下是否有数据
        List<ResourceItemPO> itemByClassId = getResourceBasicInfoMapper().getItemByClassId(fid, 0);
        OrganizationAssert.isTrue(CollectionUtils.isEmpty(itemByClassId), "当前分类下存在数据，无法删除");
        List<ResourceItemPO> deleteItems = getResourceBasicInfoMapper().getItemByClassId(fid, 1);
        // 级联删除已停用数据
        if (CollectionUtils.isNotEmpty(deleteItems)) {
            getResourceBasicInfoMapper().deleteItemByIds((deleteItems.stream().map(ResourceItemPO::getFid).collect(Collectors.toList())));
        }
        return getResourceBasicInfoMapper().deleteResourceItemClass(fid);
    }

    @Override
    public List<SearchConditionGroup> getSearchCondition() {
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> conditionItems = new ArrayList<>();
        SearchConditionItem schemeNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "名称", "fname");
        SearchConditionItem schemeNoCondition = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "编号", "fno");
        conditionItems.add(schemeNameCondition);
        conditionItems.add(schemeNoCondition);
        addGroups.add(new SearchConditionGroup("高级搜索条件", true, conditionItems));
        return addGroups;
    }

    private String buildSqlWhere(Map<String, Object> params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where 1 = 1 ";
        String fclassid = (String) params.get("fclassid");
        if (StringUtils.isNotBlank(fclassid) && !"-1".equals(fclassid)) {
            sqlWhere += " AND t.fclassid = '" + fclassid + "'";
        }
        String fno = (String) params.get("fno");
        if (StringUtils.isNotBlank(fno)) {
            sqlWhere += " AND t.fno = '" + fno + "'";
        }
        String fname = (String) params.get("fname");
        if (StringUtils.isNotBlank(fname)) {
            sqlWhere += " AND t.fname " + dbType.like(fname);
        }

        return sqlWhere;
    }
}
