package com.engine.organization.service.impl;

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.company.po.CompPO;
import com.engine.organization.entity.staff.bo.StaffPlanBO;
import com.engine.organization.entity.staff.param.StaffPlanSearchParam;
import com.engine.organization.entity.staff.po.StaffPlanPO;
import com.engine.organization.entity.staff.vo.StaffPlanTableVO;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.staff.StaffPlanMapper;
import com.engine.organization.service.StaffPlanService;
import com.engine.organization.util.*;
import com.engine.organization.util.browser.OrganizationBrowserUtil;
import com.engine.organization.util.db.DBType;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.relation.EcHrmRelationUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
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 StaffPlanServiceImpl extends Service implements StaffPlanService {

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

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

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

    @Override
    public Map<String, Object> listPage(StaffPlanSearchParam params) {
        Map<String, Object> resultMap = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        resultMap.put("hasRight", hasRight);
        if (!hasRight) {
            return resultMap;
        }
        // 刷新引用状态
        RefreshIsUsedUtil.RefreshStaffPlan("jcl_org_staffplan");
        OrganizationWeaTable<StaffPlanTableVO> table = new OrganizationWeaTable<>(user, StaffPlanTableVO.class);
        StaffPlanPO staffPlanPO = StaffPlanBO.convertParamToPO(params, (long) user.getUID());
        String sqlWhere = buildSqlWhere(staffPlanPO);
        table.setSqlwhere(sqlWhere);
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();
        resultMap.putAll(result.getResultMap());
        return resultMap;
    }

    @Override
    public int saveStaffPlan(StaffPlanSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        List<StaffPlanPO> list = getStaffPlanMapper().listByNo(Util.null2String(param.getPlanNo()));
        OrganizationAssert.isEmpty(list, "编号不允许重复");
        // 结束时间大于开始时间
        StaffPlanPO staffPlanPO = StaffPlanBO.convertParamToPO(param, (long) user.getUID());
        // 多选赋值
        staffPlanPO.setCompanyId(getJclCompanyIdsByEcIds(staffPlanPO.getEcCompany()));
        String timeStart = param.getTimeStart();
        String timeEnd = param.getTimeEnd();
        Date startDate = DateUtil.parseToDate(timeStart);
        Date endDate = DateUtil.parseToDate(timeEnd);
        OrganizationAssert.isFalse(startDate.after(endDate), "开始时间不允许在结束时间之后");
        return getStaffPlanMapper().insertIgnoreNull(staffPlanPO);
    }

    @Override
    public int updateStaffPlan(StaffPlanSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        StaffPlanPO staffPlanPO = StaffPlanBO.convertParamToPO(param, (long) user.getUID());
        // 更新前先查询下旧编号，
        String oldPlanNo = getStaffPlanMapper().getStaffPlanByID(staffPlanPO.getId()).getPlanNo();
        if (!oldPlanNo.equals(staffPlanPO.getPlanNo())) {
            List<StaffPlanPO> list = getStaffPlanMapper().listByNo(Util.null2String(staffPlanPO.getPlanNo()));
            OrganizationAssert.isEmpty(list, "编号不允许重复");
        }
        // 结束时间大于开始时间
        String timeStart = param.getTimeStart();
        String timeEnd = param.getTimeEnd();
        Date startDate = DateUtil.parseToDate(timeStart);
        Date endDate = DateUtil.parseToDate(timeEnd);
        OrganizationAssert.isFalse(startDate.after(endDate), "开始时间不允许在结束时间之后");
        // 多选赋值
        staffPlanPO.setCompanyId(getJclCompanyIdsByEcIds(staffPlanPO.getEcCompany()));
        return getStaffPlanMapper().updateStaffPlan(staffPlanPO);
    }

    @Override
    public int updateForbiddenTagById(StaffPlanSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        StaffPlanPO staffPlanPO = StaffPlanPO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).build();
        return getStaffPlanMapper().updateForbiddenTagById(staffPlanPO);
    }

    @Override
    public int deleteByIds(Collection<Long> ids) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notEmpty(ids, "请选择要删除的数据");
        return getStaffPlanMapper().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 planNoItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "编号", "planNo");
        // 名称
        SearchConditionItem planNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "名称", "planName");
        // 年度
        SearchConditionItem planYearItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 2, "年度", "planYear");
        planYearItem.setFormat("YYYY");
        // 时间开始
        SearchConditionItem timeStartItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 2, "时间开始", "timeStart");
        // 时间结束
        SearchConditionItem timeEndItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 2, "时间结束", "timeEnd");
        // 适用公司
        SearchConditionItem companyIdtItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "适用公司", "164", "ecCompany", "");
        // 说明
        SearchConditionItem descriptionItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "说明", "description");
        // 状态
        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption enableOption = new SearchConditionOption("true", "启用");
        SearchConditionOption disableOption = new SearchConditionOption("false", "禁用");
        selectOptions.add(enableOption);
        selectOptions.add(disableOption);
        SearchConditionItem forbiddenTagItem = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, false, "禁用标记", "forbiddenTag");


        conditionItems.add(planNoItem);
        conditionItems.add(planNameItem);
        conditionItems.add(planYearItem);
        conditionItems.add(timeStartItem);
        conditionItems.add(timeEndItem);
        conditionItems.add(companyIdtItem);
        conditionItems.add(descriptionItem);
        conditionItems.add(forbiddenTagItem);
        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 planNoItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 3, 50, "编号", "planNo");
        planNoItem.setRules("required|string");
        // 名称
        SearchConditionItem planNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 3, 50, "名称", "planName");
        planNameItem.setRules("required|string");
        // 年度
        SearchConditionItem planYearItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 3, "年度", "planYear");
        planYearItem.setFormat("YYYY");
        planYearItem.setRules("required|string");
        // 时间开始
        SearchConditionItem timeStartItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 3, "时间开始", "timeStart");
        timeStartItem.setRules("required|string");
        // 时间结束
        SearchConditionItem timeEndItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 3, "时间结束", "timeEnd");
        timeEndItem.setRules("required|string");
        // 适用公司
        SearchConditionItem ecCompanyIdtItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "适用公司", "194", "ecCompany", "compBrowser");
        ecCompanyIdtItem.setRules("required|string");
        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 dimensionItem = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, true, "控制维度", "controlDimension");
        dimensionItem.setViewAttr(3);
        dimensionItem.setRules("required|string");
        // 说明
        SearchConditionItem descriptionItem = OrganizationFormItemUtil.textareaItem(user, 2, 16, true, 2, 200, "说明", "description");

        // 编辑状态下赋值操作
        String id = Util.null2String(params.get("id"));
        if (!StringUtil.isEmpty(id)) {
            StaffPlanPO staffPlanPO = getStaffPlanMapper().getStaffPlanByID(Integer.parseInt(id));
            OrganizationAssert.notNull(staffPlanPO, "选择的数据不存在，或数据已删除");
            planNoItem.setValue(staffPlanPO.getPlanNo());
            planNameItem.setValue(staffPlanPO.getPlanName());
            planYearItem.setValue(Util.null2String(staffPlanPO.getPlanYear()));
            timeStartItem.setValue(DateUtil.getDate(staffPlanPO.getTimeStart(), "yyyy-MM-dd"));
            timeEndItem.setValue(DateUtil.getDate(staffPlanPO.getTimeEnd(), "yyyy-MM-dd"));

            String tmpFieldValue = staffPlanPO.getEcCompany();
            if (StringUtils.isNotBlank(tmpFieldValue)) {
                OrganizationBrowserUtil.assignBrowser(user, tmpFieldValue, 164, ecCompanyIdtItem);
            }

            dimensionItem.setValue(staffPlanPO.getControlDimension());
            descriptionItem.setValue(staffPlanPO.getDescription());

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

        selectItems.add(planNoItem);
        selectItems.add(planNameItem);
        selectItems.add(planYearItem);
        selectItems.add(timeStartItem);
        selectItems.add(timeEndItem);
        selectItems.add(ecCompanyIdtItem);
        selectItems.add(dimensionItem);
        selectItems.add(descriptionItem);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

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


    /**
     * 查询条件
     *
     * @param staffPlanPO
     * @return
     */
    private String buildSqlWhere(StaffPlanPO staffPlanPO) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where t.delete_type ='0' ";
        String planNo = staffPlanPO.getPlanNo();
        if (StringUtils.isNotBlank(planNo)) {
            sqlWhere += " AND t.plan_no " + dbType.like(planNo);
        }
        String planName = staffPlanPO.getPlanName();
        if (StringUtils.isNotBlank(planName)) {
            sqlWhere += " AND t.plan_name " + dbType.like(planName);
        }
        Integer planYear = staffPlanPO.getPlanYear();
        if (null != planYear) {
            sqlWhere += " AND t.plan_year = '" + planYear + "'";
        }
        Date timeStart = staffPlanPO.getTimeStart();
        if (null != timeStart) {
            sqlWhere += " AND t.time_start >= '" + timeStart + "'";
        }
        Date timeEnd = staffPlanPO.getTimeEnd();
        if (null != timeEnd) {
            sqlWhere += " AND t.time_end <= '" + timeEnd + "'";
        }
        String ecCompany = staffPlanPO.getEcCompany();
        if (StringUtils.isNotBlank(ecCompany)) {
            sqlWhere += " AND " + dbType.concat("t.ec_company") + " " + dbType.like("," + ecCompany + ",");
        }

        String description = staffPlanPO.getDescription();
        if (StringUtils.isNotBlank(description)) {
            sqlWhere += " AND t.description " + dbType.like(description);
        }
        Integer forbiddenTag = staffPlanPO.getForbiddenTag();
        if (null != forbiddenTag) {
            sqlWhere += " AND t.forbidden_tag = '" + forbiddenTag + "'";
        }
        return sqlWhere;
    }

    private String getJclCompanyIdsByEcIds(String ecIds) {
        List<String> jclCompanyIds = new ArrayList<>();
        String[] split = ecIds.split(",");
        for (String s : split) {
            CompPO jclCompanyId = EcHrmRelationUtil.getJclCompanyId(s);
            if (null != jclCompanyId) {
                jclCompanyIds.add(jclCompanyId.getId().toString());
            }
        }
        return StringUtils.join(jclCompanyIds, ",");
    }


}
