package com.ycwl.basic.service.mobile.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycwl.basic.biz.OrderBiz;
import com.ycwl.basic.biz.TemplateBiz;
import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.mapper.*;
import com.ycwl.basic.model.jwt.JwtInfo;
import com.ycwl.basic.model.mobile.order.IsBuyRespVO;
import com.ycwl.basic.model.mobile.scenic.ScenicAppVO;
import com.ycwl.basic.model.mobile.scenic.ScenicDeviceCountVO;
import com.ycwl.basic.model.mobile.scenic.account.ScenicLoginReq;
import com.ycwl.basic.model.mobile.scenic.account.ScenicLoginRespVO;
import com.ycwl.basic.model.mobile.scenic.content.ContentPageVO;
import com.ycwl.basic.model.pc.device.resp.DeviceRespVO;
import com.ycwl.basic.model.pc.face.resp.FaceRespVO;
import com.ycwl.basic.model.pc.scenic.entity.ScenicAccountEntity;
import com.ycwl.basic.model.pc.scenic.entity.ScenicConfigEntity;
import com.ycwl.basic.model.pc.scenic.req.ScenicReqQuery;
import com.ycwl.basic.model.pc.scenic.resp.ScenicRespVO;
import com.ycwl.basic.model.pc.source.entity.SourceEntity;
import com.ycwl.basic.model.pc.source.req.SourceReqQuery;
import com.ycwl.basic.model.pc.source.resp.SourceRespVO;
import com.ycwl.basic.model.pc.task.entity.TaskEntity;
import com.ycwl.basic.model.pc.video.entity.MemberVideoEntity;
import com.ycwl.basic.model.pc.video.entity.VideoEntity;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.repository.VideoRepository;
import com.ycwl.basic.repository.VideoTaskRepository;
import com.ycwl.basic.service.mobile.AppScenicService;
import com.ycwl.basic.service.pc.SourceService;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：longbinbin
 * @Date：2024/12/6 10:23
 */
@Slf4j
@Service
public class AppScenicServiceImpl implements AppScenicService {

    @Autowired
    private ScenicMapper scenicMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private FaceMapper faceMapper;
    @Autowired
    private SourceMapper sourceMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
    private ScenicAccountMapper scenicAccountMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private OrderBiz orderBiz;
    @Autowired
    private ScenicRepository scenicRepository;
    @Autowired
    private TemplateBiz templateBiz;
    @Autowired
    private VideoTaskRepository videoTaskRepository;
    @Autowired
    private VideoRepository videoRepository;
    @Autowired
    private SourceService sourceService;

