package org.springblade.material.controller;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.material.entity.BladeMaterial;
import org.springblade.material.entity.BladeMaterialCategory;
import org.springblade.material.service.IBladeMaterialCategoryService;
import org.springblade.material.service.IBladeMaterialService;
import org.springblade.modules.system.entity.Role;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import cn.hutool.core.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 素材分类表 前端控制器
 * </p>
 *
 * @author zbc
 * @since 2022-03-02
 */
@RestController
@RequestMapping("/material/category")
@Api(value = "素材分类管理", tags = "素材分类接口")
@Slf4j
public class BladeMaterialCategoryController {

	@Autowired
	private IBladeMaterialCategoryService bladeMaterialCategoryService;

	@Autowired
	private IBladeMaterialService bladeMaterialService;

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IUserService userService;

	@Value("${datasource.type}")
	private String dbType;


	@PostMapping("/save")
	@ApiOperation(value = "新增素材分类")
	public R save(@Valid @RequestBody BladeMaterialCategory category) {
		Long userId = SecureUtil.getUserId();
		List<BladeMaterialCategory> list = bladeMaterialCategoryService.list(new LambdaQueryWrapper<BladeMaterialCategory>()
			.eq(BladeMaterialCategory::getCategoryName, category.getCategoryName())
		);
		if(!list.isEmpty() || list.size() > 0){
			return R.fail("分类名称已存在，不能重复录入");
		}
		String code = RandomUtil.randomString(9);
		category.setCategoryCode(code);
		category.setCreateTime(new Date());
		category.setCreateUser(userId);
		if(category.getSort() == null){
			category.setSort(0);
		}
		boolean sa = bladeMaterialCategoryService.save(category);
		if(sa){
			return R.data(category);
		}
		return R.status(sa);
	}


	@PostMapping("/update")
	@ApiOperation(value = "编辑素材分类")
	public R update(@RequestBody BladeMaterialCategory category) {
		return R.status(bladeMaterialCategoryService.updateById(category));
	}



	@GetMapping("/page")
	@ApiOperation(value = "素材分类列表")
	public R<IPage<BladeMaterialCategory>> page(Integer materialType,Query query) {
		IPage<BladeMaterialCategory> page = Condition.getPage(query);
		Long userId = SecureUtil.getUserId();
		User user = userService.getById(userId);

		IPage<BladeMaterialCategory> pages = bladeMaterialCategoryService.page(page,new LambdaQueryWrapper<BladeMaterialCategory>()
			.eq(BladeMaterialCategory::getCreateUser,userId)
			.or()
			.eq(BladeMaterialCategory::getPermissions,1)
			.or()
//			.apply(user.getRoleId() != null,"find_in_set('"+user.getRoleId()+"',role_ids)")
			.apply(user.getRoleId() != null,"role_ids like '%"+user.getRoleId()+"%'")
			.orderByAsc(BladeMaterialCategory::getSort)
		);

		int count = 0;
		if(materialType != null){
			for (BladeMaterialCategory record : pages.getRecords()) {
				//materialType 1 图片 2 音频 3 视频
				if(materialType == 1){
					if ("mysql".equals(dbType)) {
						count = (int)bladeMaterialService.count(new LambdaQueryWrapper<BladeMaterial>()
										.eq(BladeMaterial::getCategoryId, record.getId())
							            .apply("SUBSTRING_INDEX(material_name,'.',-1) != 'mp4'" + " AND SUBSTRING_INDEX(material_name,'.',-1) != 'mp3'")
						);
					} else if ("kingbase".equals(dbType)) {
						count = (int)bladeMaterialService.count(new LambdaQueryWrapper<BladeMaterial>()
										.eq(BladeMaterial::getCategoryId, record.getId())
										.apply("SPLIT_PART(material_name,'.',2) != 'mp4'" + " AND SPLIT_PART(material_name,'.',2) != 'mp3'")
						);
					}
				}
				if(materialType == 2){
					if ("mysql".equals(dbType)) {
						count = (int)bladeMaterialService.count(new LambdaQueryWrapper<BladeMaterial>()
										.eq(BladeMaterial::getCategoryId, record.getId())
							            .apply("SUBSTRING_INDEX(material_name,'.',-1) = 'mp3'")
						);
					} else if ("kingbase".equals(dbType)) {
						count = (int)bladeMaterialService.count(new LambdaQueryWrapper<BladeMaterial>()
										.eq(BladeMaterial::getCategoryId, record.getId())
										.apply("SPLIT_PART(material_name,'.',2) = 'mp3'")
						);
					}
				}
				if(materialType == 3){
					if ("mysql".equals(dbType)) {
						count = (int)bladeMaterialService.count(new LambdaQueryWrapper<BladeMaterial>()
										.eq(BladeMaterial::getCategoryId, record.getId())
							.apply("SUBSTRING_INDEX(material_name,'.',-1) = 'mp4'")
										.orderByDesc(BladeMaterial::getCreateTime)
						);
					} else if ("kingbase".equals(dbType)) {
						count = (int)bladeMaterialService.count(new LambdaQueryWrapper<BladeMaterial>()
										.eq(BladeMaterial::getCategoryId, record.getId())
										.apply("SPLIT_PART(material_name,'.',2) = 'mp4'")
										.orderByDesc(BladeMaterial::getCreateTime)
						);
					}
				}
				record.setMaterialNum(count);
			}
		}
		return R.data(pages);
	}


	@GetMapping("/select/list")
	@ApiOperation(value = "角色下拉列表")
	public R selectList() {
		List<Role> list = roleService.list(
			new LambdaQueryWrapper<Role>()
				.eq(Role::getIsDeleted, 0)
		);
		List<Map<String, Object>> data = list.stream()
			.map(obj -> {
				Map<String, Object> map = new HashMap<>();
				map.put("id", obj.getId());
				map.put("name", obj.getRoleName());
				return map;
			}).collect(Collectors.toList());
		return R.data(data);
	}


	/*@PostMapping("/remove")
	@ApiOperation(value = "删除指定分类素材")
	public R update(Long id) {
		if(id == null){
			return R.fail("参数异常");
		}
		BladeMaterialCategory category = bladeMaterialCategoryService.getById(id);
		if(category == null){
			return R.fail("所选分类不存在");
		}
		return R.status(bladeMaterialCategoryService.removeById(id));
	}*/

}

