/*
 * Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yifu.cloud.plus.v1.yifu.admin.controller;

import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDict;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDictItem;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysDictItemService;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysDictService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.MsgUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.common.security.annotation.Inner;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
 * @author lengleng
 * @since 2019-03-19
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/dict")
@Tag(name = "字典管理模块")
public class DictController {

	private final SysDictItemService sysDictItemService;

	private final SysDictService sysDictService;

	/**
	 * 通过ID查询字典信息
	 * @param id ID
	 * @return 字典信息
	 */
	@GetMapping("/{id:\\d+}")
	public R<SysDict> getById(@PathVariable Long id) {
		SysDict sysDict = sysDictService.getById(id);
		SysDict sysDict1 = sysDictService.getOne(Wrappers.<SysDict>query().lambda().eq(SysDict::getType, sysDict.getParentItemType()));
		if (null != sysDict1) {
			sysDict.setParentItemName(sysDict1.getDescription());
		}
		return R.ok(sysDict);
	}

	/**
	 * 分页查询字典信息
	 * @param page 分页对象
	 * @return 分页对象
	 */
	@GetMapping("/page")
	public R<IPage<SysDict>> getDictPage(Page page, SysDict sysDict) {
		return R.ok(sysDictService.pageAsso(page, sysDict));
	}

	/**
	 * 通过字典类型查找字典
	 * @param type 类型
	 * @return 同类型字典
	 */
	@GetMapping("/type/{type}")
	@Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type")
	public R<List<SysDictItem>> getDictByType(@PathVariable("type") String type) {
		return R.ok(sysDictItemService.list(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getType, type)));
	}

	/**
	 * 添加字典
	 * @param sysDict 字典信息
	 * @return success、false
	 */
	@SysLog("添加字典")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_dict_add')")
	public R<Boolean> save(@Valid @RequestBody SysDict sysDict) {
		SysDict dict = sysDictService.getOne(Wrappers.<SysDict>query().lambda()
				.eq(SysDict::getType,sysDict.getType())
				.eq(SysDict::getDelFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(dict)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_ADD_TYPE_EXISTS));
		}
		return R.ok(sysDictService.save(sysDict));
	}

	/**
	 * 删除字典，并且清除字典缓存
	 * @param id ID
	 * @return R
	 */
	@SysLog("删除字典")
	@DeleteMapping("/{id:\\d+}")
	@PreAuthorize("@pms.hasPermission('sys_dict_del')")
	public R removeById(@PathVariable Long id) {
		SysDict sysDict = sysDictService.getById(id);
		if (Common.isNotNull(sysDict)){
			SysDict dict = sysDictService.getOne(Wrappers.<SysDict>query().lambda()
					.eq(SysDict::getParentItemType,sysDict.getType())
					.eq(SysDict::getDelFlag,CommonConstants.ZERO_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(dict)){
				return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_DELETE_EXIST_CHILD));
			}
		}
		sysDictService.removeDict(id);
		return R.ok();
	}

	/**
	 * 修改字典
	 * @param sysDict 字典信息
	 * @return success/false
	 */
	@PutMapping
	@SysLog("修改字典")
	@PreAuthorize("@pms.hasPermission('sys_dict_edit')")
	public R updateById(@Valid @RequestBody SysDict sysDict) {
		SysDict dict = sysDictService.getOne(Wrappers.<SysDict>query().lambda()
				.eq(SysDict::getType,sysDict.getType())
				.ne(SysDict::getId,sysDict.getId())
				.eq(SysDict::getDelFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(dict)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_ADD_TYPE_EXISTS));
		}
		sysDictService.updateDict(sysDict);
		return R.ok();
	}

	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param sysDictItem 字典项
	 * @return
	 */
	@GetMapping("/item/page")
	public R<IPage<SysDictItem>> getSysDictItemPage(Page page, SysDictItem sysDictItem) {
		return R.ok(sysDictItemService.pageItem(page, sysDictItem));
	}

	/**
	 * 获取所有字典数据
	 * @return
	 */
	@GetMapping("/item/getAllDictItem")
	public R<Map<String, Object>> getAllDictItem() {
		return sysDictItemService.getAllDictItem();
	}

	/**
	 * 通过id查询父级字典的字典值
	 * @param itemTypes
	 * @return R
	 */
	@SysLog("通过id查询父级字典的字典值")
	@GetMapping("/getParentDictItemByTypes")
	public R<Map<String, Object>> getParentDictItemByTypes(String  itemTypes) {
		return sysDictItemService.getParentDictItemByTypes(itemTypes);
	}

	/**
	 * 通过id查询父级字典的字典值
	 * @param itemTypes
	 * @return R
	 */
	@SysLog("通过id查询父级字典的字典值")
	@GetMapping("/getDictItemsByTypes")
	public R<Map<String, List>> getDictItemsByTypes(String  itemTypes) {
		return sysDictItemService.getDictItemsByTypes(itemTypes);
	}
	/**
	 * 通过id查询字典项
	 * @param id id
	 * @return R
	 */
	@SysLog("通过id查询字典项")
	@GetMapping("/item/{id:\\d+}")
	public R<SysDictItem> getDictItemById(@PathVariable("id") Long id) {
		SysDictItem  item = sysDictItemService.getById(id);
		if (Common.isNotNull(item)){
			item.setParentLabelOfValue(sysDictService.getParentDicLabelById(item.getType(),item.getValue()));
		}
		return R.ok(item);
	}

	/**
	 * 通过id查询父级字典的字典值
	 * @param itemType
	 * @return R
	 */
	@SysLog("通过id查询父级字典的字典值")
	@GetMapping("/getParentDictItemByType")
	public R<List<SysDictItem>> getParentDictItemByType(String  itemType) {
		SysDict  dict = sysDictService.getOne(Wrappers.<SysDict>query().lambda()
				.eq(SysDict::getType,itemType)
				.eq(SysDict::getDelFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isEmpty(dict)){
			return R.ok();
		}
		if (Common.isNotNull(dict.getParentItemType())){
			return R.ok(sysDictItemService.list(Wrappers.<SysDictItem>query().lambda()
					.eq(SysDictItem::getType,dict.getParentItemType())
					.eq(SysDictItem::getDelFlag,CommonConstants.ZERO_STRING)
					.eq(SysDictItem::getDisable,CommonConstants.ZERO_STRING)));
		}
		return R.ok();
	}

	/**
	 * 新增字典项
	 * @param sysDictItem 字典项
	 * @return R
	 */
	@SysLog("新增字典项")
	@PostMapping("/item")
	public R<Boolean> save(@RequestBody SysDictItem sysDictItem) {
		SysDictItem item = sysDictItemService.getOne(Wrappers.<SysDictItem>query().lambda()
				.eq(SysDictItem::getType,sysDictItem.getType())
				.eq(SysDictItem::getValue,sysDictItem.getValue())
				.eq(SysDictItem::getDelFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(item)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_ITEM_ADD_VALUE_EXIST));
		}
		return sysDictItemService.saveDiy(sysDictItem);
	}

	/**
	 * 修改字典项
	 * @param sysDictItem 字典项
	 * @return R
	 */
	@SysLog("修改字典项")
	@PutMapping("/item")
	public R updateById(@RequestBody SysDictItem sysDictItem) {
		SysDictItem item = sysDictItemService.getOne(Wrappers.<SysDictItem>query().lambda()
				.eq(SysDictItem::getType,sysDictItem.getType())
				.ne(SysDictItem::getId,sysDictItem.getId())
				.eq(SysDictItem::getValue,sysDictItem.getValue())
				.eq(SysDictItem::getDelFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(item)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_ITEM_ADD_VALUE_EXIST));
		}
		return R.ok(sysDictItemService.updateDictItem(sysDictItem));
	}

	/**
	 * 通过id删除字典项
	 * @param id id
	 * @return R
	 */
	@SysLog("删除字典项")
	@DeleteMapping("/item/{id:\\d+}")
	public R removeDictItemById(@PathVariable Long id) {
		return sysDictItemService.removeDictItemDiy(id);
	}

	@SysLog("清除字典缓存")
	@DeleteMapping("/cache")
	@PreAuthorize("@pms.hasPermission('sys_dict_del')")
	public R clearDictCache() {
		sysDictService.clearDictCache();
		// 同步清理字典项缓存
		sysDictItemService.clearDictItemCache();
		return R.ok();
	}

	/**
	 * 返回树形字典集合
	 * @param lazy 是否是懒加载
	 * @param parentId 父节点ID
	 * @return 树形菜单
	 */
	@SysLog("返回树形字典集合")
	@GetMapping(value = "/tree")
	public R<List<Tree<Long>>> getTree(boolean lazy, Long parentId) {
		return R.ok(sysDictItemService.treeMenu(lazy, parentId));
	}

	/**
	 * @Description: 获取所有字典数据：用做导入：type,<lable,value>
	 * @Author: hgw
	 * @Date: 2022/6/22 18:19
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.Map < java.lang.String, java.util.Map < java.lang.String, java.lang.String>>>
	 **/
	@Inner
	@PostMapping("/inner/getDictToLable")
	public R<Map<String, Map<String, String>>> getDictToLable() {
		return sysDictItemService.getDictToLable();
	}

	/**
	 * @Description: 获取所有字典数据：用做导出：type,<value,lable>
	 * @Author: hgw
	 * @Date: 2022/6/22 18:20
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.Map < java.lang.String, java.util.Map < java.lang.String, java.lang.String>>>
	 **/
	@Inner
	@PostMapping("/inner/getDictToValue")
	public R<Map<String, Map<String, String>>> getDictToValue() {
		return sysDictItemService.getDictToValue();
	}

	/**
	 * @Description: 根据type和value获取字典值
	 * @Author: huyc
	 * @Date: 2022/7/1
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Inner
	@PostMapping("/inner/getLableFronValue")
	public R<String> getLableFronValue(@RequestParam String value,@RequestParam String type) {
		return sysDictItemService.getLableFronValue(value,type);
	}

	/**
	 * @Description: itemType  获取对应的字典数据
	 * @Author: hgw
	 * @Date: 2022/6/22 18:19
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.Map < java.lang.String, java.util.Map < java.lang.String, java.lang.String>>>
	 **/
	@Inner
	@PostMapping("/inner/getDictList")
	public R<List<SysDictItem>> getDictList(@RequestParam(value = "itemType", required = false) String itemType) {
		List<SysDictItem> allList = sysDictItemService.list(Wrappers.<SysDictItem>query().lambda()
				.eq(SysDictItem::getDelFlag,CommonConstants.ZERO_STRING)
				.eq(SysDictItem::getDisable,CommonConstants.ZERO_STRING));
		return new R<>(allList);
	}
}
