package com.yizhi.application.offlineCourse;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.OfflineCourseClient;
import com.yizhi.course.application.vo.OfflineCourseDeleteVo;
import com.yizhi.course.application.vo.OfflineCourseVo;
import com.yizhi.training.application.feign.TpPlanActivityClient;
import com.yizhi.util.application.domain.Response;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author huangliang
 * @Date 2018/10/16
 */
@Api(tags = "管理端-线下课程", description = "线下课程接口")
@RestController
@RequestMapping("/manage/offlineCourse")
public class OfflineCourseController {

    private Logger logger = LoggerFactory.getLogger(OfflineCourseController.class);

    @Autowired
    private OfflineCourseClient offlineCourseClient;

    @Autowired
    private TpPlanActivityClient trainingProjectClient;

    @PostMapping("/delete")
    @ApiOperation(value = "删除线下课程", notes = "删除")
    public Response<String> delete(@ApiParam(name = "offlineCourseDeleteVo", value = "ids 课程主键 可传入多个  用逗号, 分割")
                                   @RequestBody OfflineCourseDeleteVo offlineCourseDeleteVo) {
//        try {
//            Boolean f = offlineCourseClient.delete(offlineCourseDeleteVo);
//            if (f) {
//                return Response.ok("删除成功！");
//            } else {
//                return Response.fail("上架课程不能删除！");
//            }
//        } catch (Exception e) {
//            logger.error("删除失败", e);
//            return Response.fail();
//        }
        List<Long> list = new ArrayList<>();
        String[] offlineCourseArr = offlineCourseDeleteVo.getIds().split(",");
        for (String offlineCourseId : offlineCourseArr) {
            list.add(Long.valueOf(offlineCourseId));
        }
        Set<String> tpNames = trainingProjectClient.checkBizIsExistInTpNames(list);
        if (CollectionUtils.isEmpty(tpNames)) {
            Boolean f = offlineCourseClient.delete(offlineCourseDeleteVo);
            if (f) {
                return Response.ok("删除成功！");
            } else {
                return Response.fail(InternationalEnums.OFFLINECOURSECONTROLLER1.getCode());
            }
        } else {
            StringBuilder sb = new StringBuilder();
            for (String tpName : tpNames) {
                sb.append(tpName);
                sb.append(",");
            }
            return Response.fail("{{"+InternationalEnums.OFFLINECOURSECONTROLLER2.getCode()+"}}" + sb.toString() + "{{"+InternationalEnums.OFFLINECOURSECONTROLLER7.getCode()+"}}");
        }

    }

    @PostMapping("/save")
    @ApiOperation(value = "添加线下课程", notes = "添加")
    public Response<String> save(@ApiParam(name = "OfflineCourseVo", value = "需要传入name, code,classifyId，authorUnit，description，tags") @RequestBody OfflineCourseVo offlineCourseVo) {
        RequestContext requestContext = ContextHolder.get();
        offlineCourseVo.setCompanyId(requestContext.getCompanyId());
        offlineCourseVo.setSiteId(requestContext.getSiteId());
        offlineCourseVo.setOrgId(requestContext.getOrgId());
        offlineCourseVo.setCreateById(requestContext.getAccountId());
        offlineCourseVo.setCreateByName(requestContext.getAccountName());

        OfflineCourseVo f = offlineCourseClient.save(offlineCourseVo);
        if (f == null) {
            return Response.fail(InternationalEnums.OFFLINECOURSECONTROLLER4.getCode());
        }
        return Response.ok();
    }

    @GetMapping("/code/verifyCourse")
    @ApiOperation(value = "课程code唯一性验证", notes = "课程code唯一性验证")
    public Response<String> verifyCourseCode(
            @ApiParam(name = "id", value = "线下课程主键,线下课程做更新时传入", required = false) @RequestParam(name = "id", required = false) Long id,
            @ApiParam(name = "code", value = "课程code") @RequestParam(name = "code") String code
    ) {
        RequestContext requestContext = ContextHolder.get();
        if (offlineCourseClient.verifyCourseCode(id, code, requestContext.getSiteId())) {
            return Response.ok("课程编码可以使用");
        }
        return Response.fail("", InternationalEnums.OFFLINECOURSECONTROLLER3.getCode());
    }

    @PostMapping("/update")
    @ApiOperation(value = "线下课程修改", notes = "修改")
    public Response update(@ApiParam(name = "offlineCourseVo", value = "课程接受参数对象") @RequestBody OfflineCourseVo offlineCourseVo
    ) {
        RequestContext requestContext = ContextHolder.get();
        offlineCourseVo.setUpdateById(requestContext.getAccountId());
        offlineCourseVo.setUpdateByName(requestContext.getAccountName());
        offlineCourseVo.setSiteId(requestContext.getSiteId());
        offlineCourseVo.setUpdateTime(new Date());
        Boolean f = offlineCourseClient.update(offlineCourseVo);
        if (f) {
            return Response.ok();
        } else {
            return Response.fail(InternationalEnums.OFFLINECOURSECONTROLLER4.getCode());
        }
    }

