package com.engine.salary.service.impl;


import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.constant.SalaryDefaultTenantConstant;
import com.engine.salary.entity.datacollection.DataCollectionEmployee;
import com.engine.salary.entity.salaryBill.bo.SalaryBillBO;
import com.engine.salary.entity.salaryBill.dto.SalaryBillAckFeedbackDTO;
import com.engine.salary.entity.salaryBill.dto.salaryBillViewingLimitSetting;
import com.engine.salary.entity.salaryBill.dto.SalaryBillWatermarkDTO;
import com.engine.salary.entity.salaryBill.param.SalaryBaseSetSaveParam;
import com.engine.salary.entity.salaryBill.po.SalaryBillWatermarkPO;
import com.engine.salary.enums.salarybill.SalaryTemplateWatermarkTypeEnum;
import com.engine.salary.service.SalaryBillBaseSetService;
import com.engine.salary.service.SalaryBillWatermarkService;
import com.engine.salary.service.SalaryEmployeeService;
import com.engine.salary.sys.constant.SalarySysConstant;
import com.engine.salary.sys.entity.po.SalarySysConfPO;
import com.engine.salary.sys.service.SalarySysConfService;
import com.engine.salary.sys.service.impl.SalarySysConfServiceImpl;
import com.engine.salary.util.JsonUtil;
import com.engine.salary.util.SalaryEntityUtil;
import com.google.common.collect.Lists;
import com.engine.salary.util.db.IdGenerator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.general.Util;
import weaver.hrm.User;

import java.util.*;

import static com.engine.salary.sys.constant.SalarySysConstant.*;

/**
 * @Description: 工资单水印
 * @Author: wangxiangzhong
 * @Date: 2023/5/16 11:10
 */

public class SalaryBillBaseSetServiceImpl extends Service implements SalaryBillBaseSetService {

    private SalaryBillWatermarkService getSalaryBillWatermarkService(User user) {
        return ServiceUtil.getService(SalaryBillWatermarkServiceImpl.class, user);
    }

    private SalaryEmployeeService getSalaryEmployeeService(User user) {
        return ServiceUtil.getService(SalaryEmployeeServiceImpl.class, user);
    }

    public SalarySysConfService getSalarySysConfService(User user) {
        return ServiceUtil.getService(SalarySysConfServiceImpl.class, user);
    }

    @Override
    public SalaryBillWatermarkDTO getWatermarkSetting() {
        List<SalaryBillWatermarkPO> list = getSalaryBillWatermarkService(user).listAll();
        SalaryBillWatermarkPO watermarkPO = CollectionUtils.isNotEmpty(list) ? list.get(0) : null;

        if (Objects.isNull(watermarkPO)) {
            return null;
        }
        return SalaryBillWatermarkDTO.builder().watermarkStatus(NumberUtils.INTEGER_ONE.equals(watermarkPO.getWatermarkStatus())).watermarkType(watermarkPO.getWatermarkType()).wmSetting(JsonUtil.parseMap(watermarkPO.getWatermarkSetting(), Object.class)).build();
    }

