package com.yeejoin.amos.boot.module.jcs.biz.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.FormValue;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonFormDto;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.SignDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.SinStaticDto;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.SignServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 打卡记录
 *
 * @author system_generator
 * @date 2022-08-15
 */
@RestController
@Api(tags = "打卡记录Api")
@RequestMapping(value = "/sign")
public class SignController extends BaseController {

    @Autowired
    SignServiceImpl signServiceImpl;

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    @Autowired
    RedisUtils redisUtils;

    /**
     * 新增打卡记录
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增打卡记录", notes = "新增打卡记录")
    public ResponseModel<SignDto> save(@RequestBody SignDto model) {
        model = signServiceImpl.createWithModel(model);
        return ResponseHelper.buildResponse(model);
    }

    /**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新打卡记录", notes = "根据sequenceNbr更新打卡记录")
    public ResponseModel<SignDto> updateBySequenceNbrSign(@RequestBody SignDto model, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        model.setSequenceNbr(sequenceNbr);
        return ResponseHelper.buildResponse(signServiceImpl.updateWithModel(model));
    }

    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除打卡记录", notes = "根据sequenceNbr删除打卡记录")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(signServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
     *
     * @param sequenceNbr  主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个打卡记录", notes = "根据sequenceNbr查询单个打卡记录")
    public ResponseModel<SignDto> selectOne(@PathVariable Long sequenceNbr) {
        SignDto signDto = signServiceImpl.queryBySeq(sequenceNbr);
        QueryWrapper<OrgUsr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sequence_nbr", signDto.getSignUserId());
        queryWrapper.eq("is_delete", 0);
        OrgUsr orgUsr = iOrgUsrService.getOne(queryWrapper);
        try {
            OrgPersonFormDto orgPersonFormDto = iOrgUsrService.selectPersonById(orgUsr.getSequenceNbr());
            List<FormValue> personImg = orgPersonFormDto.getDynamicFormAlert().stream().filter(e -> e.getKey().equals("personImg")).collect(Collectors.toList());
            signDto.setPersonPhotos(personImg.get(0).getValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseHelper.buildResponse(signDto);

    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/page")
    @ApiOperation(httpMethod = "POST", value = "打卡记录分页查询", notes = "打卡记录分页查询")
    public ResponseModel<IPage<SignDto>> queryForPage(@RequestBody SignDto dto) {
        Page<SignDto> page = new Page<SignDto>();
        page.setCurrent(dto.getCurrent());
        page.setSize(dto.getSize());
        IPage<SignDto> page1 = signServiceImpl.queryForSignPageByMapper(page, dto);
        if (0 < page1.getRecords().size()) {
            for (SignDto d : page1.getRecords()) {
                QueryWrapper<OrgUsr> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("sequence_nbr", d.getSignUserId());
                queryWrapper.eq("is_delete", 0);
                OrgUsr orgUsr = iOrgUsrService.getOne(queryWrapper);
                try {
                    OrgPersonFormDto orgPersonFormDto = iOrgUsrService.selectPersonById(orgUsr.getSequenceNbr());
                    List<FormValue> personImg = orgPersonFormDto.getDynamicFormAlert().stream().filter(e -> e.getKey().equals("personImg")).collect(Collectors.toList());
                    d.setPersonPhotos(personImg.get(0).getValue());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseHelper.buildResponse(page1);
    }

    /**
     * 人员信息卡统计打卡
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "人员信息卡统计打卡", notes = "人员信息卡统计打卡")
    @GetMapping(value = "/statistic")
    public ResponseModel<Map<String, Object>> getSignStatistic(@RequestParam(value = "userId", required = false) String userId,
                                                               @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode) {
        return ResponseHelper.buildResponse(signServiceImpl.getSignStatistic(userId, bizOrgCode));
    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/static/page")
    @ApiOperation(httpMethod = "POST", value = "打卡记录分页查询", notes = "打卡记录分页查询")
    public ResponseModel<IPage<SinStaticDto>> queryStaticForPage(@RequestBody SinStaticDto dto) {
        Page<SinStaticDto> page = new Page<>();
        page.setCurrent(dto.getCurrent());
        page.setSize(dto.getSize());
        return ResponseHelper.buildResponse(signServiceImpl.queryForSignStaticPageByMapper(page, dto));
    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/center/static/page")
    @ApiOperation(httpMethod = "POST", value = "中心级卡片驻站消防员出勤柱状图", notes = "中心级卡片驻站消防员出勤柱状图")
    public ResponseModel<Map<String, Object>> queryPeopleInfoForPage(@RequestBody SinStaticDto dto) {
        String bizOrgCode = dto.getBizOrgCode();
        if (StringUtils.isBlank(bizOrgCode)) {
            ReginParams reginParam = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
            if (null != reginParam) {
                bizOrgCode = reginParam.getPersonIdentity().getCompanyBizOrgCode();
            }
        }
        dto.setBizOrgCode(bizOrgCode);
        List<Map<String, Object>> res = signServiceImpl.queryPeopleInfo(dto);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("bizOrgCode", bizOrgCode);
        map1.put("xData", res.stream().map(x -> x.get("date")).collect(Collectors.toList()));
        map1.put("yData", res.stream().map(x -> x.get("signNum")).collect(Collectors.toList()));
        return ResponseHelper.buildResponse(map1);
    }

    /**
     * 列表全部数据查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "打卡记录列表全部数据查询", notes = "打卡记录列表全部数据查询")
    @GetMapping(value = "/list")
    public ResponseModel<List<SignDto>> selectForList() {
        return ResponseHelper.buildResponse(signServiceImpl.queryForSignList());
    }


    /**
     * 当前用户当天是否已打卡
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "打卡记录列表全部数据查询", notes = "打卡记录列表全部数据查询")
    @GetMapping(value = "/hasSign")
    public ResponseModel<Boolean> hasSign(@RequestParam(value = "type", required = false) String type,
                                          @RequestParam(value = "userId", required = false) String userId) {
        String date = DateUtils.stampToDate(new Date().getTime(), DateUtils.DATE_PATTERN);
        return ResponseHelper.buildResponse(signServiceImpl.hasSign(type, date, userId));
    }

    /**
     * 保存打卡记录
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "保存打卡记录", notes = "保存打卡记录")
    @PostMapping(value = "/saveSign")
    public ResponseModel<Boolean> hasSign(@RequestBody SignDto dto) {
        return ResponseHelper.buildResponse(signServiceImpl.saveSign(dto));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "今日出勤合格换流站（座）", notes = "今日出勤合格换流站（座）")
    @GetMapping(value = "/center/sign-stats")
    public ResponseModel<Map<String, Object>> getCenterSignStats(
            @RequestParam(value = "bizOrgCode",required = false) String bizOrgCode,
            @RequestParam(value = "date", required = false) String date,
            @RequestParam(value = "targetPassNum", defaultValue = "8") Integer targetPassNum,   // 出勤合格人数
            @RequestParam(value = "stationType", required = false) String stationType
    ) {
        if (StringUtils.isBlank(date)) {
            date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        return ResponseHelper.buildResponse(signServiceImpl.getCenterSignStats(bizOrgCode, date, targetPassNum, stationType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "消防员出勤状态统计（近一周）", notes = "消防员出勤状态统计（近一周）")
    @GetMapping(value = "/station/sign-stats")
    public ResponseModel<Map<String, Object>> getStationSignStats(@RequestParam("bizOrgCode") String bizOrgCode) {
        return ResponseHelper.buildResponse(signServiceImpl.getStationSignStats(bizOrgCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "换流站出勤情况", notes = "换流站出勤情况")
    @GetMapping(value = "/station-attendance-stats/page")
    public ResponseModel<IPage<Map<String, Object>>> getStationAttendanceStatsPage(
            @RequestParam("pageNumber") Integer pageNumber,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode,
            @RequestParam(value = "stationType", required = false) String stationType,
            @RequestParam(value = "date", required = false) String date,
            @RequestParam(value = "attendanceStatus", required = false) String attendanceStatus,
            @RequestParam(value = "targetPassNum", defaultValue = "8") Integer targetPassNum,   // 出勤合格人数
            @RequestParam(value = "sorter", required = false) String sorter
    ) {
        if (StringUtils.isBlank(date)) {
            date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        Page page = new Page(pageNumber, pageSize);
        return ResponseHelper.buildResponse(signServiceImpl.getStationAttendanceStatsPage(page, date, stationType, bizOrgCode, attendanceStatus, targetPassNum, sorter));
    }
}
