package io.renren.application.common.service.imp;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.application.common.dto.ChaoXiangParamDto;
import io.renren.application.common.entity.SysPublicParam;
import io.renren.application.common.mapper.SysPublicParamMapper;
import io.renren.application.common.service.SysPublicParamService;
import io.renren.application.common.vo.ChaoXiangParamVo;
import io.renren.application.common.vo.Results;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SysPublicParamServiceImpl extends ServiceImpl<SysPublicParamMapper, SysPublicParam> implements SysPublicParamService {

    String CHAO_XIANG_PARAM_PRE = "CHAO_XIANG_PARAM_QRCODE_WEEK_";
    @Override
    public Results modeifyParam(ChaoXiangParamDto dto) {
        if (dto.getValues()==null){
            dto.setValues(new ArrayList<>(7));//初始化
        }
        Integer size = 6;
        while (dto.getValues().size()<7){
            dto.getValues().add("");//补全
        }
        for (int i = 0; i <size ; i++) {
            String value = dto.getValues().get(i);
            String key = CHAO_XIANG_PARAM_PRE+(i+1);
            SysPublicParam publicParam = getOne(Wrappers.<SysPublicParam>lambdaQuery().eq(SysPublicParam::getPublicKey,key));
            if (publicParam==null){
                publicParam = new SysPublicParam();
                publicParam.setPublicKey(key);
            }
            publicParam.setPublicValue(value);
            publicParam.setStatus(1);
            publicParam.insertOrUpdate();
        }
        return Results.success();
    }

    @Override
    public Results<ChaoXiangParamVo> getAllWeekParam() {
        List<ChaoXiangParamVo> list = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            ChaoXiangParamVo vo = new ChaoXiangParamVo();
            String name = DayOfWeek.of(i).name();
            String value = null;
            SysPublicParam publicParam = getOne(Wrappers.<SysPublicParam>lambdaQuery().eq(SysPublicParam::getPublicKey,CHAO_XIANG_PARAM_PRE+i));
            if (publicParam !=null){
                value = publicParam.getPublicValue();
            }
            vo.setName(name);
            vo.setValue(value);
            list.add(vo);
        }
        return Results.success(list);
    }

    @Override
    public Results<String> getWeekParam() {
        int i = LocalDateTime.now().getDayOfWeek().getValue();
        SysPublicParam publicParam = getOne(Wrappers.<SysPublicParam>lambdaQuery().eq(SysPublicParam::getPublicKey,CHAO_XIANG_PARAM_PRE+i));
        if (publicParam ==null){
            return Results.success();
        }
        return Results.success(publicParam.getPublicValue());
    }

}
