package com.yonge.cooleshow.admin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.VipSubmitReq;
import com.yonge.cooleshow.biz.dal.dto.search.StudentSearch;
import com.yonge.cooleshow.biz.dal.dto.search.VipRecordSearch;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.MemberPriceSettingsService;
import com.yonge.cooleshow.biz.dal.service.StudentService;
import com.yonge.cooleshow.biz.dal.service.VipCardRecordService;
import com.yonge.cooleshow.biz.dal.vo.StudentVo;
import com.yonge.cooleshow.biz.dal.vo.VipRecordVo;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.UserLockFlag;
import com.yonge.cooleshow.common.enums.UserStatusEnum;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.toolset.utils.date.DateUtil;
import com.yonge.toolset.utils.excel.POIUtil;

@RestController
@RequestMapping("/student")
@Api(value = "学生表", tags = "学生表")
public class StudentController extends BaseController {
    @Autowired
    private StudentService studentService;


    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private MemberPriceSettingsService memberPriceSettingsService;

    @Autowired
    private VipCardRecordService vipCardRecordService;


    @GetMapping("/detail/{id}")
    @ApiOperation(value = "详情", notes = "传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "path", dataType = "long", required = true),
    })
    @PreAuthorize("@pcs.hasPermissions('student/detail')")
    public HttpResponseResult<StudentVo> detail(@PathVariable("id") Long id){
		StudentVo detail = studentService.detail(id);
		return succeed(detail);
	}

    @PostMapping("/page")
    @ApiOperation(value = "查询分页", notes = "传入StudentSearch")
    @PreAuthorize("@pcs.hasPermissions('student/page')")
    public HttpResponseResult<PageInfo<StudentVo>> page(@RequestBody StudentSearch query) {
    	
    	if(StringUtils.isNotBlank(query.getUserStatus())){
    		switch (query.getUserStatus()) {
			case "LOCKED":
				query.setDelFlag(YesOrNoEnum.NO);
				query.setLockFlag(UserLockFlag.LOCKED);
				break;
			case "CLOSED":
				query.setDelFlag(YesOrNoEnum.YES);
				break;

			default:
				query.setDelFlag(YesOrNoEnum.NO);
				query.setLockFlag(UserLockFlag.NORMAL);
				break;
			}
    	}
    	
		IPage<StudentVo> pages = studentService.selectPage(PageUtil.getPage(query), query);
		List<StudentVo> rows = pages.getRecords();
		
		for(StudentVo vo : rows){
			if(vo.getDelFlag() == YesOrNoEnum.YES){
				vo.setUserStatus(UserStatusEnum.CLOSED);
			}else{
				if(vo.getLockFlag() == UserLockFlag.LOCKED){
					vo.setUserStatus(UserStatusEnum.LOCKED);
				}else{
					vo.setUserStatus(UserStatusEnum.NORMAL);
				}
			}
		}
        return succeed(PageUtil.pageInfo(pages));
	}

    @ApiOperation(value = "学生列表导出")
    @PostMapping("export")
    @PreAuthorize("@pcs.hasPermissions('student/export')")
    public void export(HttpServletResponse response, @RequestBody StudentSearch queryInfo) throws IOException {
        queryInfo.setPage(1);
        queryInfo.setRows(49999);
    	
    	if(StringUtils.isNotBlank(queryInfo.getUserStatus())){
    		switch (queryInfo.getUserStatus()) {
			case "LOCKED":
				queryInfo.setDelFlag(YesOrNoEnum.NO);
				queryInfo.setLockFlag(UserLockFlag.LOCKED);
				break;
			case "CLOSED":
				queryInfo.setDelFlag(YesOrNoEnum.YES);
				break;

			default:
				queryInfo.setDelFlag(YesOrNoEnum.NO);
				queryInfo.setLockFlag(UserLockFlag.NORMAL);
				break;
			}
    	}
        List<StudentVo> rows = studentService.selectPage(PageUtil.getPage(queryInfo), queryInfo).getRecords();
        if (rows.size() < 1) {
            throw new BizException("没有可导出数据");
        }
		
		for(StudentVo vo : rows){
			if(vo.getDelFlag() == YesOrNoEnum.YES){
				vo.setUserStatus(UserStatusEnum.CLOSED);
			}else{
				if(vo.getLockFlag() == UserLockFlag.LOCKED){
					vo.setUserStatus(UserStatusEnum.LOCKED);
				}else{
					vo.setUserStatus(UserStatusEnum.NORMAL);
				}
			}
		}
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"学生编号", "学生姓名", "真实姓名", "性别", "出生日期",
                    "年龄", "专业", "手机号码", "是否是会员", "注册时间","用户状态"}, new String[]{
                    "userId","username" , "realName", "gender.msg", "birthdate", "age", "subjectName", "phone",
                    "isVip.msg", "createTime", "userStatus.msg"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attac:wq" +
                    "hment;filename=学生列表-" + DateUtil.getDate(new Date()) + ".xls");

            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @PostMapping("/addVip")
    @ApiOperation(value = "添加会员")
    @PreAuthorize("@pcs.hasPermissions('student/addVip')")
    public HttpResponseResult<Boolean> addVip(@Valid @RequestBody VipSubmitReq vipSubmitReq) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        return succeed(memberPriceSettingsService.addVip(vipSubmitReq, ClientEnum.STUDENT, sysUser));
    }


    @PostMapping("/vipRecord")
    @ApiOperation(value = "会员记录")
    @PreAuthorize("@pcs.hasPermissions('student/vipRecord')")
    public HttpResponseResult<PageInfo<VipRecordVo>> vipRecord(@Valid @RequestBody VipRecordSearch recordSearch) {

        recordSearch.setClient(ClientEnum.STUDENT);
        return succeed(vipCardRecordService.vipRecord(recordSearch));
    }
}