package com.zd.laboratory.controller;

import com.zd.common.core.domain.R;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.FileConfigUtils;
import com.zd.common.core.utils.UrlFormatUtils;
import com.zd.common.core.utils.poi.ExcelUtil;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.web.page.TableDataInfo;
import com.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.common.security.service.TokenService;
import com.zd.laboratory.domain.LabBlacklist;
import com.zd.laboratory.domain.LabNegativelistHistory;
import com.zd.laboratory.domain.LabViolation;
import com.zd.laboratory.domain.vo.*;
import com.zd.laboratory.service.*;
import com.zd.system.api.exam.RemoteExamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 违规记录Controller
 *
 * @author zd
 * @date 2021-09-01
 */
@RestController
@RequestMapping("/violation")
@Api(tags = "【违规记录*】")
public class LabViolationController extends BaseController {
    @Autowired
    private ILabViolationService labViolationService;

    @Autowired
    private ILabBlacklistService labBlacklistService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ILabSemesterService labSemesterService;

    @Autowired
    private ILabNegativeListRecordsService labNegativeListRecordsService;

    @Autowired
    private ILabNegativelistHistoryService labNegativelistHistoryService;

    @Autowired
    private ILabBlacklistService blacklistService;

    @Autowired
    private RemoteExamService remoteExamService;

    @Autowired
    private FileConfigUtils fileConfigUtils;



    /**
     * 违规记录列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_VIOLATION + PerFun.LIST)
    @GetMapping("/list")
    public TableDataInfo list(LabViolationVO labViolation) {
        startPage();

//        labViolation.setCreact_id(tokenService.getLoginUser().getUserid());
        List<LabViolationVO> list = labViolationService.pageList(labViolation);
        return getDataTable(list);
    }




    /**
     * 查询违规历史记录列表
     */
    @GetMapping("/historylist")
    @ApiOperation(value = "查询负面清单历史记录列表")
    public TableDataInfo<LabNegativelistHistory> list(LabNegativelistVO labNegativelistHistory)
    {
        startPage();
        labNegativelistHistory.setDataType(0);
        List<LabNegativelistHistory> list = labNegativelistHistoryService.selectLabNegativelistHistoryList(labNegativelistHistory);
        return getDataTable(list);
    }

    /**
     * 查询违规记录详细列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_VIOLATION + PerFun.LIST)
    @GetMapping("/getDetailList")
    public TableDataInfo getDetailList(LabViolationVO labViolation) {
        startPage();
        List<LabViolationVO> list = labViolationService.getDetailList(labViolation);
        return getDataTable(list);
    }

    /**
     * 查询违规记录详细-通过ID
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_VIOLATION + PerFun.LIST)
    @ApiOperation("查询违规记录详细-通过ID")
    @GetMapping("/{id}/detail")
    public LabViolationVO getDetail(@PathVariable Long id) {
        LabViolationVO labViolation = new LabViolationVO();
        labViolation.setId(id);
        List<LabViolationVO> list = labViolationService.getDetailList(labViolation);
        return Optional.ofNullable(list.get(0)).orElseGet(null);
    }

    /**
     * 导出违规记录列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_VIOLATION + PerFun.EXPORT)
    @Log(title = "违规记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LabViolationVO labViolation) throws IOException {
        List<LabViolationVO> list = labViolationService.selectLabViolationList(labViolation);
        ExcelUtil<LabViolationVO> util = new ExcelUtil<LabViolationVO>(LabViolationVO.class);
        util.exportExcel(response, list, "违规记录数据");
    }

    /**
     * 获取违规记录详细信息
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_VIOLATION + PerFun.QUERY)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(labViolationService.selectLabViolationById(id));
    }

   /* *//**
     * 新增违规记录
     *//*
    @PreAuthorize(hasPermi = "laboratory:violation:add")
    @Log(title = "old违规记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LabViolationVO labViolationVO) {
        labViolationVO.setUserId(tokenService.getLoginUser().getUserid());
        labViolationVO.setUpdateBy(tokenService.getLoginUser().getSysUser().getNickName());
        labViolationVO.setDeptId(tokenService.getLoginUser().getSysUser().getDeptId());
        labViolationVO.setDeptName(tokenService.getLoginUser().getSysUser().getDeptName());
        return toAjax(labViolationService.insertLabViolation(labViolationVO));
    }*/

