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.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.exception.OrganizationRunTimeException;
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 org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.StringUtil;
import weaver.general.Util;
import weaver.systeminfo.SystemEnv;

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);
    }
    
    @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, SystemEnv.getHtmlLabelName(547137, user.getLanguage()));
        // 结束时间大于开始时间
        StaffPlanPO staffPlanPO = StaffPlanBO.convertParamToPO(param, (long) user.getUID());
        // 多选赋值
        staffPlanPO.setCompanyId(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), SystemEnv.getHtmlLabelName(547445,user.getLanguage()));
        List<StaffPlanPO> staffPlanPO1 = getStaffPlanMapper().customSelect(param.getTimeStart(),param.getTimeEnd(), param.getEcCompany(), param.getControlDimension());
        OrganizationAssert.isEmpty(staffPlanPO1,SystemEnv.getHtmlLabelName(547446,user.getLanguage()));
        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, SystemEnv.getHtmlLabelName(547137, user.getLanguage()));
        }
        // 结束时间大于开始时间
        String timeStart = param.getTimeStart();
        String timeEnd = param.getTimeEnd();
        Date startDate = DateUtil.parseToDate(timeStart);
        Date endDate = DateUtil.parseToDate(timeEnd);
        OrganizationAssert.isFalse(startDate.after(endDate), SystemEnv.getHtmlLabelName(547445,user.getLanguage()));
        List<StaffPlanPO> staffPlanPO1 = getStaffPlanMapper().customSelect(param.getTimeStart(),param.getTimeEnd(), param.getEcCompany(), param.getControlDimension());
        if (staffPlanPO1.size() > 1) {
            throw new OrganizationRunTimeException(SystemEnv.getHtmlLabelName(547458,user.getLanguage()));
        }
        // 多选赋值
        staffPlanPO.setCompanyId(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, SystemEnv.getHtmlLabelName(547138,user.getLanguage()));
        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, 547118, "planNo");
        // 名称
        SearchConditionItem planNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, 547141, "planName");
        // 年度
        SearchConditionItem planYearItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 2, 547336, "planYear");
        planYearItem.setFormat("YYYY");
        // 时间开始
        SearchConditionItem timeStartItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 2, 547337, "timeStart");
        // 时间结束
        SearchConditionItem timeEndItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 2, 547338, "timeEnd");
        // 适用公司
        SearchConditionItem companyIdtItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, 547340, "164", "ecCompany", "");
        // 说明
        SearchConditionItem descriptionItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, 547142, "description");
        // 状态
        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption enableOption = new SearchConditionOption("true", SystemEnv.getHtmlLabelName(547186, user.getLanguage()));
        SearchConditionOption disableOption = new SearchConditionOption("false", SystemEnv.getHtmlLabelName(547192, user.getLanguage()));
        selectOptions.add(enableOption);
        selectOptions.add(disableOption);
        SearchConditionItem forbiddenTagItem = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, false, 547130, "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, 547118, "planNo");
        planNoItem.setRules("required|string");
        // 名称
        SearchConditionItem planNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 3, 50, 547141, "planName");
        planNameItem.setRules("required|string");
        // 年度
        SearchConditionItem planYearItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 3, 547336, "planYear");
        planYearItem.setFormat("YYYY");
        planYearItem.setRules("required|string");
        // 时间开始
        SearchConditionItem timeStartItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 3, 547337, "timeStart");
        timeStartItem.setRules("required|string");
        // 时间结束
        SearchConditionItem timeEndItem = OrganizationFormItemUtil.datePickerItem(user, 2, 16, false, 3, 547338, "timeEnd");
        timeEndItem.setRules("required|string");
        // 适用公司
        SearchConditionItem ecCompanyIdtItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, 547340, "194", "ecCompany", "compBrowser");
        ecCompanyIdtItem.setRules("required|string");
        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption option1 = new SearchConditionOption("1", SystemEnv.getHtmlLabelName(547332,user.getLanguage()));
        SearchConditionOption option2 = new SearchConditionOption("2", SystemEnv.getHtmlLabelName(547331,user.getLanguage()));
        SearchConditionOption option3 = new SearchConditionOption("3", SystemEnv.getHtmlLabelName(547333,user.getLanguage()));
        selectOptions.add(option1);
        selectOptions.add(option2);
        selectOptions.add(option3);
        // 控制维度
        SearchConditionItem dimensionItem = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, true, 547341, "controlDimension");
        dimensionItem.setViewAttr(3);
        dimensionItem.setRules("required|string");
        // 说明
        SearchConditionItem descriptionItem = OrganizationFormItemUtil.textareaItem(user, 2, 16, true, 2, 200, 547142, "description");

        // 编辑状态下赋值操作
        String id = Util.null2String(params.get("id"));
        if (!StringUtil.isEmpty(id)) {
            StaffPlanPO staffPlanPO = getStaffPlanMapper().getStaffPlanByID(Integer.parseInt(id));
            OrganizationAssert.notNull(staffPlanPO, SystemEnv.getHtmlLabelName(547154,user.getLanguage()));
            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(user.getLanguage());
    }


    /**
     * 查询条件
     *
     * @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;
    }
}
