package com.ruoyi.web.modules.content.service.impl;

import java.nio.charset.StandardCharsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.content.constant.MerchantEntryAgreementConstants;
import com.ruoyi.web.modules.content.domain.BizMerchantEntryAgreement;
import com.ruoyi.web.modules.content.mapper.BizMerchantEntryAgreementMapper;
import com.ruoyi.web.modules.content.service.IMerchantEntryAgreementService;
import com.ruoyi.web.modules.content.support.AgreementContentSupport;
import com.ruoyi.web.modules.content.vo.MerchantEntryAgreementAppVO;
import com.ruoyi.web.modules.content.vo.MerchantEntryAgreementConfigVO;
import com.ruoyi.web.modules.content.vo.MerchantEntryStatusVO;

/**
 * 商家入驻协议服务实现
 */
@Service
public class MerchantEntryAgreementServiceImpl implements IMerchantEntryAgreementService
{
    private static final String DICT_YES_NO = "sys_yes_no";

    @Autowired
    private BizMerchantEntryAgreementMapper agreementMapper;

    @Override
    public MerchantEntryAgreementConfigVO getConfig()
    {
        BizMerchantEntryAgreement row = loadRowOrDefault();
        return toConfigVo(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveConfig(BizMerchantEntryAgreement row, String operator)
    {
        validateSave(row);
        BizMerchantEntryAgreement existing = agreementMapper.selectById(MerchantEntryAgreementConstants.CONFIG_ID);
        row.setConfigId(MerchantEntryAgreementConstants.CONFIG_ID);
        if (existing == null)
        {
            row.setCreateBy(operator);
            if (agreementMapper.insert(row) <= 0)
            {
                throw new ServiceException("保存失败");
            }
        }
        else
        {
            row.setUpdateBy(operator);
            if (agreementMapper.update(row) <= 0)
            {
                throw new ServiceException("保存失败");
            }
        }
    }

    @Override
    public MerchantEntryAgreementAppVO getForApp()
    {
        MerchantEntryAgreementAppVO vo = new MerchantEntryAgreementAppVO();
        if (!isEnabled())
        {
            vo.setEnabled(false);
            vo.setMessage(MerchantEntryAgreementConstants.MSG_ENTRY_CLOSED);
            return vo;
        }
        BizMerchantEntryAgreement row = agreementMapper.selectById(MerchantEntryAgreementConstants.CONFIG_ID);
        vo.setEnabled(true);
        vo.setAgreementTitle(row.getAgreementTitle());
        vo.setVersionLabel(row.getVersionLabel());
        vo.setContent(row.getContent());
        vo.setCheckboxLabel(buildCheckboxLabel(row.getAgreementTitle(), row.getVersionLabel()));
        return vo;
    }

    @Override
    public MerchantEntryStatusVO getEntryStatus()
    {
        MerchantEntryStatusVO vo = new MerchantEntryStatusVO();
        vo.setEntryOpen(isEnabled());
        return vo;
    }

    @Override
    public boolean isEnabled()
    {
        BizMerchantEntryAgreement row = agreementMapper.selectById(MerchantEntryAgreementConstants.CONFIG_ID);
        if (row == null)
        {
            return false;
        }
        return MerchantEntryAgreementConstants.ENABLE_YES.equals(row.getEnableFlag())
                && !AgreementContentSupport.isBlankHtml(row.getContent());
    }

    @Override
    public void assertAccepted(boolean agreementAccepted)
    {
        if (!isEnabled())
        {
            throw new ServiceException(MerchantEntryAgreementConstants.MSG_ENTRY_CLOSED);
        }
        if (!agreementAccepted)
        {
            throw new ServiceException(MerchantEntryAgreementConstants.MSG_AGREE_REQUIRED);
        }
    }

    @Override
    public String buildCheckboxLabel(String agreementTitle, String versionLabel)
    {
        String title = StringUtils.isEmpty(agreementTitle) ? "" : agreementTitle.trim();
        if (StringUtils.isEmpty(versionLabel))
        {
            return "我已阅读并同意《" + title + "》";
        }
        return "我已阅读并同意《" + title + "》（" + versionLabel.trim() + "）";
    }

    void validateSave(BizMerchantEntryAgreement row)
    {
        if (row == null)
        {
            throw new ServiceException("参数不能为空");
        }
        if (StringUtils.isEmpty(row.getAgreementTitle()) || StringUtils.isEmpty(row.getAgreementTitle().trim()))
        {
            throw new ServiceException(MerchantEntryAgreementConstants.MSG_TITLE_REQUIRED);
        }
        String title = row.getAgreementTitle().trim();
        if (title.length() > MerchantEntryAgreementConstants.MAX_TITLE_LENGTH)
        {
            throw new ServiceException("协议标题长度不能超过128个字符");
        }
        row.setAgreementTitle(title);
        if (StringUtils.isNotEmpty(row.getVersionLabel()))
        {
            String version = row.getVersionLabel().trim();
            if (version.length() > MerchantEntryAgreementConstants.MAX_VERSION_LENGTH)
            {
                throw new ServiceException("协议版本号长度不能超过32个字符");
            }
            row.setVersionLabel(version);
        }
        else
        {
            row.setVersionLabel(null);
        }
        validateEnableFlag(row.getEnableFlag());
        if (row.getContent() != null && row.getContent().getBytes(StandardCharsets.UTF_8).length
                > MerchantEntryAgreementConstants.MAX_CONTENT_BYTES)
        {
            throw new ServiceException("协议内容超出允许的最大长度");
        }
        if (MerchantEntryAgreementConstants.ENABLE_YES.equals(row.getEnableFlag()))
        {
            if (AgreementContentSupport.isBlankHtml(row.getContent()))
            {
                if (StringUtils.isEmpty(row.getContent()))
                {
                    throw new ServiceException(MerchantEntryAgreementConstants.MSG_CONTENT_REQUIRED_WHEN_ENABLED);
                }
                throw new ServiceException(MerchantEntryAgreementConstants.MSG_CONTENT_BLANK);
            }
        }
    }

    private void validateEnableFlag(String enableFlag)
    {
        if (!MerchantEntryAgreementConstants.ENABLE_YES.equals(enableFlag)
                && !MerchantEntryAgreementConstants.ENABLE_NO.equals(enableFlag))
        {
            throw new ServiceException(MerchantEntryAgreementConstants.MSG_ENABLE_FLAG_INVALID);
        }
    }

    private BizMerchantEntryAgreement loadRowOrDefault()
    {
        BizMerchantEntryAgreement row = agreementMapper.selectById(MerchantEntryAgreementConstants.CONFIG_ID);
        if (row != null)
        {
            return row;
        }
        BizMerchantEntryAgreement empty = new BizMerchantEntryAgreement();
        empty.setConfigId(MerchantEntryAgreementConstants.CONFIG_ID);
        empty.setAgreementTitle("");
        empty.setContent("");
        empty.setEnableFlag(MerchantEntryAgreementConstants.ENABLE_NO);
        return empty;
    }

    private MerchantEntryAgreementConfigVO toConfigVo(BizMerchantEntryAgreement row)
    {
        MerchantEntryAgreementConfigVO vo = new MerchantEntryAgreementConfigVO();
        vo.setConfigId(row.getConfigId());
        vo.setAgreementTitle(row.getAgreementTitle());
        vo.setVersionLabel(row.getVersionLabel());
        vo.setContent(row.getContent());
        vo.setEnableFlag(row.getEnableFlag());
        vo.setUpdateBy(row.getUpdateBy());
        vo.setUpdateTime(row.getUpdateTime());
        vo.setEnableFlagLabel(resolveEnableFlagLabel(row.getEnableFlag()));
        return vo;
    }

    private String resolveEnableFlagLabel(String enableFlag)
    {
        try
        {
            String label = DictUtils.getDictLabel(DICT_YES_NO, enableFlag);
            if (StringUtils.isNotEmpty(label))
            {
                return label;
            }
        }
        catch (Exception ignored)
        {
        }
        return MerchantEntryAgreementConstants.ENABLE_YES.equals(enableFlag) ? "是" : "否";
    }
}
