package com.dcsoft.system.face.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.dcsoft.common.core.constant.HttpStatus;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.core.utils.sql.SqlUtil;
import com.dcsoft.common.core.web.page.PageDomain;
import com.dcsoft.common.core.web.page.TableDatasInfo;
import com.dcsoft.common.core.web.page.TableSupport;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.system.api.domain.FaceStudentBody;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.face.domain.FaceImage;
import com.dcsoft.system.face.domain.FaceRecord;
import com.dcsoft.system.face.domain.FaceRule;
import com.dcsoft.system.face.domain.FaceStudent;
import com.dcsoft.system.face.service.*;
import com.dcsoft.system.kq.domain.KqGatherMonth;
import com.dcsoft.system.kq.domain.KqGroup;
import com.dcsoft.system.kq.service.IKqGatherMonthService;
import com.dcsoft.system.kq.service.IKqGroupService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生信息Controller
 *
 * @author nichun
 * @date 2023-03-30
 */
@RestController
@RequestMapping("/student")
public class FaceStudentController extends BaseController
{
    @Autowired
    private IFaceStudentService faceStudentService;

    @Autowired
    private IFaceImageService faceImageService;

    @Autowired
    private IFaceRuleService faceRuleService;

    @Autowired
    private IFaceRecordService faceRecordService;

    @Autowired
    private IKqGatherMonthService kqGatherMonthService;

    @Autowired
    private IKqGroupService kqGroupService;

  /*  @Autowired
    private IAlgoService algoService;
*/

    /**
     * 查询学生信息列表
     */
    @RequiresPermissions("face:student:list")
    @GetMapping("/list")
    public TableDataInfo list(FaceStudent faceStudent)
    {
        startPage();
        List<FaceStudent> list = faceStudentService.selectFaceStudentList(faceStudent);
        return getDataTable(list);
    }

    @PostMapping("/studentList")
    public TableDatasInfo studentList(@RequestBody FaceStudentBody faceStudentBody)
    {
        FaceStudent faceStudent=new FaceStudent();
        faceStudent.setStartTime(faceStudentBody.getStartTime());
        faceStudent.setEndTime(faceStudentBody.getEndTime());
        faceStudent.setPhone(faceStudentBody.getPhone());
        faceStudent.setIdCard(faceStudentBody.getIdCard());
        PageDomain pageDomain = TableSupport.buildPageRequest();
        String pageNums = faceStudentBody.getPageNum();
        String pageSizes = faceStudentBody.getPageSize();
        Integer pageNum = Integer.parseInt(pageNums);
        Integer pageSize =Integer.parseInt(pageSizes);
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        List<FaceStudent> list = faceStudentService.selectFaceStudentList(faceStudent);
        if(StringUtils.isNotEmpty(faceStudentBody.getLabel())){

        }
        return  getDataTables(list,faceStudentBody);
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDatasInfo getDataTables(List<?> list,FaceStudentBody faceStudentBody)
    {
        TableDatasInfo rspData = new TableDatasInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setData(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        rspData.setPageSize(Integer.parseInt(faceStudentBody.getPageSize()));
        rspData.setPageNum(Integer.parseInt(faceStudentBody.getPageNum()));
        return rspData;
    }

    /**
     * 导出学生信息列表
     */
    @RequiresPermissions("face:student:export")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FaceStudent faceStudent)
    {
        List<FaceStudent> list = faceStudentService.selectFaceStudentList(faceStudent);
        ExcelUtil<FaceStudent> util = new ExcelUtil<FaceStudent>(FaceStudent.class);
        util.exportExcel(response, list, "学生信息数据");
    }

    /**
     * 获取学生信息详细信息
     */
    @RequiresPermissions("face:student:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(faceStudentService.selectFaceStudentById(id));
    }

    /**
     * 新增学生信息
     */
    @RequiresPermissions("face:student:add")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FaceStudent faceStudent)
    {
        if(StringUtils.isNotEmpty(faceStudent.getImgs())){
            FaceImage faceImage=new FaceImage();
            faceImage.setImgs(faceStudent.getImgs());
            faceImage.setStuId(faceStudent.getStuId());
            faceImage.setLabel("0");//工作照
            faceImageService.insertFaceImage(faceImage);
        }
        return toAjax(faceStudentService.insertFaceStudent(faceStudent));
    }

