package com.rongwei.bscommon.sys.utils;

import com.rongwei.bscommon.sys.dao.QuestionCommonSqlDao;
import com.rongwei.bscommon.sys.service.impl.SrmIssuesFiveWhyServiceImpl;
import com.rongwei.bsentity.domin.SrmIssuesFiveWhyDo;
import com.rongwei.bsentity.vo.FiveWhyVo;
import com.rongwei.commonservice.serial.service.SysSerialNumberService;
import com.rongwei.rwadmincommon.system.domain.SysDictDo;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.domain.SysUserDo;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommonentity.commonservers.vo.SysSerialVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.rongwei.bscommon.sys.utils.QuestionConstants.FIVE_WHY_ONT_H_DESC;

@Component
public class QuestionUtils {

    private static final Logger log = LoggerFactory.getLogger(QuestionUtils.class.getName());

    @Autowired
    private SysSerialNumberService autoSysSerialNumberService;
    @Autowired
    private SrmIssuesFiveWhyServiceImpl autoSrmIssuesFiveWhyService;
    @Autowired
    private QuestionCommonSqlDao autoQuestionCommonSqlDao;

    private static SysSerialNumberService sysSerialNumberService;
    private static SrmIssuesFiveWhyServiceImpl srmIssuesFiveWhyService;
    private static QuestionCommonSqlDao questionCommonSqlDao;

    @PostConstruct
    public void init() {
        srmIssuesFiveWhyService = autoSrmIssuesFiveWhyService;
        sysSerialNumberService = autoSysSerialNumberService;
        questionCommonSqlDao = autoQuestionCommonSqlDao;
    }

    public static String dateConvertStr(Date date) {
        if (date == null) {
            return "";
        }
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

    public static String dateConvertStr(Date date, String formatPattern) {
        if (date == null) {
            return "";
        }
        return new SimpleDateFormat(formatPattern).format(date);
    }

    public static String getDictValueByDictName(String value,
                                                String dictType,
                                                List<SysDictDo> sysDictDoList) {
        if (StringUtils.isBlank(value)) {
            return "";
        }
        if (StringUtils.isBlank(dictType)) {
            return "";
        }
        if (sysDictDoList.isEmpty()) {
            return "";
        }
        // 数据字典多选特殊处理
        List<String> values = Arrays.asList(value.split(","));
        // 获取数字字典
        String dictNames = sysDictDoList.stream()
                .filter(dict -> values.contains(dict.getValue()) && dictType.equals(dict.getDicttype()))
                .map(SysDictDo::getName).collect(Collectors.joining(","));
        return dictNames;
    }


    /**
     * 流水码生成
     *
     * @param moduleCode      流水码CODE
     * @param ruleTemplateStr 流水码编码规则
     * @return
     */
    public static String streamCodeGeneration(String moduleCode, String ruleTemplateStr) {

        return streamCodeGeneration(moduleCode, ruleTemplateStr, "");
    }

    /**
     * 流水码生成
     *
     * @param moduleCode      流水码CODE
     * @param ruleTemplateStr 流水码编码规则
     * @param resetRule       重置规则
     * @return
     */
    public static String streamCodeGeneration(String moduleCode, String ruleTemplateStr, String resetRule) {
        log.info("开始生成流水码");
        SysSerialVo sysSerialVo = new SysSerialVo();
        sysSerialVo.setModulecode(moduleCode);
        sysSerialVo.setRuleTemplateStr(ruleTemplateStr);

        if (StringUtils.isNotBlank(resetRule)) {
            sysSerialVo.setIfautomaticreset("y");
            sysSerialVo.setResetrule(resetRule);
        }

        String streamCode = sysSerialNumberService.getCodeByTemplate(sysSerialVo);
        log.info("流水码生成成功：{}", streamCode);
        return streamCode;
    }

    /**
     * 生成 5W1H表
     *
     * @param mainIds
     * @return
     */
    public static void save5W1H(List<String> mainIds, List<FiveWhyVo> fiveWhyVos) {
        List<SrmIssuesFiveWhyDo> saveList = new ArrayList<SrmIssuesFiveWhyDo>();
        mainIds.forEach(mainId -> {
            for (int i = 0; i < FIVE_WHY_ONT_H_DESC.size(); i++) {
                FiveWhyVo fiveWhyVo = fiveWhyVos.stream().filter(info -> mainId.equals(info.getId())).findFirst().orElse(null);
                SrmIssuesFiveWhyDo srmIssuesFiveWhyDo = new SrmIssuesFiveWhyDo();
                srmIssuesFiveWhyDo.setId(SecurityUtil.getUUID());
                srmIssuesFiveWhyDo.setMainid(mainId);
                srmIssuesFiveWhyDo.setWhy(FIVE_WHY_ONT_H_DESC.get(i));
                srmIssuesFiveWhyDo.setWhnumber(String.valueOf(i));
                if (i == 2) {
                    srmIssuesFiveWhyDo.setDescription(fiveWhyVo == null ? "" : fiveWhyVo.getWhoDesc());
                }
                if (i == 3) {
                    srmIssuesFiveWhyDo.setDescription(fiveWhyVo == null ? "" : fiveWhyVo.getWhatDesc());
                }
                saveList.add(srmIssuesFiveWhyDo);
            }
        });
        srmIssuesFiveWhyService.saveBatch(saveList);
    }

    /**
     * 获取当前工位以及车间的  部门经理或部门PS负责人
     * @param sysOrganizationDo
     * @return
     */
    public static List<SysUserDo> getPSManagerByOrgId(SysOrganizationDo sysOrganizationDo, String roleCode){
        // 工段ID
        String id = sysOrganizationDo.getId();
        // 车间Id
        String pid = sysOrganizationDo.getPid();
        if(StringUtils.isBlank(id)&&StringUtils.isBlank(pid)){
            return new ArrayList<>();
        }
       return questionCommonSqlDao.getUserByRoleCodeAndOrgId(new ArrayList<String>() {{
            add(id);
            add(pid);
        }}, roleCode);
    }
}
