package com.yizhi.application.album;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import com.yizhi.album.application.feign.AlbumClassifyClient;
import com.yizhi.album.application.feign.ClassifyStrategyClient;
import com.yizhi.album.application.vo.AlbumClassifyVo;
import com.yizhi.album.application.vo.ApiAlbumClassifyVo;
import com.yizhi.album.application.vo.domain.AlbumClassify;
import com.yizhi.album.application.vo.domain.ClassifyStrategy;
import com.yizhi.core.application.enums.*;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.vo.ClassifyVo;
import com.yizhi.util.application.date.DateUtil;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.json.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "管理端-专辑分类", description = "专辑分类接口")
@RestController
@RequestMapping("/manage/album/classify")
public class AlbumClassifyController {

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

	@Autowired
	private AlbumClassifyClient classifyClient;

	@Autowired
	private ClassifyStrategyClient classifyStrategyClient;
	@ApiOperation(value = "修改分类策略",response = ClassifyStrategy.class)
	@GetMapping(value = "/updateStrategy")
	public Response updateStrategy(
			@ApiParam(name = "type", value = "类型 1平铺式 2展开式") @RequestParam(value = "type", required = true) Integer type,
			@ApiParam(name = "status", value = "状态 0关闭 1打开") @RequestParam(value = "status", required = true) Integer status) {
		ClassifyStrategy strategy = classifyStrategyClient.update(type,status);
		return Response.ok(strategy);
	}

	@ApiOperation("添加分类")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Response<Integer> saveClassify(
			@ApiParam(name="classify",value = "传入parentName，name，description，ParentId") @RequestBody AlbumClassify classify) {

		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.ALBUMCLASSIFYCONTROLLER1.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);
		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 = "传入id") @RequestBody AlbumClassify classify) {
		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.ALBUMCLASSIFYCONTROLLER1.getCode());
		} else if (i == -1) {
			return Response.fail(InternationalEnums.ALBUMCLASSIFYCONTROLLER2.getCode());
		} else {
			return Response.ok("删除成功");
		}
	}

	@ApiOperation("分类名称修改")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Response<Integer> updateClassify(@ApiParam(value = "传入id name description") @RequestBody AlbumClassify classify) {
		RequestContext requestContext = ContextHolder.get();
		boolean checkExtisRet = classifyClient.checkExtisClassifyName(classify.getCode(), 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 = "每页条数,默认10条") @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<AlbumClassify> page = classifyClient.listClassify(isStartHQ, name, pageNo, pageSize,
				requestContext.getCompanyId(), requestContext.getSiteId(), null);
		List<AlbumClassifyVo> list = new ArrayList<>();
		List<AlbumClassify> records = null;
		int total = 0;
		if (page != null) {
			total = page.getTotal();
			AlbumClassifyVo classifyVo = null;
			records = page.getRecords();
			for (int i = 0; i < records.size(); i++) {
				classifyVo = new AlbumClassifyVo();
				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 = "分类排序",response = AlbumClassify.class)
	@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<AlbumClassify> list1 = JsonUtil.json2List(list, AlbumClassify.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 = "每页条数,默认10条") @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
		logger.info("开始进入web端的分页查询-------------------------------");
		RequestContext requestContext = ContextHolder.get();
		Page<ApiAlbumClassifyVo> 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 = "返回专辑分类策略")
    @GetMapping("/getStrategy")
    public Response<String> getStrategy(){
    	RequestContext context = ContextHolder.get();
    	Long siteId = context.getSiteId();
    	Long companyId = context.getCompanyId();
    	ClassifyStrategy strategy = classifyStrategyClient.get(companyId, siteId);
    	if (strategy==null) {
    		strategy = new ClassifyStrategy();
        	strategy.setStatus(0);
        	strategy.setType(0);
		}
        return Response.ok(strategy);
    }
}