    @GetMapping("/list")
    @ApiOperation(value = "线下课程分页查询", notes = "返回分页结果集", response = OfflineCourseVo.class)
    public Response<Page<OfflineCourseVo>> list(
            @ApiParam(name = "name ", value = "课程名称", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(name = "offlineClassifyId", value = "分类id", required = false) @RequestParam(name = "offlineClassifyId", required = false) Long offlineClassifyId,
            @ApiParam(name = "status", value = "0 未上架 1 已上架 2 草稿", required = false) @RequestParam(name = "status", required = false) Integer status,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize
    ) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        map.put("name", name);
        map.put("status", status);
        map.put("offlineClassifyId", offlineClassifyId);
        RequestContext requestContext = ContextHolder.get();
        map.put("companyId", requestContext.getCompanyId());
        map.put("siteId", requestContext.getSiteId());
        map.put("orgIds", requestContext.getOrgIds());

        Page<OfflineCourseVo> page = offlineCourseClient.list(map);
        return Response.ok(page);
    }

    @PostMapping("/up")
    @ApiOperation(value = "线下课程_课程上架", notes = "上架操作")
    public Response<String> up(
            @ApiParam(name = "offlineCourse", value = "只需传入id") @RequestBody OfflineCourseVo offlineCourse
    ) {
        Boolean f = offlineCourseClient.up(offlineCourse);
        if (f) {
            return Response.ok("上架成功");
        } else {
            return Response.fail();
        }
    }

    @PostMapping("/down")
    @ApiOperation(value = "下架", notes = "下架操作")
    public Response<String> down(
            @ApiParam(name = "offlineCourse", value = "只需传入id") @RequestBody OfflineCourseVo offlineCourse
    ) {
        List<Long> list = new ArrayList<>();
        list.add(offlineCourse.getId());
        Set<String> tpNames = trainingProjectClient.checkBizIsExistInTpNames(list);
        if (CollectionUtils.isEmpty(tpNames)){
            Boolean f = offlineCourseClient.down(offlineCourse);
            if (f) {
                return Response.ok("下架成功");
            } else {
                return Response.fail(InternationalEnums.OFFLINECOURSECONTROLLER5.getCode());
            }
        }else{
            StringBuilder sb = new StringBuilder();
            for (String s : tpNames) {
                sb.append(s);
                sb.append(",");
            }
            return Response.fail("{{"+InternationalEnums.OFFLINECOURSECONTROLLER6.getCode()+"}}"+ sb.toString()+"{{" + InternationalEnums.OFFLINECOURSECONTROLLER8.getCode()+"}}");
        }
    }

    @GetMapping("/get")
    @ApiOperation(value = "课程查看", notes = "查看操作", response = OfflineCourseVo.class)
    public Response get(
            @ApiParam(name = "id", value = "课程接受参数对象") @RequestParam(name = "id") Long id
    ) {
        RequestContext requestContext = ContextHolder.get();
        OfflineCourseVo courseVo = offlineCourseClient.get(id);
        return Response.ok(courseVo);
    }

    @PostMapping("/upload")
    @ApiOperation(value = "上传文件", notes = "上传文件", response = OfflineCourseVo.class)
    public Response<String> upload(
            @ApiParam(name = "offlineCourseVo", value = "", required = true) @RequestBody OfflineCourseVo offlineCourseVo
    ) {
        RequestContext requestContext = ContextHolder.get();
        offlineCourseVo.setUpdateById(requestContext.getAccountId());
        offlineCourseVo.setUpdateByName(requestContext.getAccountName());
        offlineCourseVo.setFileName(offlineCourseVo.getFileName());
        offlineCourseVo.setUpdateTime(new Date());

        String taskName = offlineCourseClient.upload(offlineCourseVo);
        String currentSerialNo = taskName.substring(taskName.lastIndexOf(" "));
        return Response.ok("上传并发布成功,已经成功创建任务,任务编号: "+currentSerialNo+", 请到任务管理中查看完成情况");
    }

    @PostMapping("/download")
    @ApiOperation(value = "下载报表数据")
    public Response<String> download(
            @ApiParam("参数形式如：{\"startTime\": \"2018-01-10\", \"endTime\": \"2018-01-10\", \"name\" : \"course\"}")
            @RequestBody Map<String, Object> param
    ) {
        RequestContext requestContext = ContextHolder.get();
        Date submitTime = new Date();
        Long taskId = submitTime.getTime();
        String serialNo=""+taskId;
        param.put("taskId",taskId);
        param.put("serialNo",serialNo);
        String taskName = offlineCourseClient.download(param);
        return Response.ok("已经成功创建任务, 任务编号: "+serialNo+", 请到任务管理中查看完成情况");
    }

}
