package com.yizhi.application.course.controller;
import com.alibaba.fastjson.JSON;
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.ClassifyClient;
import com.yizhi.course.application.feign.ClassifyGroupClient;
import com.yizhi.course.application.vo.ApiClassifyVo;
import com.yizhi.course.application.vo.ClassifyVo;
import com.yizhi.course.application.vo.domain.ClassifyEntityVo;
import com.yizhi.util.application.date.DateUtil;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.json.JsonUtil;
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.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * Created with IntelliJ. IDEA
 * User:zhuwenwen
 * Date: 2018/3/20
 * Time: 13:26
 **/
@Api(tags="管理端-课程分类",description="课程分类接口")
@RestController
@RequestMapping("/manage/classify")
public class ClassifyController {

    @Autowired
    private ClassifyClient classifyClient;

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

    @Autowired
    private ClassifyGroupClient classifyGroupClient;


    @ApiOperation("添加分类")
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Response<Integer> saveClassify(
            @ApiParam(value = "传入parentName，name，description，ParentId")@RequestBody ClassifyEntityVo classify
//            @ApiParam(required = false,value = "上级分类名称") @RequestParam(value = "parentName",required = false) String parentName,
//            @ApiParam(required = true,value = "分类名称")@RequestParam(value = "name",required = true) String name,
//            @ApiParam(required = false,value = "分类描述")@RequestParam(value = "description",required = false) String description,
//            @ApiParam(required = false,value = "父类id")@RequestParam(value = "id",required = false) String ParentId
    ){

        Date date=new Date();
        RequestContext requestContext = ContextHolder.get();
        boolean checkExtisRet = classifyClient.checkExtisClassifyName(classify.getName(),classify.getParentId()
                ,requestContext.getSiteId(),1,classify.getId());
        if(!checkExtisRet){
            return Response.fail(InternationalEnums.CLASSIFYCONTROLLER1.getCode());
        }
        classify.setCreateTime(date);
        classify.setCode(Long.toString(date.getTime()));
        classify.setCompanyId(requestContext.getCompanyId());
        classify.setCreateById(requestContext.getAccountId());
        classify.setCreateByName(requestContext.getAccountName());
        classify.setSiteId(requestContext.getSiteId());
        classify.setOrgId(requestContext.getOrgId() == null ? new Long(0) : requestContext.getOrgId());
        classify.setStatus(1);
        classify.setSource(1);
        if(classify.getParentId() != null){
        }else {
            classify.setParentId(0L);
        }
        try {
            int i = classifyClient.saveClassify(classify);
            if(i==1){
                return Response.ok(1);
            }
            else if(i==3){
                return Response.fail(InternationalEnums.CLASSIFYCONTROLLER1.getCode());
            }
            else{
                return Response.fail(InternationalEnums.OFFLINECOURSECLASSIFYCONTROLLER3.getCode());
            }
        }catch (Exception e){
            logger.error("",e);
            return Response.fail(InternationalEnums.CLASSIFYCONTROLLER2.getCode());
        }
    }

    @ApiOperation(value = "分类删除")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Response<Integer> deleteClassify(
            @ApiParam(value = "传入idd")@RequestBody ClassifyEntityVo classify
//            @ApiParam(required = true,value = "分类id")@RequestParam(value = "id",required = true) Long id
    ){

        boolean jonStatus = classifyGroupClient.joinStatus(classify.getId());
        if(!jonStatus){
            return Response.fail(InternationalEnums.CLASSIFYCONTROLLER3.getCode());
        }
        int i=0;
        try {
            i= classifyClient.deleteClassify(classify);
        }catch (Exception e){
            logger.error("删除失败",e);
            return Response.fail(InternationalEnums.CLASSIFYCONTROLLER4.getCode());
        }
        if (i== 0){
            return Response.fail(InternationalEnums.CLASSIFYCONTROLLER5.getCode());
        }
        else if (i == -1){
            return Response.fail(InternationalEnums.CLASSIFYCONTROLLER6.getCode());//hutao add
        }
        else {
            return Response.ok("删除成功");
        }
    }

    @ApiOperation("分类名称修改")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Response<Integer> updateClassify(
            @ApiParam(value = "传入id name description")@RequestBody ClassifyEntityVo classify
//            @ApiParam(required = true,value = "分类id")@RequestParam(value = "id",required = true) Long id,
//            @ApiParam(required = false,value = "分类名称")@RequestParam(value = "name",required = false)String name,
//            @ApiParam(required = false,value = "分类描述") @RequestParam(value = "description",required = false) String description
    ){
        RequestContext requestContext = ContextHolder.get();
        boolean checkExtisRet = classifyClient.checkExtisClassifyName(classify.getName(),classify.getParentId()
                ,requestContext.getSiteId(),2,classify.getId());
        if(!checkExtisRet){
            return Response.fail(InternationalEnums.CLASSIFYCONTROLLER1.getCode());
        }
        Long accountId = requestContext.getAccountId();
        String accountName = requestContext.getAccountName();
        classify.setUpdateById(accountId);
        classify.setUpdateByName(accountName);
        classify.setUpdateTime(new Date());
        try{
           int i= classifyClient.updateClassify(classify);
            if(i==4){
                return Response.fail(InternationalEnums.CLASSIFYCONTROLLER7.getCode());
            }
            else if(i==3){
                return Response.fail(InternationalEnums.CLASSIFYCONTROLLER1.getCode());
            }
        }catch (Exception e){

            logger.error("",e);
            return Response.fail(InternationalEnums.DOCUMENTCLASSIFYCOMTROLLER3.getCode());
        }

        return Response.ok("修改成功");
    }

