package cn.com.ctop.toutiao.modules.material.controller;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.StringUtils;
import cn.com.ctop.toutiao.modules.material.entity.ByteDanceCreativeWordPackage;
import cn.com.ctop.toutiao.modules.material.entity.BytedanceVideoSlogenInfo;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceCreativeWordPackageService;
import cn.com.ctop.toutiao.modules.material.service.IBytedanceVideoSlogenInfoService;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 头条视频文案信息
 * @author jeecg-boot
 * 2021-04-19
 * @version V1.0
 */
@Slf4j
@Api(tags="头条视频文案信息")
@RestController
@RequestMapping("/ctop/bytedanceVideoSlogenInfo")
public class BytedanceVideoSlogenInfoController {
	@Autowired
	private IBytedanceVideoSlogenInfoService bytedanceVideoSlogenInfoService;
	@Autowired
	private IByteDanceCreativeWordPackageService byteDanceGeneralCopywriterService;
	/**
	  * 分页列表查询
	 * @param slogenInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-分页列表查询", notes="头条视频文案信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BytedanceVideoSlogenInfo>> queryPageList(BytedanceVideoSlogenInfo slogenInfo,
																 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																 HttpServletRequest req) {
		Result<IPage<BytedanceVideoSlogenInfo>> result = new Result<>();
		slogenInfo.setStatus(1);
		QueryWrapper<BytedanceVideoSlogenInfo> queryWrapper = QueryGenerator.initQueryWrapper(slogenInfo, req.getParameterMap());
		Page<BytedanceVideoSlogenInfo> page = new Page<>(pageNo, pageSize);
		IPage<BytedanceVideoSlogenInfo> pageList = bytedanceVideoSlogenInfoService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	/**
	  *   添加
	 * @param slogenInfo
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-添加", notes="头条视频文案信息-添加")
	@PostMapping(value = "/add")
	public Result<BytedanceVideoSlogenInfo> add(@RequestBody BytedanceVideoSlogenInfo slogenInfo) {
		Result<BytedanceVideoSlogenInfo> result = new Result<>();
		try {
			bytedanceVideoSlogenInfoService.save(slogenInfo);
			result.success("添加成功！");
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}
	}

	/**
	 *  编辑
	 * @param slogenInfo 文案信息
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-编辑", notes="头条视频文案信息-编辑")
	@PostMapping(value = "/edit")
	public Result<BytedanceVideoSlogenInfo> edit(@RequestBody BytedanceVideoSlogenInfo slogenInfo) {
		Result<BytedanceVideoSlogenInfo> result = new Result<>();
		try{
			BytedanceVideoSlogenInfo bytedanceVideoSlogenInfoEntity = bytedanceVideoSlogenInfoService.getById(slogenInfo.getId());
			if(bytedanceVideoSlogenInfoEntity==null) {
				result.error500("未找到对应实体");
				return result;
			}
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			slogenInfo.setUpdateBy(user.getId());
			slogenInfo.setUpdateTime(new Date());

			String title = slogenInfo.getSlogan();
			title = title.trim().replaceAll("[\\{]{2,}", "{");
			title = title.trim().replaceAll("[\\}]{2,}", "}");
			slogenInfo.setSlogan(title);


			String reg = "\\{[\\u4e00-\\u9fa5\\-]{2,6}\\}";
			Pattern pattern = Pattern.compile(reg);
			Matcher matcher = pattern.matcher(title);
			JSONArray creativeWordIdsArray = new JSONArray();

			int len = StringUtils.lengthAsSlogan(title);
			int left = title.indexOf("{");
			int right = title.indexOf("}");
			if (left >= 0 || right >= 0) {
				int times = 0;
				while (matcher.find()) { //此处find()每次被调用后，会偏移到下一个匹配
					times++;
					if (times >= 3) {
						result.error500("动态词包不合法，词包数量超过2个");
						return result;
					}
					String matchStr = matcher.group();//获取当前匹配的值
					title = title.replace(matchStr,"");
					ByteDanceCreativeWordPackage creativeWordPackage = byteDanceGeneralCopywriterService.selectCreativeWordPackageByName(matchStr.substring(1, matchStr.length() - 1));
					if (Check.isNull(creativeWordPackage)) {
						return result.error500("动态词包不合法，词包不存在或者含有单独的非词包大括号");
					}
					creativeWordIdsArray.add(creativeWordPackage.getCreativeWordId());
					len = len - (right - left) + creativeWordPackage.getMaxWordLen();
					left = title.indexOf("{");
					right = title.indexOf("}");
				}
				if(title.contains("{") || title.contains("}")){
					return result.error500("大括号单独出现或大括号中内容不合法");
				}
				slogenInfo.setCreativeWordIds(creativeWordIdsArray.toJSONString());
			}
			//校验标题长度，长度小于5和大于30的全部过滤
			if (len < 5 || len > 30) {
				return result.error500("文案长度不合法，小于5或大于30");
			}

			bytedanceVideoSlogenInfoService.updateById(slogenInfo);
			result.setCode(0);
			result.setMessage("修改成功!");
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}
	}

	/**
	 *   通过id删除
	 * @param id
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-通过id删除", notes="头条视频文案信息-通过id删除")
	@PostMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id") String id) {
		try {
			BytedanceVideoSlogenInfo slogenInfo = bytedanceVideoSlogenInfoService.getById(id);
			if(null == slogenInfo||slogenInfo.getStatus() == 0){
				return Result.ok("此文案不存在或者已经被删除");
			}
			slogenInfo.setStatus(0);
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			slogenInfo.setUpdateTime(new Date());
			slogenInfo.setCreateBy(user.getId());
			bytedanceVideoSlogenInfoService.updateById(slogenInfo);
			return Result.ok("删除成功!");
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
	}

	/**
	 * 通过id查询
	 * @param id
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-通过id查询", notes="头条视频文案信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BytedanceVideoSlogenInfo> queryById(@RequestParam(name="id") String id) {
		Result<BytedanceVideoSlogenInfo> result = new Result<>();
		BytedanceVideoSlogenInfo bytedanceVideoSlogenInfo = bytedanceVideoSlogenInfoService.getById(id);
		if(bytedanceVideoSlogenInfo==null) {
			result.error500("未找到对应实体");
			return result;
		}
		result.setResult(bytedanceVideoSlogenInfo);
		result.setSuccess(true);
		return result;
	}
}