    @Override
    public String saveBaseSet(SalaryBaseSetSaveParam saveParam) {
        // 检查参数
        SalaryBaseSetSaveParam.checkParam(saveParam);

        Date now = new Date();
        // 工资单水印===========================================================
        Integer watermarkStatus = NumberUtils.INTEGER_ONE;
        String watermark = null;
        String wmSetting = StringUtils.EMPTY;
        // 如果开启了
        if (saveParam.getWatermarkStatus()) {
            if (SalaryTemplateWatermarkTypeEnum.CUSTOM.equals(saveParam.getWatermark())) {
                wmSetting = JsonUtil.toJsonString(saveParam.getWmSetting());
            } else {
                // 系统默认水印 给一个默认的json
                wmSetting = "{\"wmWidth\":100,\"wmRotate\":30,\"wmSelectedFieldIds\":[\"HRM_Name\"],\"pureWmText\":\" 当前操作者姓名 \",\"wmText\":\"<p><span style=\\\"font-size:16px;\\\">&nbsp;<span>$HRM_Name</span>&nbsp;</span></p>\",\"wmClassify\":\"text\",\"wmHeight\":100,\"wmOriginText\":\"<p><span style=\\\"font-size:16px;\\\">&nbsp;<span contenteditable=\\\"false\\\" data-id=\\\"HRM_Name\\\">当前操作者姓名</span>&nbsp;</span></p>\",\"wmNoTransparent\":15}";
            }
            watermark = saveParam.getWatermark().getValue();
        } else {
            watermarkStatus = NumberUtils.INTEGER_ZERO;
        }

        // 将当前生效的水印信息都删除
        getSalaryBillWatermarkService(user).deleteAll();
        // 保存最新的水印信息
        getSalaryBillWatermarkService(user).insertIgnoreNull(SalaryBillWatermarkPO.builder().id(IdGenerator.generate()).watermarkStatus(watermarkStatus).watermarkType(watermark).watermarkSetting(wmSetting).createTime(now).updateTime(now).creator(Long.valueOf(user.getUID())).deleteType(NumberUtils.INTEGER_ZERO).tenantKey(SalaryDefaultTenantConstant.DEFAULT_TENANT_KEY).build());


        // 工资单确认和反馈 ===========================================================
        SalaryBillAckFeedbackDTO ackFeedbackSetting = saveParam.getAckFeedbackSetting();
        // 1.保存确认反馈开关状态
        getSalarySysConfService(user).saveSettingByType(ackFeedbackSetting.getAckStatus(), SALARY_SEND_FEEDBACK, "工资单确认状态", "billSend");
        getSalarySysConfService(user).saveSettingByType(ackFeedbackSetting.getFeedbackStatus(), SALARY_SEND_FEEDBACK_FK, "工资单反馈状态", "billSend");
        if (StringUtils.equals(ackFeedbackSetting.getAckStatus(), "1")) {
            // 保存自动确认时间
            getSalarySysConfService(user).saveSettingByType(ackFeedbackSetting.getAutoAckDays().toString(), SALARY_AUTO_ACK_DAYS, "工资单反馈自动确认", "billSend");
        }

        if (StringUtils.equals(ackFeedbackSetting.getFeedbackStatus(), "1")) {
            // 保存反馈地址
            getSalarySysConfService(user).saveSettingByType(ackFeedbackSetting.getFeedBackUrl(), SALARY_FEEDBACK_URL, "工资单反馈地址", "billSend");
            getSalarySysConfService(user).saveSettingByType(ackFeedbackSetting.getMobileFeedbackUrl(), SALARY_FEEDBACK_URL_MOBILE, "移动端工资单反馈地址", "billSend");
        }

        // 工资单时效性设置
        salaryBillViewingLimitSetting salaryBillViewingLimitDTO = saveParam.getSalaryBillViewingLimitSetting();
        if (salaryBillViewingLimitDTO != null) {
            getSalarySysConfService(user).saveSettingByType(Util.null2String(salaryBillViewingLimitDTO.getLimitMonth()), SALARY_BILL_VIEWING_LIMIT_MONTH, "工资单时效性设置", "billSend");
            getSalarySysConfService(user).saveSettingByType(Util.null2String(salaryBillViewingLimitDTO.getBurningAfterReadingMin()), SALARY_BILL_BURNING_AFTER_READING_MIN, "工资单查看后销毁设置", "billSend");
        }
        return StringUtils.EMPTY;
    }

    @Override
    public String previewWaterMark(Map<String, Object> wmSetting) {
        String wmText = wmSetting.getOrDefault("wmText", StringUtils.EMPTY).toString();
        List<String> wmTextFieldIds = (List<String>) wmSetting.getOrDefault("wmSelectedFieldIds", Lists.newArrayList());
        if (CollectionUtils.isEmpty(wmTextFieldIds) || StringUtils.isEmpty(wmText)) {
            return wmText;
        }
        DataCollectionEmployee simpleEmployee = getSalaryEmployeeService(user).getEmployeeById(Long.valueOf(user.getUID()));
        return SalaryBillBO.handleWmText(wmText, wmTextFieldIds, simpleEmployee);
    }

