package com.heyu.api.controller.mm;


import com.alibaba.fastjson.JSON;
import com.heyu.api.alibaba.request.mm.VVAdminRequest;
import com.heyu.api.common.annotation.AdminNotNeedLogin;
import com.heyu.api.common.annotation.Describe;
import com.heyu.api.data.constants.RedisConstans;
import com.heyu.api.data.dao.vv.VvAdminDao;
import com.heyu.api.data.dao.vv.VvLoginLogDao;
import com.heyu.api.data.dto.vv.VVAdminDTO;
import com.heyu.api.data.entity.vv.VvAdminEntity;
import com.heyu.api.data.entity.vv.VvLoginLogEntity;
import com.heyu.api.data.utils.DateUtils;
import com.heyu.api.data.utils.MD5Utils;
import com.heyu.api.data.utils.R;
import com.heyu.api.data.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/mm/user/")
@AdminNotNeedLogin
public class AdminLoginController {

    @Autowired
    private VvAdminDao vvAdminDao;

    @Autowired
    private VvLoginLogDao vvLoginLogDao;

    @Autowired
    private RedisUtils redisUtils;

    /***
     * mmToken
     *
     * token
     *
     * 列表
     * http://localhost:8888/mm/user/login
     *
     * https://api.1024api.com/api-interface//mm/admin/login
     *
     * {"username":"admin","password":"admin123"}
     */
    @Describe("后台用户登录")
    @RequestMapping("/login")
    public R list(@RequestBody VVAdminRequest vvAdminRequest) {
        VVAdminDTO vvAdminDTO = new VVAdminDTO();
        VvAdminEntity vvAdminEntity = vvAdminDao.selectVvAdminByUserName(vvAdminRequest.getUsername());
        // admin123   !=  '1'  or 1 = 1
        if (vvAdminEntity.getPassword().equals(vvAdminRequest.getPassword())) {
            String token = MD5Utils.getMD5(System.currentTimeMillis() + vvAdminRequest.getUsername());

            vvAdminDTO.setToken(token);
            vvAdminDTO.setUsername(vvAdminRequest.getUsername());
            vvAdminDTO.setExpireTime(DateUtils.addDays(new Date(), 7).getTime());
            vvAdminDTO.setAdminId(vvAdminEntity.getId());

            VvLoginLogEntity vvLoginLogEntity = new VvLoginLogEntity();
            vvLoginLogDao.deleteVvLoginLogRealByUserName(vvAdminRequest.getUsername());

            vvLoginLogEntity.setUsername(vvAdminRequest.getUsername());
            vvLoginLogEntity.setToken(token);
            vvLoginLogDao.insertOrUpdateVvLoginLog(vvLoginLogEntity);

            redisUtils.set(token, JSON.toJSONString(vvAdminDTO), RedisConstans.SECOND_OF_ONE_7_DAY);

            return R.ok().setData(vvAdminDTO);
        }
        return R.ok("密码错误");
    }

}
