package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CloudVideoProcessUtil;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.manage.modules.actor.entity.Actor;
import cn.com.ctop.manage.modules.actor.entity.ActorComment;
import cn.com.ctop.manage.modules.actor.entity.ActorPhoto;
import cn.com.ctop.manage.modules.actor.entity.ActorVideo;
import cn.com.ctop.manage.modules.actor.service.IActorCommentService;
import cn.com.ctop.manage.modules.actor.service.IActorPhotoService;
import cn.com.ctop.manage.modules.actor.service.IActorService;
import cn.com.ctop.manage.modules.actor.service.IActorVideoService;
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 lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.checkerframework.checker.units.qual.C;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author jeecg-boot
 */
@RestController
@Slf4j
@RequestMapping("/ctop/actor")
public class ActorController {
    @Autowired
    private IActorService actorService;
    @Autowired
    private IActorCommentService actorCommentService;
    @Autowired
    private IActorPhotoService actorPhotoService;
    @Autowired
    private IActorVideoService actorVideoService;

    @ResponseBody
    @GetMapping("/detail")
    public Result<Actor> getDetail(@RequestParam(name = "actorId") Long actorId) {
        Result<Actor> result = new Result<>();
        Actor actor = actorService.getById(actorId);
        List<String> tags = actorCommentService.getTagsNames(actorId);
        actor.setTagNameList(tags);
        String phone = actor.getPhone();
        if (!Check.isNull(phone)) {
            String encPhone = getEncPhone(phone);
            if (!Check.isNull(encPhone)) {
                actor.setEncPhone(encPhone);
            }
        }
        result.setResult(actor);
        result.setSuccess(true);
        return result;
    }

