package com.yizhi.application.lecturer.Controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.application.lecturer.Service.LecturerExportService;
import com.yizhi.application.tools.PageTools;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.vo.LecturerCourseVO;
import com.yizhi.lecturer.application.feign.LecturerClient;
import com.yizhi.lecturer.application.vo.*;
import com.yizhi.lecturer.application.vo.domain.LecturerDicVo;
import com.yizhi.lecturer.application.vo.domain.LecturerResponseVo;
import com.yizhi.lecturer.application.vo.domain.LecturerVo;
import com.yizhi.site.application.enums.PortalEnum;
import com.yizhi.site.application.feign.api.PortalApiFeignClients;
import com.yizhi.site.application.vo.site.PortalPlateVO;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import com.yizhi.util.application.date.DateUtil;
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 lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * @description: 讲师库字典
 * @author: lly
 * @date: 2019-04-18 11:50
 **/
@Log4j2
@Api(tags = "讲师库")
@RestController
@RequestMapping("/manage/lecturer")
public class LecturerController {

    private static final Logger LOG = LoggerFactory.getLogger(LecturerController.class);


    @Autowired
    private LecturerExportService lecturerExportService;

    @Autowired
    private CourseClient courseClient;

    @Autowired
    private PortalApiFeignClients portalApiFeignClients;

    @Autowired
    private TrainingProjectClient trainingProjectClient;

    @Autowired
    LecturerClient lecturerClient;

    @ApiOperation(value = "讲师字典", notes = "讲师字典")
    @GetMapping(value = "/list/code")
    public Response<String> codeList(
            @ApiParam(name = "code", value = "ed：学历，source:来源")
            @RequestParam(name = "code") String code) {
        List<LecturerDicVo> lecturerDicList = lecturerClient.getLecturerDicList(code);

        return Response.ok(lecturerDicList);

    }

    @ApiOperation(value = "创建讲师", notes = "创建讲师", response = LecturerVO.class)
    @PostMapping(value = "/add")
    public Response<String> addLecturer(@ApiParam("编码") @RequestBody LecturerVO lecturerVO) {

        if (lecturerVO.getId() == null) {
            //新增
            LecturerVO lecturer = lecturerClient.saveLecturer(lecturerVO);

            if (lecturer != null) {
                return Response.ok(lecturer);
            } else {
                return Response.fail();
            }
        } else {
            // 更新
            LecturerVO updateResult = lecturerClient.updateLecturer(lecturerVO);
            if (updateResult != null) {
                return Response.ok(updateResult);
            } else {
                return Response.fail();
            }
        }


    }

    @ApiOperation(value = "讲师修改", notes = "讲师修改1")
    @PostMapping(value = "/update")
    public Response<String> updateLecturer(@ApiParam(name = "lecturerVO", required = true) @RequestBody LecturerVO lecturerVO) {

        LecturerVO updateResult = lecturerClient.updateLecturer(lecturerVO);
        if (updateResult != null) {
            return Response.ok(updateResult);
        } else {
            return Response.fail();
        }

    }

    @ApiOperation(value = "讲师上", notes = "讲师修改1")
    @PostMapping(value = "/upOrDown")
    public Response<String> upOrDown(@ApiParam(name = "lecturer", required = true) @RequestBody LecturerVo lecturer) {
        LecturerResponseVo lecturerResponse = null;
        try {
            lecturerResponse = lecturerClient.upOrDown(lecturer);
            if ("fail".equals(lecturerResponse.getCode())){
                return Response.fail(lecturerResponse.getMsg());
            } else {
                return Response.ok();
            }
        } catch (Exception e) {
            log.info("错误提示{}",e);
            return Response.ok(Constants.LECTURER_MSG_BIZ_ERROR);
        }
    }

    @ApiOperation(value = "讲师详情", notes = "讲师详情", response = LecturerListVO.class)
    @GetMapping(value = "/get")
    public Response<String> getLecturer(@ApiParam(name = "id", value = "讲师id") @RequestParam(name = "id", required = true) Long id) {


        return Response.ok(lecturerClient.queryLecturer(id));

    }

