/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.user.platform.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.Category;
import com.yami.shop.bean.param.CategoryScoreConfigParam;
import com.yami.shop.bean.param.ScoreConfigParam;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.config.Constant;
import com.yami.shop.service.CategoryService;
import com.yami.shop.service.SysConfigService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;


/**
 * 积分配置管理实现
 *
 * @author lhd
 * @version 1.0.0
 * @since 2020-02-26
 */
@RestController
@RequestMapping("/user/scoreConfig")
public class ScoreConfigController {

	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private CategoryService categoryService;


	/**
	 * 获取配置信息
	 */
	@GetMapping("/info/{id}")
	@PreAuthorize("@pms.hasPermission('user:scoreSonfig:info')")
	public ResponseEntity<ScoreConfigParam> info(@PathVariable("id") String key){
		ScoreConfigParam scoreParamDb = sysConfigService.getSysConfigObject(key,ScoreConfigParam.class);
		if(Objects.isNull(scoreParamDb)){
			ScoreConfigParam scoreParam = new ScoreConfigParam();
			addCategoryConfig(scoreParam);
			return ResponseEntity.ok(scoreParam);
		}
		if(Objects.isNull(scoreParamDb) || CollectionUtils.isEmpty(scoreParamDb.getCategoryConfigs())){
			addCategoryConfig(scoreParamDb);
		}

		if(scoreParamDb.getSignInScoreString() != null) {
			List<Integer> signScore = new ArrayList<>();
			String[] scores = scoreParamDb.getSignInScoreString().split(StrUtil.COMMA);
			for (String score : scores) {
				signScore.add(Integer.valueOf(score.trim()));
			}
			scoreParamDb.setSignInScore(signScore);
		}
//		scoreParamDb.setId(config.getId());
		return ResponseEntity.ok(scoreParamDb);
	}

	private void addCategoryConfig(ScoreConfigParam scoreParam) {
		List<CategoryScoreConfigParam> params = new ArrayList<>();
		List<Category> categories = categoryService.list(new LambdaQueryWrapper<Category>()
				.le(Category::getGrade, 1)
				.eq(Category::getShopId, Constant.PLATFORM_SHOP_ID)
				.eq(Category::getParentId,0)
				.orderByAsc(Category::getSeq));
		for (Category category : categories) {
			CategoryScoreConfigParam param = new CategoryScoreConfigParam();
			param.setCategoryId(category.getCategoryId());
			param.setCategoryName(category.getCategoryName());
			param.setGetScoreLimit(1.0);
			param.setUseScoreLimit(1.0);
			params.add(param);
		}
		scoreParam.setCategoryConfigs(params);
	}


	/**
	 * 保存配置
	 */
	@SysLog("保存配置")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('user:scoreSonfig:save')")
	public ResponseEntity<Void> save(@RequestBody @Valid ScoreConfigParam scoreConfigParam){
		sysConfigService.saveOrUpdateSysConfigService(scoreConfigParam,Constant.SCORE_CONFIG);
		return ResponseEntity.ok().build();
	}

	/**
	 * 修改配置
	 */
	@SysLog("修改配置")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('user:scoreSonfig:update')")
	public ResponseEntity<Void> update(@RequestBody @Valid ScoreConfigParam scoreConfigParam){
//		SysConfig config = new SysConfig();
//		List<Integer> signInScore = scoreConfigParam.getSignInScore();
//		if(CollectionUtils.isNotEmpty(signInScore)) {
//			StringBuilder signsString = new StringBuilder();
//			for (Integer score : signInScore) {
//				signsString.append(score).append(StrUtil.COMMA);
//			}
//			signsString.deleteCharAt(signsString.length() - 1);
//			scoreConfigParam.setSignInScoreString(signsString.toString());
//			scoreConfigParam.setSignInScore(null);
//		}
////		if(Objects.equals(scoreConfigParam.getDiscountRange(),0)){
////			scoreConfigParam.setCategoryConfigs(null);
////		}else{
////			scoreConfigParam.setDiscount(null);
////		}
//		config.setRemark("积分获取比例和积分抵现规则");
//		config.setId(scoreConfigParam.getId());
//		scoreConfigParam.setId(null);
//		String paramValue = Json.toJsonString(scoreConfigParam);
//		config.setParamValue(paramValue);
//		sysConfigService.updateById(config);
//		sysConfigService.removeSysConfig(Constant.SCORE_CONFIG);
		return ResponseEntity.ok().build();
	}


}
