package com.cxyxiaomo.epp.access.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cxyxiaomo.epp.PageTable.enums.AddType;
import com.cxyxiaomo.epp.PageTable.enums.EditType;
import com.cxyxiaomo.epp.PageTable.enums.FieldType;
import com.cxyxiaomo.epp.PageTable.enums.SearchType;
import com.cxyxiaomo.epp.PageTable.query.PageQuery;
import com.cxyxiaomo.epp.PageTable.utils.FieldBuilder;
import com.cxyxiaomo.epp.PageTable.utils.FieldMapperBuilder;
import com.cxyxiaomo.epp.access.rpc.UserServiceFeign;
import com.cxyxiaomo.epp.access.service.AccessLogService;
import com.cxyxiaomo.epp.access.service.GateService;
import com.cxyxiaomo.epp.common.pojo.AccessLog;
import com.cxyxiaomo.epp.common.pojo.Gate;
import com.cxyxiaomo.epp.common.pojo.User;
import com.cxyxiaomo.epp.common.query.AccessLogQuery;
import com.cxyxiaomo.epp.common.response.Res;
import com.cxyxiaomo.epp.common.vo.AccessLogVO;
import com.cxyxiaomo.epp.common.vo.GateVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/access/access-log")
public class AccessLogController {

    @Resource
    GateService gateService;

    @Resource
    UserServiceFeign userService;

    @Resource
    AccessLogService accessLogService;

    /**
     * 进入进出记录（小程序端）
     *
     * @return
     */
    @GetMapping("/miniprogram/enterGate")
    @ResponseBody
    public Res enterAccessLog(Integer userId, String gateId, String type/*'IN','OUT'*/) throws Exception {
        if (Objects.isNull(type) || !("IN".equals(type) || "OUT".equals(type))) {
            return Res.error("参数错误");
        }

        Gate gate = gateService.getGateById(Long.valueOf(gateId));
        User user = userService.getUserById(userId);
        if (user == null || gate == null) {
            return Res.error("参数错误");
        }

        // 推送到门禁端
        JSONObject websocketData = new JSONObject();
        websocketData.put("gateId", gateId);
        websocketData.put("action", "onopen");
        String websocketJSON = websocketData.toString();
        WebSocketServer.sendAllMessage(websocketJSON);

        AccessLog accessLog = new AccessLog();
        accessLog.setId(null);
        accessLog.setType(type);
        accessLog.setTime(new Date());
        accessLog.setUserId(user.getId());
        accessLog.setUserRealName(user.getRealname());
        accessLog.setGateId(gate.getId());

        boolean b = accessLogService.addAccessLog(accessLog);
        return Res.success(b);
    }

    /**
     * 获取进出记录列表
     *
     * @return
     */
    @GetMapping("/manage/getAccessLogList")
    @ResponseBody
    public Res getAccessLogList(PageQuery pageQuery, AccessLogQuery accessLogQuery) {
        // 查询分页数据
        PageHelper.startPage(pageQuery.getPageIndex(), pageQuery.getPageSize());
        List<AccessLog> accessLogList = accessLogService.getAccessLogList(accessLogQuery);
        PageInfo<AccessLog> accessLogPageInfo = new PageInfo<>(accessLogList);
        List<AccessLog> list = accessLogPageInfo.getList();
        List<AccessLogVO> voList = AccessLogVO.convertFrom(list);

        // id列 字段名（区分大小写；以VO中的变量名为准）
        // 新增、修改弹窗时，使用该列作为主键列进行操作
        String idFieldName = "id";

        // 当前管理页面
        String pageName = "进出记录管理";

        // 指定前端表格显示列
        JSONArray columns = FieldBuilder.create()
                .add("timestamp", "timestamp", "打卡时间", "",
                        FieldType.DATETIME, SearchType.DATETIME_INTERVAL, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        null, null, null, null
                )
                .add("userId", "userId", "用户id", "",
                        FieldType.TEXT, SearchType.INPUT, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        null, null, null, null
                )
                .add("userRealName", "userRealName", "用户真实姓名", "",
                        FieldType.TEXT, SearchType.INPUT, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        null, null, null, null
                )
                .add("gateId", "gateId", "大门id", "",
                        FieldType.TEXT, SearchType.CAN_NOT_SEARCH, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        null, null, null, null
                )
                .add("gateId", "gateName", "大门名称", "",
                        FieldType.TEXT, SearchType.SELECT, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                        "大门",
                        null, null, null, null
                )
                // .add("type", "typeStatus", "类型", true,
                //         FieldType.TEXT, SearchType.SELECT, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                //         FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                //         "状态", FieldBuilder.EDIT_PLACEHOLDER_SAME_AS_ADD_PLACEHOLDER,
                //         FieldRuleListBuilder.create(),
                //         "DPD @pick(['true', 'false'])"
                // )
                .build();

        // 指定需要翻译的字段
        List<Gate> gateList = gateService.getGateList(new GateVO());
        HashMap gateMap = new HashMap();
        for (Gate gate : gateList) {
            gateMap.put(gate.getId(), gate.getName());
        }
        HashMap<Object, Object> stateMap = new HashMap<>(2);
        stateMap.put(true, "进入社区");
        stateMap.put(false, "离开社区");
        // build
        JSONArray fieldMapper = FieldMapperBuilder.create()
                .add("gateId", "gateName", gateMap)
                .add("type", "typeStatus", stateMap)
                .build();

        // 拼装返回结果
        JSONObject map = new JSONObject(6);
        map.put("total", accessLogPageInfo.getTotal());
        map.put("list", voList);
        map.put("columns", columns);
        map.put("fieldMapper", fieldMapper);
        map.put("idFieldName", idFieldName);
        map.put("pageName", pageName);

        // 返回结果
        return Res.success(map);
    }

    /**
     * 导出进出记录列表
     *
     * @return
     */
    @GetMapping("/manage/exportAccessLogList")
    @ResponseBody
    public Res exportAccessLogList(AccessLogQuery accessLogQuery) {
        List<AccessLog> accessLogList = accessLogService.getAccessLogList(accessLogQuery);
        List<AccessLogVO> accessLogVOList = AccessLogVO.convertFrom(accessLogList);

        // 当前时间
        Date now = Calendar.getInstance().getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String dateTime = format.format(now);

        HashMap<String, Object> map = new HashMap<>();
        map.put("list", accessLogVOList);
        map.put("sheetName", "社区进出记录表-" + System.currentTimeMillis());
        map.put("fileName", "社区进出记录表_导出时间_" + dateTime);

        return Res.success(map);
    }
}
