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.api.browser.bean.SearchConditionOption;
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.staff.bo.StaffBO;
import com.engine.organization.entity.staff.param.StaffSearchParam;
import com.engine.organization.entity.staff.po.StaffPO;
import com.engine.organization.entity.staff.po.StaffsPO;
import com.engine.organization.entity.staff.vo.StaffTableVO;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.mapper.staff.StaffMapper;
import com.engine.organization.mapper.staff.StaffPlanMapper;
import com.engine.organization.mapper.staff.StaffsMapper;
import com.engine.organization.service.StaffService;
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/25
 * @version: 1.0
 */
public class StaffServiceImpl extends Service implements StaffService {

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

    private StaffMapper getStaffMapper() {
        return MapperProxyFactory.getProxy(StaffMapper.class);
    }

    private StaffPlanMapper getStaffPlanMapper() {
        return MapperProxyFactory.getProxy(StaffPlanMapper.class);
    }

    private CompMapper getCompMapper() {
        return MapperProxyFactory.getProxy(CompMapper.class);
    }

    private DepartmentMapper getDepartmentMapper() {
        return MapperProxyFactory.getProxy(DepartmentMapper.class);
    }

    private JobMapper getJobMapper() {
        return MapperProxyFactory.getProxy(JobMapper.class);
    }