    @Override
    public SalaryBillAckFeedbackDTO getDefaultAckFeedbackSetting() {
        // 获取反馈开启状态、自动确认时长、反馈地址
        List<String> codes = Arrays.asList(SalarySysConstant.SALARY_SEND_FEEDBACK, SalarySysConstant.SALARY_SEND_FEEDBACK_FK ,SalarySysConstant.SALARY_AUTO_ACK_DAYS, SalarySysConstant.SALARY_FEEDBACK_URL, SALARY_FEEDBACK_URL_MOBILE);
        List<SalarySysConfPO> sysConfList = getSalarySysConfService(user).getListByCodes(codes);
        Map<String, String> sysConfMap = SalaryEntityUtil.convert2Map(sysConfList, SalarySysConfPO::getConfKey, SalarySysConfPO::getConfValue);

        SalaryBillAckFeedbackDTO defaultAckFeedBackDTO = SalaryBillAckFeedbackDTO.builder().build();
        String ackStatus = sysConfMap.getOrDefault(SalarySysConstant.SALARY_SEND_FEEDBACK, "0");
        // if (StringUtils.equals(ackStatus, "0")) {
        //     // 未开启工资单确认
        //     defaultAckFeedBackDTO.setAckStatus("0");
        //     defaultAckFeedBackDTO.setAutoAckDays(0);
        //     defaultAckFeedBackDTO.setFeedBackUrl("/");
        //     defaultAckFeedBackDTO.setMobileFeedbackUrl("/");
        //     return defaultAckFeedBackDTO;
        // }
        defaultAckFeedBackDTO.setAckStatus(ackStatus);


        String feedbackStatus = sysConfMap.get(SALARY_SEND_FEEDBACK_FK);
        if (feedbackStatus == null) {
            // 处理历史数据
            feedbackStatus = ackStatus;
        }
        defaultAckFeedBackDTO.setFeedbackStatus(feedbackStatus);

        // 获取超时自动确认时间
        Integer autoAckDays = Integer.valueOf(sysConfMap.getOrDefault(SalarySysConstant.SALARY_AUTO_ACK_DAYS, "7"));
        defaultAckFeedBackDTO.setAutoAckDays(autoAckDays);
        // 反馈地址
        String feedbackUrl = sysConfMap.getOrDefault(SalarySysConstant.SALARY_FEEDBACK_URL, "");
        defaultAckFeedBackDTO.setFeedBackUrl(feedbackUrl);

        String mobileFeedbackUrl = sysConfMap.getOrDefault(SALARY_FEEDBACK_URL_MOBILE, "");
        defaultAckFeedBackDTO.setMobileFeedbackUrl(mobileFeedbackUrl);
        return defaultAckFeedBackDTO;
    }

    @Override
    public salaryBillViewingLimitSetting getSalaryBillViewingLimitSetting() {
        SalarySysConfPO limitMonthSetting = getSalarySysConfService(user).getOneByCode(SALARY_BILL_VIEWING_LIMIT_MONTH);
        int limitMonth = 0;
        if (limitMonthSetting != null && NumberUtils.isNumber(limitMonthSetting.getConfValue())) {
            limitMonth = Integer.parseInt(limitMonthSetting.getConfValue());
        }
        return salaryBillViewingLimitSetting.builder().limitMonth(limitMonth).build();
    }

    @Override
    public Integer getBurningAfterReadingMin() {
        SalarySysConfPO ineffectiveMinSetting = getSalarySysConfService(user).getOneByCode(SALARY_BILL_BURNING_AFTER_READING_MIN);
        if (ineffectiveMinSetting == null || StringUtils.isBlank(ineffectiveMinSetting.getConfValue()) || !NumberUtils.isNumber(ineffectiveMinSetting.getConfValue())) {
            // 代表该设置不生效，即首次读后可以一直查看
            return null;
        } else {
            return Integer.parseInt(ineffectiveMinSetting.getConfValue());
        }
    }
}
