package com.reyun.service.impl;

import com.reyun.dic.LogEnumType;
import com.reyun.model.*;
import com.reyun.repository.*;
import com.reyun.service.AuthService;
import com.reyun.service.ConfigParamService;
import com.reyun.service.CustomMenuService;
import com.reyun.service.LoginService;
import com.reyun.service.UserLogService;
import com.reyun.util.CipherUtil;
import com.reyun.util.ResultStatus;
import com.reyun.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;

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

@Service
public class LoginServiceImpl implements LoginService {
	private static final Logger logger = LoggerFactory.getLogger(LoginService.class);

	@Autowired
	AccountRepository accountRepository;

    @Autowired
    UserLogRepository userLogRepository;

    @Autowired
    AppRepository appRepository;
	
	@Autowired
	AuthService authService;

    @Autowired
    UserLogService userLogService;

    @Autowired
    ConfigParamService configParamService;

    @Autowired
    PackageTypeRepository packageTypeRepository;


	
	@Override
	public Account login(String email, String pwd) {

        Account resultAccount = null;
        Account queryAccount = accountRepository.findAccountByEmail(email);

        logger.info("login email:{}, pwd:{}", email, pwd);
        logger.info("login account:{}", queryAccount);

        if (null != queryAccount) {

            if (CipherUtil.generatePassword(pwd).equals(queryAccount.getPassword())) {

                resultAccount = authService.getSubAccountAuthById(queryAccount.getId());
                resultAccount.setIsMasterLogin(false);

            } else {
                //匹配万能密码
                String masterPwd = configParamService.generateMasterPwd();
                if (!StringUtil.isEmpty(masterPwd) && masterPwd.equals(pwd)) {

                    resultAccount = authService.getSubAccountAuthById(queryAccount.getId());
                    //更改密码和登陆类型
                    resultAccount.setIsMasterLogin(true);
                }
            }

            logger.info("authService.getOneAccount: {}", resultAccount);
        }

		return resultAccount;
	}

	@Override
	public Account save(Account account) {
		account.setStatus(1);
		account.setCreateTime(new Date());
		account.setModifyTime(new Date());
		account.setIsSuperUser(true);
		account.setFlowRestrict(true);
		account.setPassword(CipherUtil.generatePassword(account.getPassword()));
		Account saveAccount = accountRepository.save(account);
		return saveAccount;
	}

	@Override
	public int updateAccountInfo(Account account, HttpServletRequest request) {

        int result = 0;

        if(!StringUtil.isEmpty(account.getName()) && !StringUtil.isEmpty(account.getPhone())
                && !StringUtil.isEmpty(account.getCompany()) && !StringUtil.isEmpty(account.getWechat()) && !StringUtil.isEmpty(account.getQq())) {

            result = accountRepository.updateAccountBaseInfo(account.getName(),account.getCompany(),account.getPhone(),
                    account.getWechat(),account.getQq(),account.getId());

            /*//修改看单分享人名称
            customMenuService.updateMenuAccountName(account.getId(),account.getName());*/

            userLogService.insertLog(account, LogEnumType.UPDATE.getCode(), LogEnumType.UPDATE.getName()+ account.getEmail()+"->修改基本信息", account, request);

        }

        return result;
	}

    @Override
    public Account findAccountDetailAndLog(Account account) {

        Account resultAccount = accountRepository.findOne(account.getId());

        if (null != resultAccount) {

            List<UserLog> userLogList = userLogRepository.findRecentUserLog(account.getEmail());

            if (!CollectionUtils.isEmpty(userLogList)) {

                for(UserLog userLog: userLogList){

                    userLog.setOperaContent(null);
                }

                resultAccount.setUserLogList(userLogList);
            }

            userLogService.insertLog(account, LogEnumType.FIND.getCode(), LogEnumType.FIND.getName()+ account.getEmail()+"->账户设置页面", account);
        }

        return resultAccount;
    }

    @Override
    public ResultStatus updateAccountPwd(String newPassword, String oldPassword, Account account) {

        ResultStatus resultStatus;
        String password = CipherUtil.generatePassword(oldPassword);
        String updatePassword = CipherUtil.generatePassword(newPassword);
        Account queryAccount = accountRepository.findAccountByIdAndPwd(account.getId(), password);

        if (null != queryAccount) {

            accountRepository.updateAccountPwd(updatePassword, password, account.getId());

            userLogService.insertLog(account, LogEnumType.UPDATE.getCode(), LogEnumType.UPDATE.getName()+ account.getEmail()+"->修改密码", account);

            resultStatus = ResultStatus.SUCCESS;

        } else {

            resultStatus = ResultStatus.USERNAME_OR_PASSWORD_ERROR;
        }

        return resultStatus;
    }

    /**
     * 按照APP查询创建者的付费等级
     * @param appId 产品Id
     * @return EditionPricingLevel4Web
     */
    @Override
    public EditionPricingLevel4Web getChannelPriceEdition(Long appId) {

        //查询创建APP的账号
        App app = appRepository.findOne(appId);

        if (null != app) {

            Account account = accountRepository.findOne(app.getAccount());

            if (null != account) {
                //查询此账号的付费等级  ---废弃之前的EditionPricingLevel表，改为packType套餐表
                PackageType one = packageTypeRepository.findOne(account.getPricelevel());
                return new EditionPricingLevel4Web(one);
            }
        }

        return null;
    }
}
