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.ReportServiceImpl;
import com.cxyxiaomo.epp.common.pojo.Report;
import com.cxyxiaomo.epp.common.pojo.User;
import com.cxyxiaomo.epp.common.query.ReportQuery;
import com.cxyxiaomo.epp.common.response.Res;
import com.cxyxiaomo.epp.common.vo.ReportVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/access/report")
public class ReportController {

    @Autowired
    private UserServiceFeign userService;

    @Autowired
    private ReportServiceImpl reportService;

    /**
     * 体温上报
     *
     * @param id
     * @param address
     * @param timestamp
     * @param temperature
     * @return
     */
    @PostMapping("/submit")
    @ResponseBody
    public Res submit(@RequestParam("userId") Integer id,
                      @RequestParam("address") String address,
                      @RequestParam("timestamp") Long timestamp,
                      @RequestParam("temperature") Integer temperature) {
        User user = userService.getUserById(id);
        if (user == null) {
            return Res.error("用户不存在");
        }

        // 查询数据库，判断当天是否已经填报过

        Calendar instance = Calendar.getInstance();
        instance.setTimeInMillis(timestamp);

        Report report = new Report();
        report.setAddress(address);
        report.setName(user.getRealname());
        report.setTime(instance.getTime());
        report.setUserId(user.getId());
        report.setTemperature(temperature);

        reportService.addRecord(report);

        return Res.success();
    }

    /**
     * 获取用户填报信息
     *
     * @param userId
     * @return
     */
    @PostMapping("/getRecordList")
    @ResponseBody
    public Res getRecordList(@RequestParam("userId") Integer userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return Res.error("用户不存在");
        }
        List<Report> records = reportService.getRecordListByUserId(user.getId());
        return Res.success(records);
    }

    /**
     * 获取最近一次用户填报信息
     *
     * @param userId
     * @return
     */
    @PostMapping("/getLatestRecord")
    @ResponseBody
    public Res getLatestRecord(@RequestParam("userId") Integer userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return Res.error("用户不存在");
        }
        Report records = reportService.getLatestRecordByUserId(user.getId());
        return Res.success(records);
    }

    /**
     * 删除最近一次用户填报信息
     *
     * @param userId
     * @return
     */
    @PostMapping("/withdraw")
    @ResponseBody
    public Res withdrawLatestRecord(@RequestParam("userId") Integer userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return Res.error("用户不存在");
        }
        Report records = reportService.getLatestRecordByUserId(user.getId());
        if (records != null) {
            reportService.removeRecord(records.getId());
        }
        return Res.success(records);
    }


    /**
     * 获取体温数据列表
     *
     * @return
     */
    @GetMapping("/manage/getReportList")
    @ResponseBody
    public Res getReportList(PageQuery pageQuery, ReportQuery reportQuery) {
        // 查询分页数据
        PageHelper.startPage(pageQuery.getPageIndex(), pageQuery.getPageSize());
        List<Report> reportList = reportService.getReportList(reportQuery);
        PageInfo<Report> reportPageInfo = new PageInfo<>(reportList);
        List<Report> list = reportPageInfo.getList();
        List<ReportVO> voList = ReportVO.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("name", "name", "用户姓名", "",
                        FieldType.TEXT, SearchType.INPUT, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        null, null, null, null
                )
                .add("temperature", "displayTemperature", "状态", "",
                        FieldType.TEXT, SearchType.SELECT, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        null, null, null, null
                )
                .add("address", "address", "地址", "",
                        FieldType.LONG_TEXT, SearchType.INPUT, AddType.CAN_NOT_ADD, EditType.CAN_NOT_EDIT,
                        FieldBuilder.SEARCH_PLACEHOLDER_SAME_AS_FIELDNAME,
                        null, null, null, null
                )
                .build();

        // 指定需要翻译的字段
        HashMap<Object, Object> stateMap = new HashMap<>(2);
        stateMap.put("0", "正常");
        stateMap.put("1", "异常（≥37.3℃）");
        // build
        JSONArray fieldMapper = FieldMapperBuilder.create()
                .add("temperature", "displayTemperature", stateMap)
                .build();

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

        map.put("pawQuery", pageName);

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

    /**
     * 导出商品列表
     *
     * @return
     */
    @GetMapping("/manage/exportReportList")
    @ResponseBody
    public Res exportReportList(ReportQuery reportQuery) {
        List<Report> reportList = reportService.getReportList(reportQuery);
        List<ReportVO> reportVOList = ReportVO.convertFrom(reportList);

        // 当前时间
        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", reportVOList);
        map.put("sheetName", "体温数据表-" + System.currentTimeMillis());
        map.put("fileName", "体温数据表_导出时间_" + dateTime);

        return Res.success(map);
    }
}
