package com.ssm.manage.service.impl;

import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmStoreManagementDao;
import com.ssm.manage.entity.BaseStaff;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.entity.StoreManagement;
import com.ssm.manage.entity.SysUser;
import com.ssm.manage.query.StoreManagementRequest;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.SsmStoreManagementService;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class SsmStoreManagementServiceImpl extends BaseServiceImpl<StoreManagement> implements SsmStoreManagementService {
    @Autowired
    private SsmStoreManagementDao dao;

    @Autowired
    private RedisClient<UserResponse> redisClient;

    @Override
    public SsmStoreManagementDao getDao() {
        return dao;
    }

    @Override
    public List<StoreManagement> selectList(StoreManagementRequest storeManagementRequest) {
        List<StoreManagement> list = new ArrayList<>();
        StoreManagement storeManagement = new StoreManagement();
        storeManagement.setStoreIds(storeManagementRequest.getStoreIds());
        list = dao.select(storeManagement);
        return list;
    }

    @Override
    public int saveBatch(List<StoreManagement> storeManagements, String userNum) throws SmsException {
        //先删除当前分配的门店之前存在的所有关系
        StoreManagement storeManagement = new StoreManagement();
        storeManagement.setStoreIds(storeManagements.get(0).getStoreIds());
        int delete = dao.delete(storeManagement);
        if(delete>0){
            //从redis获取当前操作人信息 将添加用户的创建人和创建时间进行赋值
            if (redisClient.hasKey(getKey(userNum))){
                UserResponse userResponse = redisClient.get(getKey(userNum));
                for (StoreManagement management : storeManagements) {
                    management.setFunderName(userResponse.getUserName());
                    management.setFunderDate(new Date());
                    //生成主键
                    management.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                }
            }
            int i = dao.insertList(storeManagements);
            return i;
        }else{
            throw new RuntimeException("操作失败");
        }
    }

    public String getKey(String userNum){
        String key = "";
        if (StringUtils.isNotBlank(userNum)){
            key = Constant.userKey + userNum;
        }
        return key;
    }
}
