package com.yizhi.application.documents;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.caseLibrary.util.StuCommonUtils;
import com.yizhi.application.caseLibrary.util.StuUpConvert;
import com.yizhi.application.documents.vo.CanDownload;
import com.yizhi.documents.application.feign.DocumentClient;
import com.yizhi.documents.application.vo.documents.DocumentVo;
import com.yizhi.documents.application.vo.documents.ParamsVo;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hutao
 * @since 2019-06-11
 */
@Api(tags = "资料表学员端接口", description = "资料表学员端接口")
@RestController
@RequestMapping("/student/document")
public class StuDocumentComtroller {

    private static final Logger LOGGER = LoggerFactory.getLogger(StuDocumentComtroller.class);

    @Autowired
    private DocumentClient documentClient;

    @Autowired
    private StuCommonUtils stuCommonUtils;
    
    @Resource
    private StuUpConvert stuUpConvert;


    @Value("${ACTIVE}")
    public String active;
    
    @GetMapping("/download")
    @ApiOperation(value = "下载", notes = "下载", response = String.class)
    public Response<String> download(@ApiParam("资料id必传") @RequestParam("id") Long id,
                                     @ApiParam("终端类型：1、PC；2、weixin；3、app；4、manage") @RequestParam("termialType") Integer termialType) {

        if (termialType < 1 && termialType > 4) {
            return Response.fail(Constants.DOCUMENT_TERMINAL_TYPE_ERR.getCode().toString(), Constants.DOCUMENT_TERMINAL_TYPE_ERR.getName());
        }
        ParamsVo paramsVo = documentClient.download(id, termialType);
        if (paramsVo.getSuccess()) {
            return Response.ok(paramsVo.getSuccessData());
        } else {
            return Response.fail(paramsVo.getErrorMsg());
        }
    }

    /**
     * @param relationId   与模块类型有关  关联id
     * @param relationType 关联模块类型：1、课程；2、培训项目
     * @param pageSize
     * @param pageNo
     * @return
     */
    @GetMapping("/query/ByRelationId")
    @ApiOperation(value = "通过关联关系查询", notes = "通过关联关系查询", response = DocumentVo.class)
    public Response<Page<DocumentVo>> queryByIds(@ApiParam("关联模块id必传") @RequestParam("relationId") Long relationId,
                                                 @ApiParam("关联模块类型必传") @RequestParam("relationType") Integer relationType,
                                                 @ApiParam("pageNo") @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                                 @ApiParam("pageSize") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        return Response.ok(documentClient.queryByIds(relationId, relationType, pageNo, pageSize));
    }

    @PostMapping("/canStudy")
    @ApiOperation(value = "判断能否下载", notes = "判断能否下载", response = DocumentVo.class)
    public Response canStudy(@RequestBody CanDownload vo) {

        Integer termialType = vo.getTermialType();
        Integer stutas = vo.getStutas();
        Long currentTime = System.currentTimeMillis();
        vo.setCurrentTime(currentTime);

        //PC端判断
        if (termialType == 1) {
            if (stutas == null) {
                return Response.fail(Constants.DOCUMENT_PARAMS_ERR.getCode().toString(), Constants.DOCUMENT_PARAMS_ERR.getName());
            }
            return pcReturnStutas(stutas);
        } else {

            //判断参数是否齐全
            if (paramsIsNotNull(vo)) {
                //判断是否需要报名
                return whetherNeedEnroll(vo);
            } else
                return Response.fail(Constants.DOCUMENT_PARAMS_ERR.getCode().toString(), Constants.DOCUMENT_PARAMS_ERR.getName());

        }
    }

    @GetMapping("/getDetailById")
    @ApiOperation(value = "查看资料详情", notes = "查看资料详情", response = DocumentVo.class)
    public Response<DocumentVo> getDetailById(@ApiParam("关联模块id必传") @RequestParam("id") Long id,@ApiParam("终端类型：0：移动端|1：PC端") @RequestParam("type") Integer type){
    	DocumentVo document = documentClient.queryById(id);
		return Response.ok(document);
    	
    }
    private Response pcReturnStutas(Integer status) {
        //培训项目所有情况的列举1-培训时间未开始，请等待！  2-开始学习 3-报名尚未开始，无法进行项目学习！ 4-报名已结束，无法进行项目学习！
        // 5-您尚未报名，报名成功后可进行学习。 6-名额已满,无法进行项目学习！ 7-报名审核中,无法进行项目学习！ 8-报名审核未通过,无法进行项目学习！9-已完成
        switch (status) {
            case 1:
                return Response.fail(Constants.DOCUMENT_PROJECT_NOT_START.getCode().toString(), Constants.DOCUMENT_PROJECT_NOT_START.getName());
            case 2:
                return Response.ok();
            case 3:
                return Response.fail(Constants.DOCUMENT_NOT_START_ENROLL.getCode().toString(), Constants.DOCUMENT_NOT_START_ENROLL.getName());
            case 4:
                return Response.fail(Constants.DOCUMENT_ENROLL_END.getCode().toString(), Constants.DOCUMENT_ENROLL_END.getName());
            case 5:
                return Response.fail(Constants.DOCUMENT_NO_ENROLL.getCode().toString(), Constants.DOCUMENT_NO_ENROLL.getName());
            case 6:
                return Response.fail(Constants.DOCUMENT_MEMBER_FULL.getCode().toString(), Constants.DOCUMENT_MEMBER_FULL.getName());
            case 7:
                return Response.fail(Constants.DOCUMENT_ADUIT_ING.getCode().toString(), Constants.DOCUMENT_ADUIT_ING.getName());
            case 8:
                return Response.fail(Constants.DOCUMENT_AUDIT_FAiL.getCode().toString(), Constants.DOCUMENT_AUDIT_FAiL.getName());
            case 9:
                return Response.ok();
        }
        return Response.ok();

    }