    @Override
    public ApiResponse<PageInfo<ScenicAppVO>> pageQuery(ScenicReqQuery scenicReqQuery) {
        PageHelper.startPage(scenicReqQuery.getPageNum(), scenicReqQuery.getPageSize());
        List<ScenicAppVO> list = scenicMapper.appList(scenicReqQuery);
        PageInfo<ScenicAppVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse<ScenicDeviceCountVO> deviceCountByScenicId(Long scenicId) {
        JwtInfo worker = JwtTokenUtil.getWorker();
        ScenicDeviceCountVO scenicDeviceCountVO = deviceMapper.deviceCountByScenicId(scenicId, worker.getUserId());
        return ApiResponse.success(scenicDeviceCountVO);
    }

    @Override
    public ApiResponse<ScenicRespVO> getDetails(Long id) {
        ScenicRespVO scenicRespVO = scenicMapper.getAppById(id);
        ScenicDeviceCountVO scenicDeviceCountVO = deviceMapper.deviceCountByScenicId(id, -1L);
        scenicRespVO.setLensNum(scenicDeviceCountVO.getTotalDeviceCount());
        return ApiResponse.success(scenicRespVO);
    }

    @Override
    public List<ContentPageVO> faceContentList(Long faceId) {
        FaceRespVO faceRespVO = faceMapper.getById(faceId);
        Long userId = faceRespVO.getMemberId();
        if (faceRespVO == null) {
            return Collections.emptyList();
        }
        List<ContentPageVO> contentList = templateMapper.listFor(faceRespVO.getScenicId());
        contentList.forEach(contentPageVO -> {
            List<MemberVideoEntity> memberVideoEntityList = videoMapper.userFaceTemplateVideo(userId, faceId, contentPageVO.getTemplateId());
            contentPageVO.setGoodsType(0);
            contentPageVO.setContentType(1);
            if (!memberVideoEntityList.isEmpty()) {
                contentPageVO.setIsBuy(memberVideoEntityList.get(0).getIsBuy());
                contentPageVO.setContentId(memberVideoEntityList.get(0).getVideoId());
                VideoEntity video = videoRepository.getVideo(contentPageVO.getContentId());
                if (video != null) {
                    contentPageVO.setDuration(video.getDuration());
                    contentPageVO.setLockType(-1);
                } else {
                    TaskEntity taskById = videoTaskRepository.getTaskById(memberVideoEntityList.get(0).getTaskId());
                    if (taskById == null) {
                        contentPageVO.setLockType(0);
                    } else if (taskById.getStatus() == 3) {
                        contentPageVO.setLockType(2);
                    } else {
                        contentPageVO.setLockType(0);
                    }
                    contentPageVO.setContentType(0);
                }
            } else {
                contentPageVO.setContentType(0);
                boolean canGenerate = templateBiz.determineTemplateCanGenerate(contentPageVO.getTemplateId(), faceId);
                if (canGenerate) {
                    contentPageVO.setLockType(0);
                } else {
                    contentPageVO.setLockType(1);
                }
            }
        });

        SourceReqQuery sourceReqQuery = new SourceReqQuery();
        sourceReqQuery.setScenicId(faceRespVO.getScenicId());
        sourceReqQuery.setFaceId(faceId);
        sourceReqQuery.setMemberId(userId);
        //查询源素材
        List<SourceRespVO> sourceList = sourceMapper.queryByRelation(sourceReqQuery);
        ContentPageVO sourceVideoContent = new ContentPageVO();
        ContentPageVO sourceImageContent = new ContentPageVO();
        sourceVideoContent.setName("录像集");
        sourceImageContent.setName("照片集");
        sourceVideoContent.setScenicId(faceRespVO.getScenicId());
        sourceImageContent.setScenicId(faceRespVO.getScenicId());
        sourceVideoContent.setGoodsType(1);
        sourceImageContent.setGoodsType(2);
        sourceVideoContent.setContentType(2);
        sourceImageContent.setContentType(2);
        sourceVideoContent.setLockType(-1);
        sourceImageContent.setLockType(-1);
        ScenicConfigEntity scenicConfig = scenicRepository.getScenicConfig(faceRespVO.getScenicId());
        if (!Integer.valueOf(1).equals(scenicConfig.getDisableSourceImage())) {
            IsBuyRespVO isBuyRespVO = orderBiz.isBuy(userId, faceRespVO.getScenicId(), 2, faceId);
            sourceImageContent.setSourceType(isBuyRespVO.getGoodsType());
            sourceImageContent.setContentId(isBuyRespVO.getGoodsId());
            if (isBuyRespVO.isBuy()) {
                sourceImageContent.setIsBuy(1);
            } else {
                sourceImageContent.setIsBuy(0);
            }
            List<SourceEntity> sourceEntities = sourceMapper.listImageByFaceRelation(faceRespVO.getMemberId(), faceId);
            if (!sourceEntities.isEmpty()) {
                sourceImageContent.setLockType(-1);
            } else {
                sourceImageContent.setLockType(1);
            }
            contentList.add(sourceImageContent);
        }
        if (!Integer.valueOf(1).equals(scenicConfig.getDisableSourceVideo())) {
            IsBuyRespVO isBuyRespVO = orderBiz.isBuy(userId, faceRespVO.getScenicId(), 1, faceId);
            sourceVideoContent.setSourceType(isBuyRespVO.getGoodsType());
            sourceVideoContent.setContentId(isBuyRespVO.getGoodsId());
            if (isBuyRespVO.isBuy()) {
                sourceVideoContent.setIsBuy(1);
            } else {
                sourceVideoContent.setIsBuy(0);
            }
            List<SourceEntity> sourceEntities = sourceMapper.listVideoByFaceRelation(faceRespVO.getMemberId(), faceId);
            if (!sourceEntities.isEmpty()) {
                sourceVideoContent.setLockType(-1);
            } else {
                sourceVideoContent.setLockType(1);
            }
            contentList.add(sourceVideoContent);
        }
        sourceList.stream().collect(Collectors.groupingBy(SourceRespVO::getType)).forEach((type, list) -> {
            if (type == 1) {
                sourceVideoContent.setSourceType(1);
                sourceVideoContent.setLockType(-1);
                sourceVideoContent.setTemplateCoverUrl(list.get(0).getUrl());
            } else {
                sourceImageContent.setSourceType(2);
                sourceImageContent.setLockType(-1);
                sourceImageContent.setTemplateCoverUrl(list.get(0).getUrl());
            }
        });

        return contentList;
    }

    @Override
    public ApiResponse<ScenicLoginRespVO> login(ScenicLoginReq scenicLoginReq) throws Exception {

        ScenicAccountEntity scenicAccount = scenicAccountMapper.getByAccount(scenicLoginReq.getAccount());
        if (scenicAccount == null) {
            return ApiResponse.fail("账号不存在");
        }
        if (scenicAccount.getStatus() == 0) {
            return ApiResponse.fail("账号已被禁用");
        }
        if (!scenicAccount.getPassword().equals(scenicLoginReq.getPassword())) {
            return ApiResponse.fail("密码错误");
        }

        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setName(scenicAccount.getName());
        jwtInfo.setAccount(scenicAccount.getAccount());
        jwtInfo.setUserId(scenicAccount.getId());
        jwtInfo.setScenicId(scenicAccount.getScenicId());
        String token = jwtTokenUtil.generateToken(jwtInfo);

        ScenicLoginRespVO scenicLoginRespVO = new ScenicLoginRespVO();
        BeanUtil.copyProperties(scenicAccount,scenicLoginRespVO);
        scenicLoginRespVO.setToken(token);
        return ApiResponse.success(scenicLoginRespVO);
    }

    @Override
    public ApiResponse<List<ContentPageVO>> contentListUseDefaultFace() {
        FaceRespVO lastFaceByUserId = faceMapper.findLastFaceByUserId(BaseContextHandler.getUserId());
        List<ContentPageVO> contentPageVOS = faceContentList(lastFaceByUserId.getId());
        return ApiResponse.success(contentPageVOS);
    }

    @Override
    public ApiResponse<ScenicRespVO> getMyScenic() {
        String userId = BaseContextHandler.getUserId();
        ScenicAccountEntity account = scenicAccountMapper.findAccountById(userId);
        if (account == null) {
            return ApiResponse.fail("用户未绑定景区");
        }
        return getDetails(account.getScenicId());
    }

    @Override
    public ApiResponse<List<DeviceRespVO>> getMyDevices() {
        String userId = BaseContextHandler.getUserId();
        ScenicAccountEntity account = scenicAccountMapper.findAccountById(userId);
        if (account == null) {
            return ApiResponse.fail("用户未绑定景区");
        }
        List<DeviceRespVO> deviceRespVOList = deviceMapper.listByScenicIdWithWVP(account.getScenicId());
        return ApiResponse.success(deviceRespVOList);
    }
}
