package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeUserDynamics;
import shop.alien.entity.store.vo.LifePinglunVo;
import shop.alien.entity.store.vo.LifeUserDynamicsVo;
import shop.alien.store.service.LifeUserDynamicsService;
import shop.alien.util.common.ListToPage;
import shop.alien.util.common.netease.ImageCheckUtil;
import shop.alien.util.common.netease.TextCheckUtil;
import shop.alien.util.common.safe.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户动态
 */
@Api(tags = {"一期-用户动态"})
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/userDynamics")
@RequiredArgsConstructor
public class LifeUserDynamicsController {

    private final LifeUserDynamicsService lifeUserDynamicsService;

    @Autowired
    private TextModerationUtil textModerationUtil;

    @Autowired
    private ImageModerationUtil imageModerationUtil;

    @ApiOperation("社区列表")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "分页页数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "myself", value = "0-全部 1-自己的动态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "1-动态 2-商家社区 3-官方社区", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isfollowed", value = "0-全部, 1-关注用户的动态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phoneId", value = "用户唯一标识", dataType = "String", paramType = "query")})
    @GetMapping("/getUserDynamics")
    public R<IPage<LifeUserDynamicsVo>> getUserDynamics(@RequestParam(defaultValue = "1") Integer page,
                                                        @RequestParam(defaultValue = "10") Integer size,
                                                        @RequestParam(required = false) String myself,
                                                        @RequestParam(required = false) String type,
                                                        @RequestParam(required = false) String isfollowed,
                                                        @RequestParam(required = false) String phoneId) {
        log.info("LifeUserDynamicsController.getUserDynamics?page={}&size={}&myself={}&type={}&isfollowed={}&phoneId={}", page, size, myself, type, isfollowed, phoneId);
        List<LifeUserDynamicsVo> stores = lifeUserDynamicsService.getUserDynamics(myself, type, isfollowed, phoneId);
        return R.data(ListToPage.setPage(stores, page, size));
    }

