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.PageTable.utils.FieldRuleBuilder;
import com.cxyxiaomo.epp.PageTable.utils.FieldRuleListBuilder;
import com.cxyxiaomo.epp.access.service.GateService;
import com.cxyxiaomo.epp.common.pojo.Gate;
import com.cxyxiaomo.epp.common.response.Res;
import com.cxyxiaomo.epp.common.vo.GateVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/access/gate")
public class GateController {

    @Resource
    GateService gateService;

    /**
     * 获取大门列表（门禁端）
     *
     * @return
     */
    @GetMapping("/guard-client/getGateList")
    @ResponseBody
    public Res getAllGateList() {
        GateVO gateVO = new GateVO();
        List<Gate> gateList = gateService.getGateList(gateVO);
        List<GateVO> gateVOList = GateVO.convertFrom(gateList);
        return Res.success(gateVOList);
    }

    /**
     * 获取大门详情（小程序端）
     *
     * @return
     */
    @GetMapping("/miniprogram/detail")
    @ResponseBody
    public Res getGateDetail(String id) {
        Long gateId = Long.valueOf(id);
        Gate gate = gateService.getGateById(gateId);
        GateVO gateVO = GateVO.convertFrom(gate);

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

        return Res.success(gateVO);
    }

    /**
     * 获取大门列表
     *
     * @return
     */
    @GetMapping("/manage/getGateList")
    @ResponseBody
    public Res getGateList(PageQuery pageQuery, GateVO gateVO) {
        // 查询分页数据
        PageHelper.startPage(pageQuery.getPageIndex(), pageQuery.getPageSize());
        List<Gate> gateList = gateService.getGateList(gateVO);
        PageInfo<Gate> gatePageInfo = new PageInfo<>(gateList);
        List<Gate> list = gatePageInfo.getList();
        List<GateVO> voList = GateVO.convertFrom(list);

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

        // 当前管理页面
        String pageName = "大门管理";

        // 指定前端表格显示列
        JSONArray columns = FieldBuilder.create()
                .add("name", "name", "大门名称", "",
                        FieldType.TEXT, SearchType.INPUT, AddType.INPUT, EditType.INPUT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        "大门名称", FieldBuilder.EDIT_PLACEHOLDER_SAME_AS_ADD_PLACEHOLDER,
                        FieldRuleListBuilder.create()
                                .add(FieldRuleBuilder.create("大门名称").required())
                                .add(FieldRuleBuilder.create("大门名称").minMax(2, 12)),
                        "DPD @cword(2, 12)"
                )
                .add("open", "openStatus", "状态", true,
                        FieldType.TEXT, SearchType.SELECT, AddType.SELECT, EditType.SELECT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        "状态", FieldBuilder.EDIT_PLACEHOLDER_SAME_AS_ADD_PLACEHOLDER,
                        FieldRuleListBuilder.create()
                                .add(FieldRuleBuilder.create("状态").required()),
                        "DPD @pick(['true', 'false'])"
                )
                .build();

        // 指定需要翻译的字段
        HashMap<Object, Object> stateMap = new HashMap<>(2);
        stateMap.put(true, "允许通行");
        stateMap.put(false, "禁止通行");
        // build
        JSONArray fieldMapper = FieldMapperBuilder.create()
                .add("open", "openStatus", stateMap)
                .build();

        // 拼装返回结果
        JSONObject map = new JSONObject(6);
        map.put("total", gatePageInfo.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
     */
    @PostMapping("/manage/editGate")
    @ResponseBody
    public Res editGate(@ModelAttribute GateVO gateVO) throws Exception {
        Gate gate = GateVO.convertTo(gateVO);

        // 先查询大门是否存在
        Gate existGate = gateService.getGateById(gate.getId());

        if (gate.getId() == null || gate.getId() < 1) {
            // 新增大门
            if (existGate != null) {
                return Res.error("大门已存在，操作失败");
            }

            if (gate.getName() == null || "".equals(gate.getName())) {
                return Res.error("大门名称不能为空");
            }
            gate.setId(null);
            gateService.addGate(gate);
        } else {
            // 修改大门
            if (existGate == null) {
                return Res.error("大门不存在，操作失败");
            }

            gateService.updateGate(gate);
        }
        return Res.success(true);
    }

    /**
     * 删除大门
     *
     * @param id
     * @return
     */
    @PostMapping("/manage/deleteGate")
    @ResponseBody
    public Res deleteGate(Long id) {
        if (id == null || id <= 0) {
            return Res.error("大门不存在，删除失败");
        }
        // 先查询大门是否存在
        Gate existGate = gateService.getGateById(id);
        if (existGate == null) {
            return Res.error("大门不存在，删除失败");
        }
        boolean b = gateService.deleteGate(existGate.getId());
        return Res.success(b);
    }

    /**
     * 导出大门列表
     *
     * @return
     */
    @GetMapping("/manage/exportGateList")
    @ResponseBody
    public Res exportGateList(GateVO gateVO) {
        List<Gate> gateList = gateService.getGateList(gateVO);
        List<GateVO> gateVOList = GateVO.convertFrom(gateList);

        // 当前时间
        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", gateVOList);
        map.put("sheetName", "社区大门表-" + System.currentTimeMillis());
        map.put("fileName", "社区大门表_导出时间_" + dateTime);

        return Res.success(map);
    }
}
