package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.annotation.TrackEvent;
import shop.alien.store.service.LifeUserDynamicsService;
import shop.alien.store.util.ai.AiContentModerationUtil;
import shop.alien.util.common.ListToPage;

import java.util.*;

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

    private final LifeUserDynamicsService lifeUserDynamicsService;

    private final AiContentModerationUtil aiContentModerationUtil;

    @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));
    }

    @TrackEvent(
            eventType = "POST_PUBLISH",
            eventCategory = "INTERACTION",
            storeId = "",
            targetType = "POST"
    )

    @ApiOperation(value = "发布动态社区", notes = "0:发布失败, -1:文本内容异常, 其他:动态id")
    @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 {
            // 与 saveCommonRating 一致：AiContentModerationUtil（ai.service.moderate-url），仅校验正文；配图由前端审核
            AiContentModerationUtil.AuditResult contentAuditResult =
                    aiContentModerationUtil.auditContent(lifeUserDynamics.getContext(), null);
            if (!contentAuditResult.isPassed()) {
                log.warn("发布动态文本审核未通过: {}", contentAuditResult.getFailureReason());
                return R.data(-1);
            }
            // 审核通过（含无正文：moderate 侧跳过请求，视为通过）→ 落库审核状态为「审核完成」
            lifeUserDynamics.setCheckFlag(2);
            lifeUserDynamics.setReason(null);
            lifeUserDynamics.setUpdatedTime(new java.util.Date());
            int cnt = lifeUserDynamicsService.addOrUpdateStore(lifeUserDynamics);
            if (cnt == 0) {
                return R.data(0);
            }
            return R.data(lifeUserDynamics.getId());
        } catch (Exception ex) {
            log.error("LifeUserDynamicsController.addOrUpdate ERROR Msg={}", ex.getMessage());
            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 R dianzan(String id) {
        log.info("LifeUserDynamicsController.addLiulanShu?id={}", id);
        if (lifeUserDynamicsService.addLiulanCount(id) == 0){
            return R.fail("操作失败");
        }
        return R.success("操作成功");
    }

    @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));
    }

    @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 = "userName", value = "昵称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "user-用户 store-商户", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dynamicsType", value = "1-图片 2-视频", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "releaseStartTime", value = "发布开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "releaseEndTime", value = "发布结束时间", dataType = "String", paramType = "query")})
    @GetMapping("/getDynamicsList")
    public R<IPage<LifeUserDynamicsVo>> getDynamicsList(@RequestParam(defaultValue = "1") Integer pageNum,
                                                        @RequestParam(defaultValue = "10") Integer pageSize,
                                                        @RequestParam(required = false) String userName,
                                                        @RequestParam(required = false) String storeName,
                                                        @RequestParam(required = false) String userType,
                                                        @RequestParam(defaultValue = "0",required = false) Integer dynamicsType,
                                                        @RequestParam(required = false) String releaseStartTime,
                                                        @RequestParam(required = false) String releaseEndTime) {
        log.info("LifeUserDynamicsController.getDynamicsList?page={}&size={}&nickName={}&userType={}&dynamicsType={}", pageNum, pageSize, userName, userType, dynamicsType);
        List<LifeUserDynamicsVo> stores = lifeUserDynamicsService.getDynamicsList(pageNum, pageSize, userName, userType, dynamicsType, releaseStartTime, releaseEndTime, storeName);
        return R.data(ListToPage.setPage(stores, pageNum, pageSize));
    }

    @ApiOperation("门店动态列表")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storePhone", value = "门店账号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "user-用户 store-商户", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "loginPhone", value = "当前登录人", dataType = "String", paramType = "query")
    })
    @GetMapping("/getStoreDynamicsList")
    public R<List<LifeUserDynamicsVo>> getStoreDynamicsList(
                                                        @RequestParam(required = false) String storePhone,
                                                        @RequestParam(required = false) String userType,
                                                        @RequestParam(required = false) String loginPhone) {
        log.info("LifeUserDynamicsController.getStoreDynamicsList?storePhone={}&userType={}&loginPhone={}", storePhone, userType, loginPhone);
        List<LifeUserDynamicsVo> stores = lifeUserDynamicsService.getStoreUserDynamics(storePhone, userType, loginPhone);
        return R.data(stores);
    }


    @ApiOperation("置顶/取消功能")
    @ApiOperationSupport(order = 2)
    @PostMapping("setTopStatus")
    public R setTopStatus(@RequestBody() LifeUserDynamicsVo lifeUserDynamicsVo) {
        log.info("LifeUserDynamicsController.setTopStatus?id={}，topStatus={}", lifeUserDynamicsVo.getId(), lifeUserDynamicsVo.getTopStatus());
        if (lifeUserDynamicsService.setTopStatus(lifeUserDynamicsVo) == 0){
            return R.fail("操作失败");
        }
        return R.success("操作成功");
    }

    @ApiOperation("启用/禁用功能")
    @ApiOperationSupport(order = 2)
    @PostMapping("setEnableStatus")
    public R setEnableStatus(@RequestBody() LifeUserDynamicsVo lifeUserDynamicsVo) {
        log.info("LifeUserDynamicsController.setEnableStatus?id={}，topStatus={}", lifeUserDynamicsVo.getId(), lifeUserDynamicsVo.getEnableStatus());
        if (lifeUserDynamicsService.enableStatus(lifeUserDynamicsVo) == 0){
            return R.fail("操作失败");
        }
        return R.success("操作成功");
    }

    @ApiOperation("查看动态详情")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "动态ID", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/getDynamicsDetail")
    public R<LifeUserDynamicsVo> getDynamicsDetail(@RequestParam() Integer id) {
        log.info("LifeUserDynamicsController.getDynamicsDetail?id={}", id);
        LifeUserDynamicsVo lifeUserDynamicsVo = lifeUserDynamicsService.getDynamicsDetail(id);
        return R.data(lifeUserDynamicsVo);
    }

    /**
     * 动态被转发次数+1
     * @param id 动态id
     * @return 操作结果
     */
    @TrackEvent(
            eventType = "POST_REPOST",
            eventCategory = "INTERACTION",
            storeId = "",
            targetId = "#{#id}",
            targetType = "POST"
    )
    @ApiOperation("动态被转发次数+1")
    @ApiOperationSupport(order = 9)
    @GetMapping("addTransferCount")
    public R addTransferCount(String id) {
        log.info("LifeUserDynamicsController.addTransferCount?id={}", id);
        if (lifeUserDynamicsService.addTransferCount(id) == 0){
            return R.fail("操作失败");
        }
        return R.success("操作成功");
    }
}