    /**
     * 修改违规记录
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_VIOLATION + PerFun.EDIT)
    @Log(title = "违规记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LabViolation labViolation) {
        return toAjax(labViolationService.updateLabViolation(labViolation));
    }

    /**
     * 删除违规记录
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_VIOLATION + PerFun.REMOVE)
    @Log(title = "违规记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(labViolationService.deleteLabViolationByIds(ids));
    }


    /**
     * 查询个人违规记录列表
     */
    @RequestMapping("/myListViolation")
    public TableDataInfo myListViolation(LabViolationVO labViolation) {
        startPage();
        labViolation.setJoinUserId(tokenService.getLoginUser().getUserid());
        List<LabViolationVO> list = labViolationService.mylist(labViolation);
        return getDataTable(list);
    }


    /**
     * 小程序查询违规记录列表
     */
    @RequestMapping("/mylist")
    public TableDataInfo mylist(@RequestBody LabViolationVO labViolation) {
        startPage(labViolation.getAppPageNum(),labViolation.getAppPageSize());
        List<LabViolationVO> list = labViolationService.mylist(labViolation);
        return getDataTable(list);
    }

    /**
     * 加入黑名单
     */
   /* @PreAuthorize(hasPermi = "laboratory:violation:edit")
    @Log(title = "黑名单记录", businessType = BusinessType.UPDATE)
    @PostMapping("/joinBlackList/{ids}")
    public AjaxResult joinBlackList(@RequestParam String reason,
                                    @RequestParam String creditScore,
                                    @PathVariable("ids") Long... ids) {
        LabViolation violation = labViolationService.selectLabViolationById(ids[0]);
        LabBlacklist blackList = new LabBlacklist();
        blackList.setJoinUserId(violation.getJoinUserId());
        blackList.setBlacklistStatus(1);
        blackList.setDeptId(violation.getDeptId());
        blackList.setDeptName(violation.getDeptName());
        blackList.setUserId(tokenService.getLoginUser().getUserid());
        blackList.setCreateBy(tokenService.getLoginUser().getSysUser().getNickName());
        blackList.setReason(reason);
        blackList.setCreditScore(creditScore);
        int i = labBlacklistService.insertLabBlacklist(blackList);
        //labViolationService.updateStatus(blackList.getUserId());
        return toAjax(i);
    }*/


    /**
     * 大屏 人员违规统计
     */
    @PostMapping("/bigData/statistics")
    public AjaxResult statistics(@RequestBody LabViolation labViolation) {
        List<Map<String, Object>> data = labViolationService.statistics(labViolation);
        return AjaxResult.success(data);
    }

    /**
     * 大屏 人员违规统计
     */
    @GetMapping("/bigData/newStatistics")
    public AjaxResult newStatistics(LabViolation labViolation) {
        LinkedHashMap <String,Object> data = labViolationService.newStatistics(labViolation);
        return AjaxResult.success(data);
    }


    /**
     * 大屏详情 人员违规柱状图统计
     */
    @GetMapping("/bigData/detail/columnar")
    public AjaxResult columnar(LabViolationVO labViolationVO) {
        List<Object> data = labViolationService.columnar(labViolationVO);
        return AjaxResult.success(data);
    }


    /**
     * 大屏详情 实验室人员违规统计列表（校级）
     */
    @GetMapping("/bigData/detail/subListBySchool")
    public AjaxResult subListBySchool(LabViolationVO labViolationVO) {
        List<LabViolationColumnarVO> data = labViolationService.subListBySchool(labViolationVO);
        return AjaxResult.success(data);
    }

    /**
     * 大屏详情 实验室人员违规统计列表（院级）
     */
    @GetMapping("/bigData/detail/subList")
    public TableDataInfo subList(LabViolationVO labViolationVO) {
        startPage();
        List<LabViolationSubListVO> data = labViolationService.subList(labViolationVO);
        return getDataTable(data);
    }