    @ApiOperation(value = "分类查询",response = ClassifyVo.class)
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Response<List> listClassify(
            @ApiParam(required = false,value = "是否进行分级授权查询") @RequestParam(required = false,name = "isStartHQ") Boolean isStartHQ,
            @ApiParam(required = false,value = "分类名称")@RequestParam(value = "name",required = false) String name,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页") @RequestParam(name = "pageNo", defaultValue = "1",required = false) Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条") @RequestParam(name = "pageSize", defaultValue = "10",required = false) Integer pageSize
    ){
        RequestContext requestContext = ContextHolder.get();
        logger.info("课程分类查询的上下文参数={}", JSON.toJSONString(requestContext));
        if(Objects.isNull(isStartHQ)){
            isStartHQ = false;
        }
        Page<ClassifyEntityVo> page = classifyClient.listClassify(isStartHQ,name,pageNo,pageSize,requestContext.getCompanyId(),requestContext.getSiteId(),null);

        List<ClassifyEntityVo> li=page.getRecords();
        int index=10;
        while (li.isEmpty()&&index>0){
            page = classifyClient.listClassify(isStartHQ,name,pageNo,pageSize,requestContext.getCompanyId(),requestContext.getSiteId(),null);
            li=page.getRecords();
            index--;
        }

        List<ClassifyVo> list= new ArrayList<>();
        List<ClassifyEntityVo> records =null;
        int total=0;
        if (page != null) {
            total = page.getTotal();
            ClassifyVo classifyVo = null;
            records = page.getRecords();
            for (int i = 0; i < records.size(); i++) {
                classifyVo=new ClassifyVo();
                classifyVo.setCode(records.get(i).getCode());
                Date date = records.get(i).getCreateTime();
                String createTime = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
                classifyVo.setCreateTime(createTime);
                classifyVo.setId(records.get(i).getId());
                classifyVo.setLayer(records.get(i).getLayer());
                classifyVo.setName(records.get(i).getName());
                classifyVo.setStatus(records.get(i).getStatus());
                classifyVo.setSort(records.get(i).getSort());
                classifyVo.setTotal(total);
                list.add(classifyVo);
            }
        }
        return Response.ok(list);
    }

    @ApiOperation(value = "分类导入")
    @RequestMapping(value = "/import",method = RequestMethod.POST)
    public Response<Integer> importClassify(
            @ApiParam(required = true,value = "分类导入url")@RequestParam(value = "url",required = true) String url
    ){
        return Response.ok("导入成功");
    }

    @ApiOperation("分类排序")
    @RequestMapping(value = "/sort",method = RequestMethod.POST)
    public Response<Integer> sortClassify(
            @ApiParam(value = "排序列表,格式[{id,sort},{id,sort}] 排序好把分类id和排序sort用json传递",required = true) @RequestBody String list
    ){
        List<ClassifyEntityVo> list1 = JsonUtil.json2List(list, ClassifyEntityVo.class);
        try{
            logger.info("web端传入要排序的ID列表----------:"+list);
            return Response.ok(classifyClient.sortClassify(list1));
        }catch (Exception e){
            logger.error("",e);
            return Response.fail(InternationalEnums.CLASSIFYCONTROLLER8.getCode());
        }
    }

    @ApiOperation(value = "分类分页查询",response = ClassifyVo.class)
    @RequestMapping(value = "/page/list",method = RequestMethod.GET)
    public Response pageList(
            @ApiParam(required = false,value = "分类名称")@RequestParam(value = "name",required = false) String name,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页") @RequestParam(name = "pageNo", defaultValue = "1",required = false) Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条") @RequestParam(name = "pageSize", defaultValue = "10",required = false) Integer pageSize
    ){
        logger.info("开始进入web端的分页查询-------------------------------");
        RequestContext requestContext = ContextHolder.get();
        Page<ApiClassifyVo> page = classifyClient.pageList(name,pageNo,pageSize,requestContext.getCompanyId(),requestContext.getSiteId(),null);
         return Response.ok(page);
    }

    /**
     * 验证同站点下 同级的分类不能重名
     *
     * @param name      分类名
     * @param layer     分类层级
     * @param id        分类id （修改的时候传入）
     * @return Boolean
     */
    @GetMapping("/vail/name")
    public Response vailName(
            @ApiParam(value = "分类名称")@RequestParam(name = "name") String name,
            @ApiParam(value = "分类层级")@RequestParam(name = "layer") Integer layer,
            @ApiParam(value = "分类id(修改的时候传入）",required = false)@RequestParam(name = "id",required = false) Long id

    ){
        RequestContext requestContext = ContextHolder.get();
        if (classifyClient.vailName(name,layer,requestContext.getCompanyId(),requestContext.getSiteId(),id)) {
            return Response.ok("该分类名可以使用");
        }
        return Response.fail(InternationalEnums.CLASSIFYCONTROLLER9.getCode());
    }


    @ApiOperation(value = "根据课程分类id查询分类名称")
    @GetMapping("/find/id")
    public Response<String> getById(@ApiParam(value = "课程分类id") @RequestParam("id") Long id){
        ClassifyEntityVo classify = classifyClient.getById(id);
        return Response.ok(classify.getName());
    }


}