    //判断参数是否都传了
    private Boolean paramsIsNotNull(CanDownload vo) {
        Boolean needEnroll = vo.getNeedEnroll();
        Boolean needAudit = vo.getNeedAudit();
        Integer auditStatus = vo.getAuditStatus();
        Boolean hasFinished = vo.getHasFinished();
        Boolean hasEnroll = vo.getHasEnroll();
        Integer enrollLimit = vo.getEnrollLimit();
        Integer hasEnrollNum = vo.getHasEnrollNum();
        Date projectStartTime = vo.getProjectStartTime();
        Date projectEndTime = vo.getProjectEndTime();
        Date enrollStartTime = vo.getEnrollStartTime();
        Date enrollEndTime = vo.getEnrollEndTime();
        Integer termialType = vo.getTermialType();
        if (needAudit == null || needEnroll == null || auditStatus == null || hasFinished == null || hasEnroll == null || projectEndTime == null || projectStartTime == null) {
            if (needEnroll==true){
                if(enrollLimit == null || hasEnrollNum == null || enrollStartTime == null || enrollEndTime == null){
                    return false;
                }
            }
            return false;
        }
        return true;
    }

    //判断是否需要报名
    private Response whetherNeedEnroll(CanDownload vo) {
        //是否需要报名
        if (vo.getNeedEnroll()) {
            //是否已经报名
            if (vo.getHasEnroll()) {
                //是否需要审核
                return whetherNeedAudit(vo);

            } else {
                //判断能否报名
                return jugdeCanEnroll(vo);
            }

        }
        //判断项目时间
        return judgeTime(vo);
    }


    /**
     * 已经报名，判断是否需要审核
     *
     * @param
     * @return
     */
    private Response whetherNeedAudit(CanDownload vo) {

        if (vo.getNeedAudit()) {
            //审核状态：1：待审核，2：审核通过，3：审核不通过，0：不需要审核
            switch (vo.getAuditStatus()) {
                case 1:
                    return Response.fail(Constants.DOCUMENT_ADUIT_ING.getCode().toString(), Constants.DOCUMENT_ADUIT_ING.getName());
                case 2:
                    return judgeTime(vo);
                case 3:
                    return Response.fail(Constants.DOCUMENT_AUDIT_FAiL.getCode().toString(), Constants.DOCUMENT_AUDIT_FAiL.getName());
                case 0:
                    return judgeTime(vo);
            }
        }
        //根据当前时间判断培训项目能否学习
        return judgeTime(vo);
    }

    /**
     * 需要报名，根据当前时间，判断能否报名
     *
     * @return
     */
    private Response jugdeCanEnroll(CanDownload vo) {
        Long enrollStartTime = vo.getEnrollStartTime().getTime();
        Long enrollEndTime = vo.getEnrollEndTime().getTime();
        Long currentTime = vo.getCurrentTime();

        if (enrollStartTime <= currentTime && enrollEndTime >= currentTime) {
            //判断是否名额已满
            return whetherMembersFull(vo);
        } else if (currentTime < enrollStartTime) {
            //报名尚未开始，无法进行项目学习！
            return Response.fail(Constants.DOCUMENT_NOT_START_ENROLL.getCode().toString(), Constants.DOCUMENT_NOT_START_ENROLL.getName());
        } else {
            //报名已结束，无法进行项目学习！
            return Response.fail(Constants.DOCUMENT_ENROLL_END.getCode().toString(), Constants.DOCUMENT_ENROLL_END.getName());
        }
    }

    /**
     * //判断是否名额已满
     *
     * @param
     * @return
     */
    private Response whetherMembersFull(CanDownload vo) {


        Integer enrollLimit = vo.getEnrollLimit();
        Integer HasEnrolledNum = vo.getHasEnrollNum(); //已参与人数

        if (enrollLimit == 0 || enrollLimit > HasEnrolledNum) {
            //立即报名
            return Response.fail(Constants.DOCUMENT_NO_ENROLL.getCode().toString(), Constants.DOCUMENT_NO_ENROLL.getName());
        } else {
            return Response.fail(Constants.DOCUMENT_MEMBER_FULL.getCode().toString(), Constants.DOCUMENT_MEMBER_FULL.getName());
        }
    }

    /**
     * //判断培训时间 不在培训项目时间内不允许相关操作
     *
     * @param
     * @param
     * @return
     */
    private Response judgeTime(CanDownload vo) {
        if (vo.getHasFinished()) {
            //项目已完成 返回已完成状态
//            return Response.fail(Constants.TRAINING_MSG_FINISHED.getCode().toString(), Constants.TRAINING_MSG_FINISHED.getName());
            return Response.ok(true);
        } else {
            if (vo.getProjectStartTime().getTime() >= vo.getCurrentTime()) {
                return Response.fail(Constants.DOCUMENT_PROJECT_NOT_START.getCode().toString(), Constants.DOCUMENT_PROJECT_NOT_START.getName());
//            } else if (vo.getProjectEndTime().getTime() <= vo.getCurrentTime()) {
//                return Response.fail(Constants.DOCUMENT_ENROLL_END.getCode().toString(), Constants.DOCUMENT_ENROLL_END.getName());
            } else {
                return Response.ok(true);
            }
        }
    }
    
    //删除法目录方法
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
}