    /**
     * 分页列表查询
     *
     * @param actor
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<Actor>> queryPageList(Actor actor,
                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                              HttpServletRequest req) {
        Result<IPage<Actor>> result = new Result<>();
        String parm = actor.getName();
        actor.setName(null);
        QueryWrapper<Actor> queryWrapper = QueryGenerator.initQueryWrapper(actor, req.getParameterMap());
        if (!Check.isNull(parm)) {
            JSONObject jsonObject = JSONObject.parseObject(parm);
            if (!Check.isNull(jsonObject)) {
                String name = jsonObject.getString("name");
                if (!Check.isNull(name)) {
                    queryWrapper.like("name", name);
                }
                Integer cityId = jsonObject.getInteger("cityId");
                if (!Check.isNull(cityId) && cityId != 0) {
                    queryWrapper.eq("actor_city_id", cityId);
                }

                JSONArray tagList = jsonObject.getJSONArray("tagList");
                if (!Check.isNull(tagList)) {
                    List<Long> tagIds = new ArrayList<>();
                    for (int i = 0; i < tagList.size(); i++) {
                        Long aLong = tagList.getLong(i);
                        tagIds.add(aLong);
                    }
                    List<Long> actorIds = actorCommentService.getActorIds(tagIds);
                    queryWrapper.in("id", actorIds);
                }
            }
        }


        queryWrapper.orderByDesc("create_time");
        Page<Actor> page = new Page<>(pageNo, pageSize);
        IPage<Actor> pageList = actorService.page(page, queryWrapper);

        List<Actor> records = pageList.getRecords();
        for (int i = 0; i < records.size(); i++) {
            Actor actor1 = records.get(i);
            Long id = actor1.getId();
            List<Long> tags = actorCommentService.getTagListBy(id);
            actor1.setTagList(tags);

            String phone = actor1.getPhone();
            if (!Check.isNull(phone)) {
                String encPhone = getEncPhone(phone);
                if (!Check.isNull(encPhone)) {
                    actor1.setEncPhone(encPhone);
                }
            }

        }

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    private String getEncPhone(String phoneNumber) {
        //截取前三位
        String beginStr = phoneNumber.substring(0, 3);
        //截取后四位
        String endStr = phoneNumber.substring(7);
        String encPhone = beginStr + "****" + endStr;
        return encPhone;


    }

    @GetMapping(value = "/photo/list")
    public Result<IPage<ActorPhoto>> queryPhotoPageList(ActorPhoto actorPhoto,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<IPage<ActorPhoto>> result = new Result<>();
        QueryWrapper<ActorPhoto> queryWrapper = QueryGenerator.initQueryWrapper(actorPhoto, req.getParameterMap());
        Page<ActorPhoto> page = new Page<>(pageNo, pageSize);
        IPage<ActorPhoto> pageList = actorPhotoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @GetMapping(value = "/comment/list")
    public Result<IPage<ActorComment>> queryCommentPageList(ActorComment actorComment,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        Result<IPage<ActorComment>> result = new Result<>();
        QueryWrapper<ActorComment> queryWrapper = QueryGenerator.initQueryWrapper(actorComment, req.getParameterMap());
        Page<ActorComment> page = new Page<>(pageNo, pageSize);
        IPage<ActorComment> pageList = actorCommentService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    @GetMapping(value = "/getCityList")
    public Result<List<JSONObject>> getCityList() {
        Result<List<JSONObject>> result = new Result<>();
        List<JSONObject> cityList = actorCommentService.getCityList();
        result.setSuccess(true);
        result.setResult(cityList);
        return result;
    }

    @GetMapping(value = "/getTagList")
    public Result<List<JSONObject>> getTagList() {
        Result<List<JSONObject>> result = new Result<>();
        List<JSONObject> cityList = actorCommentService.getTagList();
        result.setSuccess(true);
        result.setResult(cityList);
        return result;
    }


    @DeleteMapping(value = "/comment/delete")
    public Result<ActorComment> deleteComment(@RequestParam(name = "id", required = true) String id) {
        Result<ActorComment> result = new Result<>();
        ActorComment actorComment = actorCommentService.getById(id);
        if (actorComment == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = actorCommentService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }
        return result;
    }

    @DeleteMapping(value = "/video/delete")
    public Result<ActorVideo> deleteVideo(@RequestParam(name = "id", required = true) String id) {
        Result<ActorVideo> result = new Result<>();
        ActorVideo actorVideo = actorVideoService.getById(id);
        if (actorVideo == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = actorVideoService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }
        return result;
    }

    @DeleteMapping(value = "/photo/delete")
    public Result<ActorPhoto> deletePhoto(@RequestParam(name = "id", required = true) String id) {
        Result<ActorPhoto> result = new Result<>();
        ActorPhoto actorPhoto = actorPhotoService.getById(id);
        if (actorPhoto == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = actorPhotoService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }
        return result;
    }

    @PostMapping(value = "/comment/add")
    public Result<ActorComment> addComment(ActorComment actorComment) {
        Result<ActorComment> result = new Result<>();
        try {
            actorCommentService.save(actorComment);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @PostMapping(value = "/video/add")
    public Result<ActorVideo> addVideo(ActorVideo actorVideo) {
        Result<ActorVideo> result = new Result<>();
        try {
            Long actorId = actorVideo.getActorId();
            String videoUrl = actorVideo.getVideoUrl();
            if (Check.isNull(videoUrl)) {
                throw new Exception("请选择需要上传的图片");
            }
            String[] split = videoUrl.split(",");
            if (Check.isNull(split)) {
                throw new Exception("图片格式不正确");
            }
            for (int i = 0; i < split.length; i++) {
                String video = split[i];
                String newVideoUrl = null;
                if (!video.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                    newVideoUrl = KuaishouInterfaceConstant.HTTPS_PREFIX + video;
                }
                ActorVideo addActorVideo = new ActorVideo();

                String url = URLDecoder.decode(newVideoUrl).replace("https://live-1301855440.cos.ap-chongqing.myqcloud.com/", "");

                String uuid = UUID.randomUUID().toString();
                String loadImage = "cutFrame/" + uuid + ".jpg";
                String coverUrl = CloudVideoProcessUtil.videoCutPictureHandleLive(url, loadImage);


                addActorVideo.setCoverUrl(coverUrl);
                addActorVideo.setActorId(actorId);
                addActorVideo.setVideoUrl(newVideoUrl);
                actorVideoService.save(addActorVideo);
            }

            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @PostMapping(value = "/photo/add")
    public Result<ActorPhoto> addPhoto(ActorPhoto actorPhoto) {
        Result<ActorPhoto> result = new Result<>();
        try {

            Long actorId = actorPhoto.getActorId();
            String photoUrl = actorPhoto.getPhotoUrl();
            if (Check.isNull(photoUrl)) {
                throw new Exception("请选择需要上传的图片");
            }
            String[] split = photoUrl.split(",");
            if (Check.isNull(split)) {
                throw new Exception("图片格式不正确");
            }
            for (int i = 0; i < split.length; i++) {
                String photo = split[i];
                String newPhotoUrl = null;
                if (!photo.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                    newPhotoUrl = KuaishouInterfaceConstant.HTTPS_PREFIX + photo;
                }
                ActorPhoto addActorPhoto = new ActorPhoto();
                addActorPhoto.setActorId(actorId);
                addActorPhoto.setPhotoUrl(newPhotoUrl);
                actorPhotoService.save(addActorPhoto);
            }


            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500(e.getMessage());
        }
        return result;
    }

    @GetMapping(value = "/video/list")
    public Result<IPage<ActorVideo>> queryVideoPageList(ActorVideo actorVideo,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<IPage<ActorVideo>> result = new Result<>();
        QueryWrapper<ActorVideo> queryWrapper = QueryGenerator.initQueryWrapper(actorVideo, req.getParameterMap());
        Page<ActorVideo> page = new Page<>(pageNo, pageSize);
        IPage<ActorVideo> pageList = actorVideoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 添加
     *
     * @param actor
     * @return
     */
    @PostMapping(value = "/add")
    public Result<Actor> add(@RequestBody Actor actor) {
        Result<Actor> result = new Result<>();
        try {
            String coverUrl = actor.getCoverUrl();
            if (!Check.isNull(coverUrl) && !coverUrl.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                actor.setCoverUrl(KuaishouInterfaceConstant.HTTPS_PREFIX + coverUrl);
            }

            Integer actorCityId = actor.getActorCityId();
            String cityName = actorCommentService.getCityName(actorCityId);
            actor.setActorCityName(cityName);
            actorService.save(actor);
            if (null != actor.getImageUrl() && !actor.getImageUrl().isEmpty()) {
                for (String url : actor.getImageUrl()) {
                    ActorPhoto photo = new ActorPhoto();
                    photo.setActorId(actor.getId());
                    if (!Check.isNull(url) && !url.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                        photo.setPhotoUrl(KuaishouInterfaceConstant.HTTPS_PREFIX + url);
                    }
                    actorPhotoService.save(photo);
                }
            }
            if (actor.getVideoUrl() != null && !actor.getVideoUrl().isEmpty()) {
                for (String url : actor.getVideoUrl()) {
                    ActorVideo video = new ActorVideo();
                    video.setActorId(actor.getId());
                    String videoUrl = null;
                    if (!Check.isNull(url) && !url.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                        videoUrl = KuaishouInterfaceConstant.HTTPS_PREFIX + url;
                        video.setVideoUrl(KuaishouInterfaceConstant.HTTPS_PREFIX + url);
                    }
                    String newUrl = URLDecoder.decode(videoUrl).replace("https://live-1301855440.cos.ap-chongqing.myqcloud.com/", "");
                    String uuid = UUID.randomUUID().toString();
                    String loadImage = "cutFrame/" + uuid + ".jpg";
                    String videoCoverUrl = CloudVideoProcessUtil.videoCutPictureHandleLive(newUrl, loadImage);
                    video.setCoverUrl(videoCoverUrl);
                    actorVideoService.save(video);
                }
            }

            if (actor.getTagList() != null && !actor.getTagList().isEmpty()) {
                for (Long tagId : actor.getTagList()) {
                    String tagName = actorCommentService.geTagName(tagId);
                    actorCommentService.addTag(actor.getId(), tagId, tagName);
                }
            }

            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param actor
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<Actor> edit(@RequestBody Actor actor) {
        Result<Actor> result = new Result<>();

        Actor actorEntity = actorService.getById(actor.getId());
        if (actorEntity == null) {
            result.error500("未找到对应实体");
        } else {
            String coverUrl = actor.getCoverUrl();
            if (!Check.isNull(coverUrl) && !coverUrl.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                actor.setCoverUrl(KuaishouInterfaceConstant.HTTPS_PREFIX + coverUrl);
            }
            Integer actorCityId = actor.getActorCityId();
            if (!Check.isNull(actorCityId)) {
                String cityName = actorCommentService.getCityName(actorCityId);
                actor.setActorCityName(cityName);

            }
            boolean ok = actorService.updateById(actor);
            if (ok) {
                if (actor.getTagList() != null && !actor.getTagList().isEmpty()) {
                    actorCommentService.deleteTagByActorId(actor.getId());
                    for (Long tagId : actor.getTagList()) {
                        String tagName = actorCommentService.geTagName(tagId);
                        actorCommentService.addTag(actor.getId(), tagId, tagName);
                    }
                }
                result.success("修改成功!");
            }
        }
        return result;
    }

    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            actorService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }
}