    @Override
    public Map<String, Object> listPage(StaffSearchParam params) {
        Map<String, Object> resultMap = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        resultMap.put("hasRight", hasRight);
        if (!hasRight) {
            return resultMap;
        }
        // 刷新引用状态
        RefreshIsUsedUtil.RefreshStaff("jcl_org_staff");
        OrganizationWeaTable<StaffTableVO> table = new OrganizationWeaTable<>(user, StaffTableVO.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 saveStaff(StaffSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        StaffPO staffPO = StaffBO.convertParamToPO(param, (long) user.getUID());
        return getStaffMapper().insertIgnoreNull(staffPO);
    }

    @Override
    public int updateStaff(StaffSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        StaffPO staffByID = getStaffMapper().getStaffByID(param.getId());
        StaffPO staffPO = StaffBO.convertParamToPO(param, (long) user.getUID());

        Integer changeNum = param.getChangeNum();
        if (null == changeNum) {
            // 插入明细表数据
            StaffsPO staffsPO = StaffsPO.builder().staffId(staffPO.getId()).businessType(1).changeNum(staffPO.getStaffNum() - staffByID.getStaffNum()).businessSource(1).build();
            MapperProxyFactory.getProxy(StaffsMapper.class).insertIgnoreNull(staffsPO);

        } else {
            // 插入明细表数据
            StaffsPO staffsPO = StaffsPO.builder().staffId(staffPO.getId()).businessType(2).changeNum(changeNum).businessSource(1).description(param.getChangeDescription()).build();
            MapperProxyFactory.getProxy(StaffsMapper.class).insertIgnoreNull(staffsPO);
            // 更新编制表
            staffPO.setStaffNum(staffPO.getStaffNum() + changeNum);
        }
        OrganizationAssert.isFalse(staffPO.getStaffNum() < 0, "调整后编制数小于0，请更正");
        StaffBO.buildStaffDesc(staffPO);
        // 更新主表
        return getStaffMapper().updateStaff(staffPO);
    }


    @Override
    public int deleteByIds(Collection<Long> ids) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notEmpty(ids, "请选择要删除的数据");
        return getStaffMapper().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 planIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "方案11", "161", "planId", "staffPlanBrowser");
        //planIdItem.setHide(true);
        //planIdItem.setDisplay("none");
        // 分部
        SearchConditionItem compIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "分部", "161", "compId", "compBrowser");
        // 部门
        SearchConditionItem deptIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "部门", "161", "deptId", "deptBrowser");
        // 岗位
        SearchConditionItem jobIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "岗位", "161", "jobId", "jobBrowser");
        // 编制数
        SearchConditionItem staffNumItem = OrganizationFormItemUtil.inputNumberItem(user, 2, 16, 2, "编制数", "staffNum");
        // 在编
        SearchConditionItem permanentNumItem = OrganizationFormItemUtil.inputNumberItem(user, 2, 16, 2, "在编", "permanentNum");
        // 冻结数
        SearchConditionItem freezeNumItem = OrganizationFormItemUtil.inputNumberItem(user, 2, 16, 2, "冻结数", "freezeNum");
        // 缺编状态
        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption lackOption = new SearchConditionOption("1", "缺编");
        SearchConditionOption fullOption = new SearchConditionOption("2", "满员");
        SearchConditionOption overOption = new SearchConditionOption("3", "超编");
        selectOptions.add(lackOption);
        selectOptions.add(fullOption);
        selectOptions.add(overOption);
        SearchConditionItem lackStatusItem = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, false, "缺编状态", "lackStatus");
        // 编制描述
        SearchConditionItem staffDescItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "编制描述", "staffDesc");
        // 说明
        SearchConditionItem descriptionItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "说明", "description");

        //conditionItems.add(planIdItem);
        conditionItems.add(compIdItem);
        conditionItems.add(deptIdItem);
        conditionItems.add(jobIdItem);
        conditionItems.add(staffNumItem);
        conditionItems.add(permanentNumItem);
        conditionItems.add(freezeNumItem);
        conditionItems.add(lackStatusItem);
        conditionItems.add(staffDescItem);
        conditionItems.add(descriptionItem);

        addGroups.add(new SearchConditionGroup("高级搜索条件", true, conditionItems));
        apiDatas.put("conditions", addGroups);
        return apiDatas;
    }

    @Override
    public Map<String, Object> getForm(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 planIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "方案", "161", "planId", "staffPlanBrowser");
        planIdItem.setRules("required|string");
        // 分部
        SearchConditionItem compIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "分部", "161", "compId", "compBrowser");
        compIdItem.setRules("required|string");
        // 部门
        SearchConditionItem deptIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "部门", "161", "deptId", "deptBrowser");
        deptIdItem.setRules("required|string");
        // 岗位
        SearchConditionItem jobIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "岗位", "161", "jobId", "jobBrowser");
        jobIdItem.setRules("required|string");
        // 编制数
        SearchConditionItem staffNumItem = OrganizationFormItemUtil.inputNumberItem(user, 2, 16, 3, "编制数", "staffNum");
        staffNumItem.setRules("required");
        // 控制策略
        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption option1 = new SearchConditionOption("1", "弱控");
        SearchConditionOption option2 = new SearchConditionOption("2", "强控");
        SearchConditionOption option3 = new SearchConditionOption("3", "不控");
        selectOptions.add(option1);
        selectOptions.add(option2);
        selectOptions.add(option3);
        SearchConditionItem controlPolicyItem = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, false, "控制策略", "controlPolicy");
        controlPolicyItem.setViewAttr(3);
        controlPolicyItem.setRules("required|string");
        SearchConditionItem descriptionItem = OrganizationFormItemUtil.textareaItem(user, 2, 16, true, 2, 60, "描述说明", "description");


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

            BrowserBean planIdItemBean = planIdItem.getBrowserConditionParam();
            List<Map<String, Object>> planIdMaps = getStaffPlanMapper().listPlansByIds(DeleteParam.builder().ids(staffPO.getPlanId().toString()).build().getIds());
            planIdItemBean.setReplaceDatas(planIdMaps);
            planIdItem.setBrowserConditionParam(planIdItemBean);

            BrowserBean compIdItemBean = compIdItem.getBrowserConditionParam();
            List<Map<String, Object>> compIdMaps = getCompMapper().listCompsByIds(DeleteParam.builder().ids(staffPO.getCompId().toString()).build().getIds());
            compIdItemBean.setReplaceDatas(compIdMaps);
            compIdItem.setBrowserConditionParam(compIdItemBean);

            BrowserBean deptIdItemBean = deptIdItem.getBrowserConditionParam();
            List<Map<String, Object>> deptIdMaps = getDepartmentMapper().listDeptsByIds(DeleteParam.builder().ids(staffPO.getDeptId().toString()).build().getIds());
            deptIdItemBean.setReplaceDatas(deptIdMaps);
            deptIdItem.setBrowserConditionParam(deptIdItemBean);

            BrowserBean jobIdItemBean = jobIdItem.getBrowserConditionParam();
            List<Map<String, Object>> jobIdMaps = getJobMapper().listJobsByIds(DeleteParam.builder().ids(staffPO.getJobId().toString()).build().getIds());
            jobIdItemBean.setReplaceDatas(jobIdMaps);
            jobIdItem.setBrowserConditionParam(jobIdItemBean);

            staffNumItem.setValue(staffPO.getStaffNum());
            controlPolicyItem.setValue(staffPO.getControlPolicy() + "");
            descriptionItem.setValue(staffPO.getDescription());
        }
        selectItems.add(planIdItem);
        selectItems.add(compIdItem);
        selectItems.add(deptIdItem);
        selectItems.add(jobIdItem);
        selectItems.add(staffNumItem);
        selectItems.add(controlPolicyItem);
        selectItems.add(descriptionItem);
        String operateType = (String) params.get("operateType");
        if ("2".equals(operateType)) {
            selectItems.forEach(item -> {
                item.setViewAttr(1);
                item.setRules(null);
            });
            SearchConditionItem changeNumItem = OrganizationFormItemUtil.inputNumberItem(user, 2, 16, 3, "调整数量", "changeNum");
            staffNumItem.setRules("required");
            selectItems.add(changeNumItem);
            SearchConditionItem changeDescriptionItem = OrganizationFormItemUtil.textareaItem(user, 2, 16, false, 2, 50, "变更说明", "changeDescription");
            selectItems.add(changeDescriptionItem);

        }

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

    @Override
    public Map<String, Object> getHasRight() {
        Map<String, Object> datas = MenuBtn.getCommonBtnDatas();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> selectItems = new ArrayList<>();
        // 方案
        SearchConditionItem planIdItem = OrganizationFormItemUtil.browserItem(user, 4, 3, 2, false, "编制方案", "161", "planId", "staffPlanBrowser");
        planIdItem.setRules("required|string");
        planIdItem.setHelpfulTip("请选择编制方案后查看数据");
        planIdItem.setLabelcol(2);
        selectItems.add(planIdItem);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        datas.put("condition", addGroups);
        return datas;
    }

    /**
     * 查询条件
     *
     * @param param
     * @return
     */
    private String buildSqlWhere(StaffSearchParam param) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where t.delete_type ='0' ";

        Long planId = param.getPlanId();
        if (null != planId) {
            sqlWhere += " AND t.plan_id = '" + planId + "'";
        } else {
            sqlWhere = " 1=2 ";
        }
        Long compId = param.getCompId();
        if (null != compId) {
            sqlWhere += " AND t.comp_id = '" + compId + "'";
        }
        Long deptId = param.getDeptId();
        if (null != deptId) {
            sqlWhere += " AND t.dept_id = '" + deptId + "'";
        }
        Long jobId = param.getJobId();
        if (null != jobId) {
            sqlWhere += " AND t.job_id = '" + jobId + "'";
        }
        Integer staffNum = param.getStaffNum();
        if (null != staffNum) {
            sqlWhere += " AND t.staff_num = '" + staffNum + "'";
        }
        Integer controlPolicy = param.getControlPolicy();
        if (null != controlPolicy) {
            sqlWhere += " AND t.control_policy = '" + controlPolicy + "'";
        }
        Integer permanentNum = param.getPermanentNum();
        if (null != permanentNum) {
            sqlWhere += " AND t.permanent_num = '" + permanentNum + "'";
        }
        Integer freezeNum = param.getFreezeNum();
        if (null != freezeNum) {
            sqlWhere += " AND t.freeze_num = '" + freezeNum + "'";
        }
        Integer lackStatus = param.getLackStatus();
        if (null != lackStatus) {
            sqlWhere += " AND t.lack_status = '" + lackStatus + "'";
        }
        String staffDesc = param.getStaffDesc();
        if (StringUtils.isNotBlank(staffDesc)) {
            sqlWhere += " AND t.staff_desc " + dbType.like(staffDesc);
        }
        String description = param.getDescription();
        if (StringUtils.isNotBlank(description)) {
            sqlWhere += " AND t.description " + dbType.like(description);
        }
        String staffName = param.getStaffName();
        if (StringUtils.isNotBlank(staffName)) {
            sqlWhere += " AND t.plan_id in ( select id from jcl_org_staffplan where plan_name " + dbType.like(staffName) + ") ";
        }

        return sqlWhere;
    }

}