    @ApiOperation(value = "讲师查询", notes = "讲师字典", response = LecturerListVO.class)
    @PostMapping(value = "/list")
    public Response queryList(@ApiParam("讲师列表请求实体") @RequestBody LecturerQueryVO lecturerQueryVO) {
        String mobile = lecturerQueryVO.getMobile();
        String name = lecturerQueryVO.getName();
        Integer pageNo = lecturerQueryVO.getPageNo();
        Integer pageSize = lecturerQueryVO.getPageSize();
        String sourceCode = lecturerQueryVO.getSourceCode();
        Page<LecturerListVO> lecturerListVOPage = lecturerClient.queryLecturer(name, mobile, sourceCode, pageNo, pageSize);

        return Response.ok(PageTools.versaPage(lecturerListVOPage));

    }

    /**
     * 讲师排序
     *
     * @param lecturerSortVO
     * @return
     * @date 2019-4-30
     */
    @ApiOperation(value = "讲师排序")
    @PostMapping("/sortLecturer")
    public Response<String> sortLecturer(@RequestBody LecturerSortVO lecturerSortVO) {
        try {
            lecturerClient.sortLecturer(lecturerSortVO);
        } catch (Exception e) {
            return Response.fail();
        }
        return Response.ok();
    }

    /**
     * 导出讲师库列表
     *
     * @return
     */
    @ApiOperation(value = "讲师库导出")
    @GetMapping("/exportLecturer")
    public Response<String> exportLecturer(@ApiParam(name = "keywords", value = "讲师名称") @RequestParam(name = "keywords", required = false) String keywords,
                                           @ApiParam(name = "sourceCode", value = "讲师来源inner 内部/outer 外部") @RequestParam(name = "sourceCode", required = false) String sourceCode,
                                           @ApiParam(name = "mobile", value = "手机号码") @RequestParam(name = "mobile", required = false) String mobile
    ) {
        RequestContext context = ContextHolder.get();
        List<LecturerListVO> lecturerListVOList = lecturerClient.exportLecturer(keywords, sourceCode, mobile);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", lecturerListVOList);
        map.put("siteId", context.getSiteId());
        map.put("companyId", context.getCompanyId());
        map.put("accountId", context.getAccountId());
        String taskLogSerialNo = "LECTURER-" + DateUtil.getYMDHMSS();;
        map.put("taskLogSerialNo",taskLogSerialNo);
        LOG.info("map参数：" + map);
        lecturerExportService.execute(map, Boolean.TRUE);

        return Response.ok("导出成功，任务编号："+taskLogSerialNo+",请在任务管理中下载查看完成情况!");
    }

    @ApiOperation(value = "讲师删除")
    @PostMapping("/del")
    public Response<String> delLecturer(@RequestBody LecturerSetVO lecturerSetVO) {
        if (CollectionUtils.isNotEmpty(lecturerSetVO.getIds())) {
            log.info("参数:" + lecturerSetVO);
            LecturerResponseVo lecturerResponse = lecturerClient.delLecturer(lecturerSetVO);
            return Response.ok("1000", lecturerResponse.getMsg(),null);
        } else {
            return Response.fail(InternationalEnums.LANGUAGECLASSIFYCONTROLLER3.getName());
        }
    }


