package com.bizzan.bitrade.controller.member;

import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.dao.DeviceBlacklistDao;
import com.bizzan.bitrade.entity.DeviceBlacklist;
import com.bizzan.bitrade.util.MessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/device-monitor")
@Slf4j
public class DeviceMonitorController extends BaseAdminController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DeviceBlacklistDao deviceBlacklistDao;

    @PostMapping("/page")
    public MessageResult page(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "20") int pageSize,
            @RequestParam(required = false) Long memberId,
            @RequestParam(required = false) String deviceFingerprint,
            @RequestParam(required = false) String deviceModel) {

        StringBuilder where = new StringBuilder(" WHERE 1=1");
        List<Object> params = new ArrayList<>();

        if (memberId != null) {
            where.append(" AND d.member_id = ?");
            params.add(memberId);
        }
        if (StringUtils.hasText(deviceFingerprint)) {
            where.append(" AND d.device_fingerprint LIKE ?");
            params.add("%" + deviceFingerprint + "%");
        }
        if (StringUtils.hasText(deviceModel)) {
            where.append(" AND d.device_model LIKE ?");
            params.add("%" + deviceModel + "%");
        }

        String countSql = "SELECT COUNT(*) FROM member_device d" + where;
        long total = jdbcTemplate.queryForObject(countSql, params.toArray(), Long.class);

        String dataSql = "SELECT d.id, d.member_id, d.device_fingerprint, d.device_type, d.device_model," +
                " d.os_version, d.login_count, d.last_login_ip," +
                " DATE_FORMAT(d.first_login_time, '%Y-%m-%d %H:%i:%s') AS first_login_time," +
                " DATE_FORMAT(d.last_login_time, '%Y-%m-%d %H:%i:%s') AS last_login_time," +
                " CASE WHEN b.device_fingerprint IS NOT NULL THEN 1 ELSE 0 END AS banned," +
                " cnt.account_count" +
                " FROM member_device d" +
                " LEFT JOIN device_blacklist b ON d.device_fingerprint = b.device_fingerprint" +
                " LEFT JOIN (" +
                "   SELECT device_fingerprint, COUNT(DISTINCT member_id) AS account_count" +
                "   FROM member_device GROUP BY device_fingerprint" +
                " ) cnt ON cnt.device_fingerprint = d.device_fingerprint" +
                where +
                " ORDER BY cnt.account_count DESC, d.last_login_time DESC LIMIT ? OFFSET ?";
        List<Object> dataParams = new ArrayList<>(params);
        dataParams.add(pageSize);
        dataParams.add((pageNo - 1) * pageSize);

        List<Map<String, Object>> list = jdbcTemplate.queryForList(dataSql, dataParams.toArray());

        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("list", list);
        result.put("pageNo", pageNo);
        result.put("pageSize", pageSize);
        return success(result);
    }

    @PostMapping("/ban")
    public MessageResult ban(
            @RequestParam String deviceFingerprint,
            @RequestParam(required = false, defaultValue = "") String reason) {

        if (!StringUtils.hasText(deviceFingerprint)) {
            return error("设备指纹不能为空");
        }
        if (deviceBlacklistDao.existsByDeviceFingerprint(deviceFingerprint)) {
            return error("该设备已在黑名单中");
        }
        DeviceBlacklist blacklist = new DeviceBlacklist();
        blacklist.setDeviceFingerprint(deviceFingerprint);
        blacklist.setReason(reason);
        deviceBlacklistDao.save(blacklist);
        return success("封禁成功");
    }

    @PostMapping("/unban")
    @Transactional
    public MessageResult unban(@RequestParam String deviceFingerprint) {
        if (!StringUtils.hasText(deviceFingerprint)) {
            return error("设备指纹不能为空");
        }
        if (!deviceBlacklistDao.existsByDeviceFingerprint(deviceFingerprint)) {
            return error("该设备不在黑名单中");
        }
        deviceBlacklistDao.deleteByDeviceFingerprint(deviceFingerprint);
        return success("解封成功");
    }
}
