package common.task;

import common.context.AppUtils;
import common.model.Contract;
import common.model.User;
import common.model.UserLog;
import common.repository.UserLogRepository;
import common.repository.UserRepository;
import dic.RoleTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import tkio.model.PackageType;
import tkio.repository.PackageTypeRepository;
import util.DateUtil;
import util.IPAddrUtil;
import util.MailUtils;
import util.ValidateUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by zxy on 2017/12/15.
 */
public class ContractSendEmailThread
        extends Thread
{
    protected Logger logger = LoggerFactory.getLogger(ContractSendEmailThread.class);

    private PackageTypeRepository packageTypeRepository = AppUtils.getApplicationContext().getBean(PackageTypeRepository.class);
    private UserRepository userRepository = AppUtils.getApplicationContext().getBean(UserRepository.class);

    private Contract contract;

    public ContractSendEmailThread(Contract contract) {
        this.contract = contract;
    }

    @Override
    public void run()
    {
        Map<Long, String> packageMap = getPackageMap();
        StringBuffer sb = new StringBuffer();
        sb.append("账号 :" + this.contract.getEmail() + " 签约了," + " 套餐 ：" +
                packageMap.get(this.contract.getPriceLevel()) + ",开始时间 " + this.contract.getStartDate()
                + ",结束时间 " +  this.contract.getEndDate());
        User user = userRepository.findOne(this.contract.getSale());
        List<String> list = new ArrayList<>();
        list.add(user.getEmail());
        if(!user.getRoleType().equals(RoleTypeEnum.MANAGER)){
            List<User> userList = userRepository.findOneDepartment(user.getRole());
            for(User u : userList){
                if (u.getRoleType().equals(RoleTypeEnum.MANAGER)){
                    list.add(u.getEmail());
                }
            }
        }


        try {
            MailUtils.sendSimpleEmail("新建合同",  sb.toString(),list);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public Map<Long, String> getPackageMap(){
        List<PackageType> typeList = packageTypeRepository.findAll();
        Map<Long, String> typeMap = new HashMap<>();
        if(ValidateUtil.isValid(typeList)){
            for(PackageType s: typeList){
                typeMap.put(s.getId(), s.getPackageName());
            }
        }
        return typeMap;
    }
}
