package ctop.bytedance.ad.advertise.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.api.ICommonService;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import ctop.bytedance.ad.advertise.entity.ByteDanceCreativeWordPackage;
import ctop.bytedance.ad.advertise.entity.BytedanceVideoSlogenInfo;
import ctop.bytedance.ad.advertise.service.IByteDanceGeneralCopywriterService;
import ctop.bytedance.ad.advertise.service.IBytedanceVideoSlogenInfoService;
import ctop.bytedance.ad.common.entity.MaterialInfo;
import ctop.bytedance.ad.common.service.IMaterialInfoService;
import ctop.bytedance.ad.common.utils.Check;
import ctop.bytedance.ad.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 头条视频文案信息
 * @author jeecg-boot
 * 2021-04-19
 * @version V1.0
 */
@Slf4j
@Api(tags="头条视频文案信息")
@RestController
@RequestMapping("/bytedance/ad/ctop/bytedanceVideoSlogenInfo")
public class BytedanceVideoSlogenInfoController {
	@Autowired
	private IBytedanceVideoSlogenInfoService bytedanceVideoSlogenInfoService;
	@Autowired
	private IMaterialInfoService materialInfoService;
	@Reference
	private ICommonService commonService;

	@Autowired
	private IByteDanceGeneralCopywriterService 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);		//默认不传为所有，传了1是正常，传0是已删除
		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;
	}

	@ApiOperation(value="指定文案报表数据展示", notes="指定文案报表数据展示")
	@GetMapping(value = "/queryPageListByText")
	public Result queryPageListByText(@RequestParam("userId") String userId,
									  @RequestParam(value = "projectId",defaultValue = "") String projectId,
									  @RequestParam(value = "keyWord",defaultValue = "") String keyWord,
									  @RequestParam(value = "startTime",defaultValue = "") String startTime,
									  @RequestParam(value = "endTime",defaultValue = "") String endTime,
									  @RequestParam(value = "pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(value = "pageSize", defaultValue="10") Integer pageSize,
									  @RequestParam(value = "status",required = false) Integer status
									) {
		try {
			//查询用户角色
			String roleCode = commonService.getRoleCodeByUserId(userId);
			if (Check.isNull(roleCode)){
				return Result.errorMsg("请输入正确的用户id。");
			}
			//角色为 管理员并且projectId是空表示：全量查询
			if ("admin".equals(roleCode) && Check.isNull(projectId)) {
				projectId = "admin";	//传递projectId为admin
			}
			return bytedanceVideoSlogenInfoService.getVideoSlogenReport(userId, projectId,keyWord,status, startTime,endTime,pageNo,pageSize);
		}catch (Exception e){
			log.error("指定文案-获取指定文案维度创意报表数据异常",e);
			return Result.error("请求失败，请联系开发人员!");
		}
	}

	/**
	  *   添加
	 * @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
	 * @param
	 * @param
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-批量添加", notes="头条视频文案信息-批量添加")
	@PostMapping(value = "/addList")
	public Result<BytedanceVideoSlogenInfo> addList(@RequestBody MaterialInfo materialInfo) {
		Result<BytedanceVideoSlogenInfo> result = new Result<>();
		try {
			String userId = materialInfo.getUserId();
			JSONArray slogenArray = materialInfo.getSlogans();
			for (int i = 0;i<slogenArray.size();i++) {
				JSONObject slogenInfo = slogenArray.getJSONObject(i);
				String title = slogenInfo.getString("title");
				title = title.trim().replaceAll("[\\{]{2,}","{");
				title = title.trim().replaceAll("[\\}]{2,}","}");
                slogenInfo.put("title",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){
							return  Result.errorMsg("动态词包不合法，词包数量超过2个");
						}
						String matchStr = matcher.group();//获取当前匹配的值
						title = title.replace(matchStr,"");

						ByteDanceCreativeWordPackage creativeWordPackage = byteDanceGeneralCopywriterService.selectCreativeWordPackageByName(matchStr.substring(1,matchStr.length()-1));
						if(Check.isNull(creativeWordPackage)){
							return  Result.errorMsg("动态词包不合法，词包不存在或者含有单独的非词包大括号");
						}
						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.put("creative_word_ids",creativeWordIdsArray.toJSONString());
				}
				//校验标题长度，长度小于5和大于30的全部过滤
				if(len<5 || len>30){
					return result.error500("文案长度不合法，小于5或大于30");
				}
			}

			JSONArray materialIds = materialInfo.getMaterialIds();
			for(int i=0;i<materialIds.size();i++){
				MaterialInfo materialInfo2 = materialInfoService.getById(materialIds.get(i).toString());
				String videoCode = materialInfo2.getCode();
				Long projectId = materialInfo2.getProjectId();
				bytedanceVideoSlogenInfoService.insertSlogans(projectId,videoCode,slogenArray,userId);
			}
			result.success("添加成功！");
			result.setCode(0);
			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{
			List<BytedanceVideoSlogenInfo> videoSlogenInfoList = bytedanceVideoSlogenInfoService.getVideoSlogenBySlogenAndProjectId(slogenInfo.getSlogan(),slogenInfo.getProjectId());
		if(videoSlogenInfoList==null) {
			return result.error500("未找到对应实体");
		}


		String title = slogenInfo.getNewSlogan();
		title = title.trim().replaceAll("[\\{]{2,}", "{");
		title = title.trim().replaceAll("[\\}]{2,}", "}");
		slogenInfo.setNewSlogan(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) {
					return result.error500("动态词包不合法，词包数量超过2个");
				}
				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("文案含有词包特殊字符，请检查");
			}
		}
		//校验标题长度，长度小于5和大于30的全部过滤
		if (len < 5 || len > 30) {
			return result.error500("文案长度不合法，小于5或大于30");
		}

			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			for (BytedanceVideoSlogenInfo videoSlogenInfo:videoSlogenInfoList
				 ) {
				videoSlogenInfo.setSlogan(slogenInfo.getNewSlogan());
				videoSlogenInfo.setUpdateBy(user.getId());
				videoSlogenInfo.setUpdateTime(new Date());
				videoSlogenInfo.setCreativeWordIds(creativeWordIdsArray.toJSONString());
			}

		boolean ok = bytedanceVideoSlogenInfoService.updateBatchById(videoSlogenInfoList);
			if(ok) {
				result.success("修改成功!");
				result.setCode(0);
			}
		return result;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}
	}

	/**
	 *   通过id删除
	 * @param id
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-通过id删除", notes="头条视频文案信息-通过id删除")
	@DeleteMapping(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
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-通过id删除", notes="头条视频文案信息-通过id删除")
	@DeleteMapping(value = "/deleteBySlogenAndProjectId")
	public Result<?> deleteBySlogenAndProjectId(@RequestParam(name="slogan") String slogan, @RequestParam(name="projectId") Long projectId) {
		try {
			Result result = new Result();
			List<BytedanceVideoSlogenInfo> videoSlogenInfoList = bytedanceVideoSlogenInfoService.getVideoSlogenBySlogenAndProjectId(slogan,projectId);
			if(Check.isNull(videoSlogenInfoList)) {
				return Result.ok("此文案不存在或者已经被删除");
			}
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			videoSlogenInfoList.forEach(videoSlogenInfo->{
				videoSlogenInfo.setStatus(0);
				videoSlogenInfo.setUpdateTime(new Date());
				videoSlogenInfo.setCreateBy(user.getId());});

			boolean ok = bytedanceVideoSlogenInfoService.updateBatchById(videoSlogenInfoList);
			if(ok) {
				result.success("删除成功!");
				result.setCode(0);
			}
			return result;
		} 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;
	}

	/**
	 * 通过slogen和projectId查询
	 * @param
	 * @return
	 */
	@ApiOperation(value="头条视频文案信息-通过文案内容和项目id查询", notes="头条视频文案信息-通过文案内容和项目id查询")
	@GetMapping(value = "/queryBySlogenAndProjectId")
	public Result<BytedanceVideoSlogenInfo> queryBySlogenAndProjectId(@RequestParam(name="slogan") String slogan, @RequestParam(name="projectId") Long projectId) {

		Result<BytedanceVideoSlogenInfo> result = new Result<>();
		List<BytedanceVideoSlogenInfo> videoSlogenInfoList = bytedanceVideoSlogenInfoService.getVideoSlogenBySlogenAndProjectId(slogan,projectId);
		if(Check.isNull(videoSlogenInfoList)) {
			result.error500("未找到对应实体");
			return result;
		}
        List<String> materialNameArray = new ArrayList<>();
        videoSlogenInfoList.forEach(videoSlogenInfo->materialNameArray.add(videoSlogenInfo.getMaterialName()));
        BytedanceVideoSlogenInfo bytedanceVideoSlogenInfo = videoSlogenInfoList.get(0);
        bytedanceVideoSlogenInfo.setMaterialNameArray(materialNameArray);
		result.setResult(bytedanceVideoSlogenInfo);
		result.setSuccess(true);
		return result;
	}
}
