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.postion.dto.PostInfoDTO;
import com.engine.organization.entity.postion.param.PostInfoSearchParam;
import com.engine.organization.entity.postion.po.PostInfoPO;
import com.engine.organization.entity.postion.vo.PostInfoTableVO;
import com.engine.organization.mapper.post.PostInfoMapper;
import com.engine.organization.mapper.post.PostMapper;
import com.engine.organization.service.PostInfoService;
import com.engine.organization.util.*;
import com.engine.organization.util.db.DBType;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.excel.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


/**
 * @description:
 * @author:dxfeng
 * @createTime: 2022/05/13
 * @version: 1.0
 */
public class PostInfoServiceImpl extends Service implements PostInfoService {

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

    private PostInfoMapper getPostInfoMapper() {
        return MapperProxyFactory.getProxy(PostInfoMapper.class);
    }

    private PostMapper getPostMapper() {
        return MapperProxyFactory.getProxy(PostMapper.class);
    }
    // 判断编制导入模板是否存在，不存在则创建该文件
    static {
        try {
            String outPutPath = GCONST.getRootPath() + File.separator + "hrm" + File.separator + "import" + File.separator + "template" + File.separator + "postinfo.xls";
            File excelPathFile = new File(outPutPath);
            if (!excelPathFile.exists()) {
                String columns = "编号,名称,职务分类,权限,责任,资格,描述说明";
                String[] split = columns.split(",");
                List<Object> columnList = new ArrayList<>(Arrays.asList(split));
                // 创建导入模板
                List<List<Object>> excelSheetData = new ArrayList<>();
                excelSheetData.add(columnList);
                XSSFWorkbook sheets = ExcelUtil.genWorkbookV2(excelSheetData, "postinfo");
                File excelFile = new File(outPutPath);
                if (!excelFile.exists()) {
                    String substring = outPutPath.substring(0, outPutPath.lastIndexOf(File.separator));
                    File file = new File(substring);
                    if (file.mkdirs()) {
                        boolean newFile = excelPathFile.createNewFile();
                        if (!newFile) {
                            throw new IOException(outPutPath + "文件创建失败");
                        }
                    }
                }
                FileOutputStream out = new FileOutputStream(excelPathFile);
                sheets.write(out);
                out.flush();
            }
        } catch (IOException e) {
            new BaseBean().writeLog(e);
            throw new RuntimeException(e);
        }
    }

    @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.RefreshPostInfo("jcl_org_post_info");
        OrganizationWeaTable<PostInfoTableVO> table = new OrganizationWeaTable<>(user, PostInfoTableVO.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 savePostInfo(PostInfoSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        List<PostInfoPO> list = getPostInfoMapper().listByNo(Util.null2String(param.getPostInfoNo()));
        OrganizationAssert.isEmpty(list, "编号不允许重复");
        PostInfoPO postInfoPO = PostInfoDTO.convertParamToPO(param, (long) user.getUID());
        return getPostInfoMapper().insertIgnoreNull(postInfoPO);
    }

    @Override
    public int updatePostInfo(PostInfoSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        PostInfoPO postInfoPO = PostInfoDTO.convertParamToPO(param, (long) user.getUID());
        String oldPostInfoNo = getPostInfoMapper().getPostInfoByID(postInfoPO.getId()).getPostInfoNo();
        if (!oldPostInfoNo.equals(postInfoPO.getPostInfoNo())) {
            List<PostInfoPO> list = getPostInfoMapper().listByNo(Util.null2String(postInfoPO.getPostInfoNo()));
            OrganizationAssert.isEmpty(list, "编号不允许重复");
        }
        return getPostInfoMapper().updatePostInfo(postInfoPO);
    }

    @Override
    public int updateForbiddenTagById(PostInfoSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        PostInfoPO postInfoPO = PostInfoPO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).build();
        return getPostInfoMapper().updateForbiddenTagById(postInfoPO);
    }


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