    /**
     * 修改学生信息
     */
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FaceStudent faceStudent)
    {
        //查看图片是否更换，更换就更新，没有就插入证件照
        FaceStudent faceStudents = faceStudentService.selectFaceStudentById(faceStudent.getId());
        if (StringUtils.isNotEmpty(faceStudent.getImgs())){
            if(StringUtils.isNotEmpty(faceStudents.getImgs())){
                if(!faceStudents.getImgs().equals(faceStudent.getImgs())){//更新
                    //判断特征值，二次上传特征值相近进行更换，如果不相近就不进行更换，并给出提示，两次上传人员非同一人员
                    FaceImage faceImage =faceImageService.selectFaceImageByStuId(faceStudents.getStuId());
                    faceImage.setImgs(faceStudent.getImgs());
                    faceImageService.updateFaceImage(faceImage);
                }
            }else{
                FaceImage faceImage=new FaceImage();
                faceImage.setImgs(faceStudent.getImgs());
                faceImage.setStuId(faceStudent.getStuId());
                faceImage.setLabel("0");//工作照
                faceImageService.insertFaceImage(faceImage);
            }
        }
        return toAjax(faceStudentService.updateFaceStudent(faceStudent));
    }

    /**
     * 删除学生信息
     */
    @RequiresPermissions("face:student:remove")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(faceStudentService.deleteFaceStudentByIds(ids));
    }

    /**
     * @Description: 导入excel和图片zip包
     * @Param:
     * @return:
     * @Author: nichun
     * @Date: 2023-03-31 13:45:02
     **/
    @ApiOperation(value = "导入excel和图片zip包", notes = "导入excel和图片zip包")
    @PostMapping("/import")
    public AjaxResult importExcelPic(MultipartFile file, boolean updateSupport) throws Exception {
        StringBuffer sb = faceStudentService.importPicture(file,updateSupport);
        if (sb!= null&&sb.length()>0) {
            return AjaxResult.error(sb.toString());
        }else{
            return AjaxResult.success();
        }
    }

    @Log(title = "人员信息", businessType = BusinessType.IMPORT)
    @RequiresPermissions("face:student:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<FaceStudent> util = new ExcelUtil<FaceStudent>(FaceStudent.class);
        List<FaceStudent> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = faceStudentService.importStudent(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<FaceStudent> util = new ExcelUtil<FaceStudent>(FaceStudent.class);
        util.importTemplateExcel(response, "人员信息");
    }



    @PostMapping("/getStudent")
    public FaceStudent getStudent(@RequestBody FaceStudent faceStudent)
    {
        FaceStudent faceStudents = faceStudentService.getStudent(faceStudent);
        return  faceStudents;
    }

    @GetMapping("/option")
    public List<FaceStudent>  option(FaceStudent faceStudent)
    {
        List<FaceStudent> list = faceStudentService.selectFaceStudentList(faceStudent);
        return list;
    }


    /**
     * 获取头部信息
     */
    @GetMapping("/top")
    public AjaxResult topApi() {
        return faceStudentService.top();
    }

    /**
     * 获取头部信息
     */
    @GetMapping("/topChart")
    public AjaxResult topChart() {
        return faceStudentService.topChart();
    }

    /**
     * 获取采集信息
     */
    @GetMapping("/getGather")
    public AjaxResult getGather() {
        return faceStudentService.getGather();
    }

    /**
     * 查询rule列表
     */
    @GetMapping("/listRule")
    public List<FaceRule> list(FaceRule faceRule)
    {
        List<FaceRule> list = faceRuleService.selectFaceRuleList(faceRule);
        return list;
    }

    /**
     * 新增评分核验记录
     */
    @Log(title = "评分核验记录", businessType = BusinessType.INSERT)
    @PostMapping("/faceRecord")
    public AjaxResult addRecord(@RequestBody FaceRecord faceRecord)
    {
        return toAjax(faceRecordService.insertFaceRecord(faceRecord));
    }

    /**
     * 删除学生信息
     */
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @GetMapping("/examineStudent")
    public AjaxResult examineStudent(@RequestParam("ids") Long[] ids,@RequestParam("erification") String erification)
    {
        return toAjax(faceStudentService.examineStudentByIds(ids,erification));
    }

    @PostMapping("/gatherMonth")
    public void gatherMonth()
    {
        List<KqGroup> groupList =kqGroupService.selectKqGroupList(new KqGroup());
        for(KqGroup g:groupList){
            KqGatherMonth kqGatherMonth=new KqGatherMonth();
            kqGatherMonth.setGroupId(g.getGroupId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//设置日期格式
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            try {
                //上月26日至本月25日
                Calendar cal_1=Calendar.getInstance();//获取当前日期
                cal_1.add(Calendar.MONTH, -1);
                cal_1.set(Calendar.DAY_OF_MONTH,26);
                kqGatherMonth.setStartTime(sdf1.parse(sdf.format(cal_1.getTime())+"-26"));
                kqGatherMonth.setEndTime(sdf1.parse(sdf.format(new Date())+"-25"));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            kqGatherMonthService.createKqGatherMonth(kqGatherMonth);
        }
    }

    @PostMapping("/gather")
    public void gather()
    {
         kqGatherMonthService.createKqGather();
    }


}
