package com.m2pool.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.m2pool.common.core.Result.R;
import com.m2pool.common.core.constant.HttpStatus;
import com.m2pool.common.core.web.page.TableDataInfo;
import com.m2pool.common.security.utils.SecurityUtils;
import com.m2pool.manage.dto.ManageBroadcastDto;
import com.m2pool.manage.entity.ManageBroadcast;
import com.m2pool.manage.mapper.ManageBroadcastMapper;
import com.m2pool.manage.service.ManageBroadcastService;
import com.m2pool.manage.utils.TranslateUtils;
import com.m2pool.manage.vo.ManageBaseVo;
import com.m2pool.manage.vo.ManageBroadcastVo;
import com.m2pool.manage.vo.PageVo;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 广播信息 服务实现类
 */
@Service
public class ManageBroadcastServiceImpl extends ServiceImpl<ManageBroadcastMapper, ManageBroadcast> implements ManageBroadcastService {


    @Resource
    private ManageBroadcastMapper manageBroadcastMapper;

    /**
     * 获取所有广播信息
     *
     * @return 广播列表
     */
    @Override
    public TableDataInfo<ManageBroadcastDto> getListDataByPage(PageVo pageVo) {

        PageHelper.startPage(pageVo.getPageNum(), pageVo.getPageSize());
        List<ManageBroadcastDto> listDataByPage = manageBroadcastMapper.getListDataByPage();
        return getDataTable(listDataByPage);
    }

    private TableDataInfo<ManageBroadcastDto> getDataTable(List<ManageBroadcastDto>  list)
    {
        TableDataInfo<ManageBroadcastDto> rspData = new TableDataInfo<ManageBroadcastDto>();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        PageInfo<ManageBroadcastDto> pageInfo = new PageInfo<ManageBroadcastDto>(list);
        rspData.setTotal(pageInfo.getTotal());
        rspData.setTotalPage(pageInfo.getPages());
        PageHelper.clearPage();
        return rspData;
    }


    @Override
    public R<List<ManageBroadcastDto>> findDataById(ManageBaseVo manageBaseVo) {
        LambdaQueryWrapper<ManageBroadcast> eq = new LambdaQueryWrapper<ManageBroadcast>()
                .eq(ManageBroadcast::getDel, false);
        if(manageBaseVo != null && manageBaseVo.getId() != null){
            eq.le(ManageBroadcast::getId, manageBaseVo.getId());
            eq.orderByDesc(ManageBroadcast::getId).last("limit 20");
        }else{
            eq.orderByDesc(ManageBroadcast::getId);
        }


        List<ManageBroadcast> list = this.list(eq);
        List<ManageBroadcastDto> collect;
        if (manageBaseVo != null && "zh".equals(manageBaseVo.getLang())){
            collect  = list.stream().map(broadcast ->
                        ManageBroadcastDto.builder()
                                .content(broadcast.getContent())
                                .buttonContent(broadcast.getButtonContent())
                                .buttonPath(broadcast.getButtonPath())
                                .id(broadcast.getId())
                                .createUser(broadcast.getCreateUser())
                                .updateUser(broadcast.getUpdateUser())
                                .updateTime(broadcast.getUpdateTime())
                                .createTime(broadcast.getCreateTime())
                                .build()
                    ).collect(Collectors.toList());
        }else{
            collect  = list.stream().map(broadcast -> {
                        //如果英文为null，需要翻译并保存一下
                        if("".equals(broadcast.getContentEn()) || ("".equals(broadcast.getButtonContentEn()) && !"".equals(broadcast.getButtonContent()))){
                            broadcast.setButtonContentEn(TranslateUtils.translate(broadcast.getButtonContent(), "zh", "en"));
                            broadcast.setContentEn(TranslateUtils.translate(broadcast.getContent(), "zh", "en"));
                            manageBroadcastMapper.updateById(broadcast);
                        }
                       return ManageBroadcastDto.builder()
                                .content(broadcast.getContentEn())
                                .buttonContent(broadcast.getButtonContentEn())
                               .buttonPath(broadcast.getButtonPath())
                                .id(broadcast.getId())
                                .createUser(broadcast.getCreateUser())
                                .updateUser(broadcast.getUpdateUser())
                                .updateTime(broadcast.getUpdateTime())
                                .createTime(broadcast.getCreateTime())
                                .build();
                    }).collect(Collectors.toList());
        }


        return R.success(collect);
    }

    /**
     * 新增广播信息
     *
     * @param broadcastVo 广播对象
     * @return 是否成功
     */
    @Override
    public R<String> addBroadcast(ManageBroadcastVo broadcastVo) {
        String contentEn = TranslateUtils.translate(broadcastVo.getContent(), "zh", "en");
        // 休眠 1 秒，确保符合 API 的 QPS 限制。可升级为高级版，qps为10。不要把两个文本放到一起同时翻译，会出问题
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        String buttonContentEn = TranslateUtils.translate(broadcastVo.getButtonContent(), "zh", "en");
        ManageBroadcast broadcast = ManageBroadcast.builder()
                .content(broadcastVo.getContent())
                .contentEn(contentEn)
                .buttonContent(broadcastVo.getButtonContent())
                .buttonContentEn(buttonContentEn)
                .buttonPath(broadcastVo.getButtonPath())
                .createUser(SecurityUtils.getUsername())
                .updateTime(LocalDateTime.now())
                .build();
        if(this.save(broadcast)){
            return R.success("添加成功");
        }
      return R.fail("添加失败");
    }

    /**
     * 根据ID删除广播(逻辑删除)
     *
     * @param id 主键ID
     * @return 是否成功
     */
    @Override
    public R<String> deleteBroadcastById(Long id) {
        boolean b = this.updateById(ManageBroadcast.builder().id(id).del(true).build());
        if (b){
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @Override
    public R<String> updateBroadcast(ManageBroadcastVo broadcastVo) {
        String contentEn = TranslateUtils.translate(broadcastVo.getContent(), "zh", "en");
        // 休眠 1 秒，确保符合 API 的 QPS 限制。可升级为高级版，qps为10。不要把两个文本放到一起同时翻译，会出问题
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        String buttonContentEN = TranslateUtils.translate(broadcastVo.getButtonContent(), "zh", "en");
        boolean b = this.updateById(ManageBroadcast.builder()
                        .id(broadcastVo.getId())
                        .content(broadcastVo.getContent())
                        .contentEn(contentEn)
                        .buttonContent(broadcastVo.getButtonContent())
                        .buttonContentEn(buttonContentEN)
                        .buttonPath(broadcastVo.getButtonPath())
                        .updateUser(SecurityUtils.getUsername())
                .build());
        if (b){
            return R.success("修改成功");
        }
        return R.fail("修改失败");
    }


    @Override
    public R<ManageBroadcastDto> findDataInfo(ManageBaseVo manageBaseVo) {

        ManageBroadcast byId = this.getById(manageBaseVo.getId());
        if(byId != null){
            return R.success(ManageBroadcastDto.builder()
                    .content(byId.getContent())
                    .id(byId.getId())
                    .buttonPath(byId.getButtonPath())
                    .buttonContent(byId.getButtonContent())
                    .createUser(byId.getCreateUser())
                    .updateUser(byId.getUpdateUser())
                    .updateTime(byId.getUpdateTime())
                    .createTime(byId.getCreateTime())
                    .build());
        }
        return R.fail("该通知不存在");
    }
}