    @Override
    public Map<String, Object> getPostInfoForm(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 noItem = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "编号", "postInfoNo");
        noItem.setRules("required|string");
        // 名称
        SearchConditionItem nameItem = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, "名称", "postInfoName");
        nameItem.setRules("required|string");
        // 权限
        SearchConditionItem authorityItem = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 0, "权限", "postInfoAuthority");
        // 责任
        SearchConditionItem dutyItem = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 0, "责任", "postInfoDuty");
        // 资格
        SearchConditionItem qualificationItem = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 0, "资格", "postInfoQualification");
        // 职务分类
        SearchConditionItem postIdBrowser = OrganizationFormItemUtil.browserItem(user, 2, 17, 3, false, "职务分类", "161", "postId", "postBrowser");
        postIdBrowser.setRules("required|string");
        // 说明
        SearchConditionItem descriptionItem = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 200, "描述说明", "description");

        // 编辑状态下赋值操作
        String id = Util.null2String(params.get("id"));
        String planId = Util.null2String(params.get("planId"));
        if (StringUtils.isNotBlank(id)) {
            PostInfoPO postInfoPO = getPostInfoMapper().getPostInfoByID(Integer.parseInt(id));
            OrganizationAssert.notNull(postInfoPO, "选择的数据不存在，或数据已删除");

            noItem.setValue(postInfoPO.getPostInfoNo());
            nameItem.setValue(postInfoPO.getPostInfoName());
            authorityItem.setValue(postInfoPO.getPostInfoAuthority());
            dutyItem.setValue(postInfoPO.getPostInfoDuty());
            qualificationItem.setValue(postInfoPO.getPostInfoQualification());
            descriptionItem.setValue(postInfoPO.getDescription());

            BrowserBean browserBean = postIdBrowser.getBrowserConditionParam();
            List<Map<String, Object>> maps = getPostMapper().listPostsByIds(DeleteParam.builder().ids(postInfoPO.getPostId().toString()).build().getIds());

            browserBean.setReplaceDatas(maps);
            postIdBrowser.setBrowserConditionParam(browserBean);
            // 编辑状态下,编号只读
            // noItem.setViewAttr(1);
        }else if(StringUtils.isNotBlank(planId)){
            BrowserBean browserBean = postIdBrowser.getBrowserConditionParam();
            List<Map<String, Object>> maps = getPostMapper().listPostsByIds(DeleteParam.builder().ids(planId).build().getIds());
            browserBean.setReplaceDatas(maps);
            postIdBrowser.setBrowserConditionParam(browserBean);
        }

        selectItems.add(noItem);
        selectItems.add(nameItem);
        selectItems.add(authorityItem);
        selectItems.add(dutyItem);
        selectItems.add(qualificationItem);
        selectItems.add(postIdBrowser);
        selectItems.add(descriptionItem);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

    @Override
    public Map<String, Object> getHasRight() {
        Map<String, Object> btnDatas = new HashMap<>();
        ArrayList<MenuBtn> topMenuList = new ArrayList<>();
        ArrayList<MenuBtn> rightMenuList = new ArrayList<>();
        // 新增
        topMenuList.add(MenuBtn.builder().isBatch("0").isTop("1").menuFun("addPlan").menuIcon("icon-coms-New-Flow").menuName("新增职务分类").type("BTN_AddPlan").build());
        topMenuList.add(MenuBtn.builder().isBatch("0").isTop("1").menuFun("editPlan").menuIcon("icon-coms-edit").menuName("修改职务分类").type("BTN_EditPlan").build());
        topMenuList.add(MenuBtn.builder().isBatch("0").isTop("1").menuFun("delPlan").menuIcon("icon-coms-Delete").menuName("删除职务分类").type("BTN_DelPlan").build());
        topMenuList.add(MenuBtn.topMenu_addNew());
        // 批量删除
        topMenuList.add(MenuBtn.topMenu_batchDelete());
        topMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("import").menuIcon("icon-coms-leading-in").menuName("批量导入").type("BTN_BatchImport").build());

        btnDatas.put("topMenu", topMenuList);
        // 新增
        rightMenuList.add(MenuBtn.rightMenu_addNew());
        rightMenuList.add(MenuBtn.builder().isBatch("1").isTop("0").menuFun("import").menuIcon("icon-coms-leading-in").menuName("批量导入").type("BTN_BatchImport").build());
        // 日志
        rightMenuList.add(MenuBtn.rightMenu_btnLog());
        // 显示列定制
        rightMenuList.add(MenuBtn.rightMenu_btnColumn());

        btnDatas.put("rightMenu", rightMenuList);
        return btnDatas;
    }


    /**
     * 查询条件
     *
     * @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("postInfoName");
        if (StringUtils.isNotBlank(sequenceName)) {
            sqlWhere += " AND t.post_info_name " + dbType.like(sequenceName);
        }
        String postId = (String) params.get("postId");
        if (StringUtils.isNotBlank(postId) && !"-1".equals(postId)) {
            sqlWhere += " AND t.post_id ='" + postId + "'";
        }
        return sqlWhere;
    }

}
