package com.hzs.system.config.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.core.enums.ERegisterPage;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.domain.system.config.BdRegisterPage;
import com.hzs.system.config.mapper.BdRegisterPageMapper;
import com.hzs.system.config.service.IBdRegisterPageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 注册页面配置 服务实现类
 *
 * @author hzs
 * @since 2022-10-18
 */
@Service
public class BdRegisterPageServiceImpl extends ServiceImpl<BdRegisterPageMapper, BdRegisterPage> implements IBdRegisterPageService {

    @Override
    public List<BdRegisterPage> queryList(Integer pkCountry) {
        QueryWrapper<BdRegisterPage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.orderByAsc("PK_ID");
        return baseMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveData(List<String> registerPageFieldList, Long userId, Integer pkCountry) {
        Date nowDate = new Date();

        // 删除旧数据
        UpdateWrapper<BdRegisterPage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
        baseMapper.update(null, updateWrapper);

        for (String field : registerPageFieldList) {
            ERegisterPage eRegisterPage = ERegisterPage.getEnumByValue(field);
            if (null != eRegisterPage) {
                BdRegisterPage bdRegisterPage = new BdRegisterPage();
                bdRegisterPage.setField(eRegisterPage.getValue());
                bdRegisterPage.setName(eRegisterPage.getLabel());
                bdRegisterPage.setDisplay(EYesNo.YES.getIntValue());
                bdRegisterPage.setPkCountry(pkCountry);
                bdRegisterPage.setPkCreator(userId);
                bdRegisterPage.setCreationTime(nowDate);
                baseMapper.insert(bdRegisterPage);
            }
        }
    }
}