    @ApiOperation("好友动态列表")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({@ApiImplicitParam(name = "phoneId", value = "用户唯一标识", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "分页页数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "类型，1:用户，2:商户", dataType = "String", paramType = "query")})
    @GetMapping("/getUserDynamicsList")
    public R<Map<String, Object>> getUserDynamicsList(@RequestParam(required = false) String myselfPhoneId,
                                                      @RequestParam(required = false) String phoneId,
                                                      @RequestParam(required = false, defaultValue = "1") String type,
                                                      @RequestParam(required = false, defaultValue = "1") Integer page,
                                                      @RequestParam(defaultValue = "10") Integer size) {
        return R.data(lifeUserDynamicsService.getUserDynamics(myselfPhoneId, phoneId, type, page, size));
    }


    @ApiOperation(value = "发布动态社区", notes = "0:成功, 1:失败, 2:文本内容异常, 3:图片内容异常")
    @ApiOperationSupport(order = 2)
    @PostMapping("/addOrUpdate")
    public R<Integer> addOrUpdate(@RequestBody LifeUserDynamics lifeUserDynamics) {
        log.info("LifeUserDynamicsController.addOrUpdate?store={}", lifeUserDynamics.toString());
        /*Map<String, String> checkText = TextCheckUtil.check(lifeUserDynamics.getContext());
        if (null == checkText || checkText.get("result").equals("1")) {
            return R.data(2);
        }
        Map<String, String> checkImage = ImageCheckUtil.check(lifeUserDynamics.getImagePath(), 1);
        if (checkImage != null && checkImage.get("result").equals("1")) {
            return R.data(3);
        }*/
        try {

            List<String> servicesList = Lists.newArrayList();
            servicesList.add(TextReviewServiceEnum.COMMENT_DETECTION_PRO.getService());
            servicesList.add(TextReviewServiceEnum.LLM_QUERY_MODERATION.getService());
            TextModerationResultVO textCheckResult = textModerationUtil.invokeFunction(lifeUserDynamics.getContext(), servicesList);
            if ("high".equals(textCheckResult.getRiskLevel())) {
                return R.data(2);
            }

            List<String> imgServicesList = Lists.newArrayList();
            imgServicesList.add(ImageReviewServiceEnum.TONALITY_IMPROVE.getService());
            imgServicesList.add(ImageReviewServiceEnum.AIGC_CHECK.getService());
            ImageModerationResultVO response = imageModerationUtil.productPublishCheck(lifeUserDynamics.getImagePath(),imgServicesList);
            if ("high".equals(response.getRiskLevel())) {
                return R.data(3);
            }

            int cnt = lifeUserDynamicsService.addOrUpdateStore(lifeUserDynamics);
            if (cnt == 0) {
                return R.data(1);
            }
        } catch (Exception e) {
            log.error("LifeUserDynamicsController.addOrUpdate ERROR Msg={}", e.getMessage());
            return R.data(1);
        }
        return R.data(0);
    }

    @ApiOperation("删除动态社区")
    @ApiOperationSupport(order = 3)
    @GetMapping("/deleteDynamicsById")
    public R<Boolean> deleteDynamicsById(Integer id) {
        log.info("LifeUserDynamicsController.deleteDynamicsById?id={}", id);
        try {
            lifeUserDynamicsService.deleteDynamicsById(id);
            return R.success("删除成功");
        } catch (Exception e) {
            log.error("LifeUserDynamicsController.deleteDynamicsById ERROR Msg={}", e.getMessage());
            return R.fail("删除失败");
        }
    }

    @GetMapping("/getUserDynamicsCommentById")
    public R<PageInfo> getUserDynamicsCommentById(@RequestParam(defaultValue = "1") int page,
                                                  @RequestParam(defaultValue = "10") int size,
                                                  @RequestParam(required = false) String id) {
        log.info("LifeUserDynamicsController.getUserDynamicsCommentById?page={},size={},id={}", page, size, id);
        Map<String, List<LifePinglunVo>> mapList = lifeUserDynamicsService.getUserDynamicsCommentById(id);
        List<Map<String, Object>> result = new ArrayList<>();
        int totalPinglun = 0;
        for (Map.Entry<String, List<LifePinglunVo>> entry : mapList.entrySet()) {
            String year = entry.getKey();
            List<LifePinglunVo> records = entry.getValue();
            Map<String, Object> newMap = new HashMap<>();
            newMap.put("huifuId", year);
            newMap.put("records", records);
            newMap.put("pinglunCount", records.size());
            totalPinglun = totalPinglun + records.size();
            result.add(newMap);
        }
        PageHelper.startPage(page, size);
        return R.data(new PageInfo<>(result));
    }

    @PostMapping("addLiulanShu")
    public int dianzan(String id) {
        log.info("LifeUserDynamicsController.addLiulanShu?id={}", id);
        return lifeUserDynamicsService.addLiulanCount(id);
    }

    @ApiOperation("草稿列表")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "分页页数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "phoneId", value = "用户唯一标识", dataType = "String", paramType = "query")})
    @GetMapping("/getUserDraftDynamics")
    public R<IPage<LifeUserDynamics>> getUserDraftDynamics(@RequestParam(defaultValue = "1") Integer page,
                                                        @RequestParam(defaultValue = "10") Integer size,
                                                        @RequestParam(required = false) String phoneId) {
        log.info("LifeUserDynamicsController.getUserDraftDynamics?page={}&size={}&phoneId={}", page, size, phoneId);
        List<LifeUserDynamics> stores = lifeUserDynamicsService.getUserDraftDynamics(phoneId);
        return R.data(ListToPage.setPage(stores, page, size));
    }

    @ApiOperation("点赞列表")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getDianZanList")
    public R<List<LifeUserDynamicsVo>> getDianZanList(@RequestParam(required = false) String phoneId) {
        return R.data(lifeUserDynamicsService.getDianZanList(phoneId));
    }
}