    @ApiOperation(value = "讲师关联课程/培训", response = LecturerVo.class)
    @GetMapping("/relation")
    public Response<RelationVO> getRelationList(@ApiParam(name = "type", value = "1线上课程，2线下课程,3培训项目") @RequestParam(name = "type", required = true) Integer type,
                                                @ApiParam(name = "name", value = "查询字段") @RequestParam(name = "name", required = false) String name) {
        RequestContext context = ContextHolder.get();
        List<RelationVO> relationVOS = new ArrayList<>();
        try {

            if (type.equals(PortalEnum.ONE.ordinal()) || type.equals(PortalEnum.TWO.ordinal())) {
                List<LecturerCourseVO> lecturerCourseVOS = courseClient.getCoursesBysiteId(type, context.getSiteId(), name);
                if (CollectionUtils.isNotEmpty(lecturerCourseVOS)) {
                    relationVOS = lecturerCourseVOS.parallelStream().map(lecturerCourseVO -> {
                        RelationVO relationVO = new RelationVO();
                        relationVO.setRelationId(lecturerCourseVO.getCourseId());
                        relationVO.setType(lecturerCourseVO.getCourseType());
                        relationVO.setRelationName(lecturerCourseVO.getCourseName());
                        return relationVO;
                    }).collect(toList());
                }
            } else if (type.equals(PortalEnum.THREE.ordinal())) {
                List<TrainingProjectVo> trainingProjectList =
                        null;
                try {
                    trainingProjectList = trainingProjectClient.getBySiteId(context.getSiteId(), name);
                    if (CollectionUtils.isNotEmpty(trainingProjectList)) {
                        relationVOS = trainingProjectList.parallelStream().map(
                                trainingProject -> {
                                    RelationVO relationVO = new RelationVO();
                                    relationVO.setRelationId(trainingProject.getId());
                                    relationVO.setType(PortalEnum.THREE.ordinal());
                                    relationVO.setRelationName(trainingProject.getName());
                                    return relationVO;
                                }
                        ).collect(toList());
                    }

                } catch (Exception e) {
                    return Response.fail(Constants.TRAINING_MSG_BIZ_ERROR);
                }

            }
            return Response.ok(relationVOS);
        } catch (Exception e) {
            return Response.fail(Constants.COURSE_MSG_BIZ_ERROR);
        }

    }

    @ApiOperation(value = "首页配置模块讲师添加", notes = "首页配置模块讲师添加", response = LecturerListVO.class)
    @PostMapping(value = "/template/list")
    public Response<TemplateLecturerVO> queryLecturerListByTemplateId(@ApiParam("讲师列表请求实体") @RequestBody LecturerTemplateVO lecturerTemplateVO) {


        Page<TemplateLecturerVO> lecturerListVOPage = null;

        List<PortalPlateVO> plateVOList = portalApiFeignClients.getPlateVOList(lecturerTemplateVO.getTemplateId());
        LOG.info("plateVOList的长度：" + plateVOList.size());
        List<Long> ids = new ArrayList<>();
        try {
            if (CollectionUtils.isNotEmpty(plateVOList)) {
                ids = plateVOList.parallelStream().map(portalPlateVO -> {
                    return portalPlateVO.getId();
                }).collect(toList());
                lecturerTemplateVO.setIds(ids);
            }
            LOG.info("plateVOList的长度：" + ids);
        } catch (Exception e) {
            LOG.info("门户服务异常");
            return Response.fail(InternationalEnums.LECTURERCONTROLLER1.getName());
        }
        try {
            lecturerListVOPage = lecturerClient.queryLecturerByTemplateId(lecturerTemplateVO);
            LOG.info("lecturerListVOPage返回:" + lecturerListVOPage);
            return Response.ok(PageTools.versaPage(lecturerListVOPage));
        } catch (Exception e) {
            LOG.info("异常：" + e);
            return Response.fail(InternationalEnums.LECTURERCONTROLLER2.getName());
        }


    }

    /**
     * 通过讲师id获取讲师关联的内容
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "讲师查询", notes = "讲师字典", response = RelationVO.class)
    @GetMapping("/relation/get")
    public Response<RelationVO> getRelationsById(@ApiParam(name = "id", value = "讲师id") @RequestParam(name = "id", required = true) Long id) {
        return Response.ok(lecturerClient.getRelationsById(id));
    }

    /**
     * 更新关联
     *
     * @param lecturerVO
     * @return
     */
    @ApiOperation(value = "修改讲师关联")
    @PostMapping("/relation/update")
    public Response<String> updateRelation(@RequestBody LecturerVO lecturerVO) {
        try {
            lecturerClient.updateRelation(lecturerVO);
            return Response.ok(Constants.MSG_SUCCESS);
        } catch (Exception e) {
            LOG.info("讲师库异常");
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }


    }
    @ApiOperation(value = "修改讲师评分和评级",response = LecturerVo.class)
    @PostMapping("/update/gradeOrScore")
    public Response updateGrade(@RequestBody LecturerVo lecturer) {
        try {
            lecturerClient.updateGrade(lecturer);
            return Response.ok(Constants.MSG_SUCCESS);
        } catch (Exception e) {
            LOG.info("讲师库异常");
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }
}