    /**
     * 黑名单加入
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_BLACKLIST + PerFun.ADD)
    @PostMapping("/blackAdd")
    public R blackAdd(@RequestBody LabBlacklistVO labBlacklistVO){

        return labViolationService.blackAdd(labBlacklistVO);
    }



    /**
     * 新增违规记录
     * @param vo
     * @return
     */
    @PostMapping("/addViolationHistory")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_VIOLATION + PerFun.ADD)
    public R addViolationHistory(@RequestBody ViolationNewVo vo){
        vo.setCreact_id(tokenService.getLoginUser().getUserid());
        return labViolationService.addViolationHistory(vo);
    }

   /* @Autowired
    private ILabBlacklistService labBlacklistService;*/

    /**
     * 移除黑名单(一体机)
     * @param labBlacklist
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_BLACKLIST + PerFun.REMOVE)
    @PostMapping("/delBlacklist")
    public R delBlacklist(@RequestBody LabBlacklist labBlacklist){


       return labViolationService.delBlacklist(labBlacklist);
    }


    /**
     * 移除黑名单(pc)
     * @param labBlacklist
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_BLACKLIST + PerFun.REMOVE)
    @PostMapping("/delBlacklistByPc")
    public R delBlacklistByPc(@RequestBody LabBlacklist labBlacklist){


        return labViolationService.delBlacklistByPc(labBlacklist);
    }

    /**
     * 移除负面清单(一体机)
     * @param vo
     * @return
     */
    @PostMapping("/delNegivelist")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_NEGATIVELISTRECORDS + PerFun.REMOVE)
    public R delNegivelist(@RequestBody LabNegativeListRecordsVO vo){
     return labViolationService.updateNegiveStatus(vo);

    }


    /**
     * 移除负面清单(pc)
     * @param vo
     * @return
     */
    @PostMapping("/delNegivelistByPc")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_NEGATIVELISTRECORDS + PerFun.REMOVE)
    public R delNegivelistByPc(@RequestBody LabNegativeListRecordsVO vo){
        return labViolationService.updateNegiveStatusByPc(vo);

    }

    @GetMapping("/getIntegralMatchingRules")
    public R getIntegralMatchingRules(@RequestParam String creditScore){
        Map<String,Object> markconfigMap = new HashMap<>();
        R<Object> data = remoteExamService.getPointsConfig(markconfigMap);
        int flag=0;
        if (data!=null) {
            String code = data.getCode() + "";
            if (code.equals("200")) {
                Map<String, Object> pointsConfig = (Map<String, Object>) data.getData();
                //获取积分详情列表
                List<Map<String, Object>> pointsConfigDetail = (List<Map<String, Object>>) pointsConfig.get("configDetailList");
                ElPassConfigdetailVO result = blacklistService.getIntegralMatchingRules(pointsConfigDetail,Integer.valueOf(creditScore));
               return R.ok(result);
            }
        }
        return null;
    }


    /**
     * 查询某用户是否在负面清单表中
     * @param userId
     * @return
     */
    @PostMapping("/userexist/{userId}")
    public R userexist(@PathVariable Long userId){

       return labViolationService.userexist(userId);

    }


    @GetMapping("/userInfo")
    @ApiOperation(value = "查询个人违规信息")
    public R getPersonInfo(){
        R r=labViolationService.getPersonInfo();
        if(r.getCode()!=200){
            return r;
        }
        LabViolationInfoVO labViolat= (LabViolationInfoVO) r.getData();
        String avatar=labViolat.getAvatar();
        String url=fileConfigUtils.getLocalUrl()+ File.separator+avatar;
        url= UrlFormatUtils.getHttpsORHttpUrl(url);
        labViolat.setAvatar(url);
        r.setData(labViolat);
        return r;
    }

    @GetMapping("/exist")
    @ApiOperation(value = "是否有违规信息")
    public R exist(){

        return labViolationService.exist();
    }

    /**
     * 个人中心---按用户查询违规历史列表
     * @param  overStatus：default -1
     * @return
     */
    @GetMapping("/historyList")
    @ApiOperation(value = "查询违规记录列表")
    public TableDataInfo violationhistoryList(@RequestParam(defaultValue = "-1") String overStatus,
                                              @RequestParam(defaultValue = "") String statTime,
                                              @RequestParam(defaultValue = "") String endTime) {
        startPage();
        List<LabViolationPageListVO> list = labNegativelistHistoryService.historypageList(overStatus,statTime,endTime);
        return getDataTable(list);
    }





}
