package com.ssm.manage.service.impl;

import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmStaffWorksDao;
import com.ssm.manage.entity.StaffWorks;
import com.ssm.manage.query.StaffWorkRequest;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.SsmStaffWorksService;
import com.ssm.util.RedisClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SsmStaffWorksServiceImpl extends BaseServiceImpl<StaffWorks> implements SsmStaffWorksService {
    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmStaffWorksDao dao;

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

    private static String KEY = "staffKey";

    @Override
    public List<StaffWorks> selectList(StaffWorkRequest staffWorkRequest) {
        StaffWorks staffWorks = new StaffWorks();
        staffWorks.setStaffId(staffWorkRequest.getStaffId());
        List<StaffWorks> list = dao.select(staffWorks);
        return list;
    }

    @Override
    public int addStaffWorks(StaffWorks staffWorks,String phone) {
        staffWorks.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//        staffWorks.setPictureFile();
//        staffWorks.setPictureFilePath();
        String key = getKey(phone);
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(key)){
            staffResponse = redisClient.get(key);
            staffWorks.setUploadUser(staffResponse.getStaffName());
            staffWorks.setUploadTelephone(staffResponse.getMobilePhone());
        }
        Set<String> keys = redisClient.keys(key + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String k =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(k);
            staffWorks.setUploadUser(staffResponse.getStaffName());
            staffWorks.setUploadTelephone(staffResponse.getMobilePhone());
        }
        staffWorks.setUploadTime(new Date());
        return dao.saveNotNull(staffWorks);
    }

    @Override
    public int deleteStaffWorks(StaffWorkRequest staffWorkRequest) {
        StaffWorks staffWorks = new StaffWorks();
        staffWorks.setId(staffWorkRequest.getId());
        return dao.deleteByPrimaryKey(staffWorks);
    }


    public static String getKey(String phone) {
        String key = "";
        if (StringUtils.isNotBlank(phone)){
            key = KEY + phone;
        }
        return key;
    }
}
