package com.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.om.entity.dto.*;
import com.om.entity.po.Client;
import com.om.entity.po.Wxsc;
import com.om.entity.vo.AppWxscQueryPageVO;
import com.om.entity.vo.AppWxscVO;
import com.om.exception.BadReqException;
import com.om.exception.BizException;
import com.om.mapper.WxscMapper;
import com.om.service.IClientService;
import com.om.service.IWxscService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.om.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author henry-ong
 * @since 2024-03-09
 */
@Service
public class WxscServiceImpl extends ServiceImpl<WxscMapper, Wxsc> implements IWxscService {
  private final WxscMapper wxscMapper;

  public WxscServiceImpl(WxscMapper wxscMapper) {
    this.wxscMapper = wxscMapper;
  }

  @Resource
  private HuaweiObsUtil obsUtil;

  @Resource
  private IClientService clientService;

  @Resource
  private PushUtil pushUtil;

  @Override
  public Page<Wxsc> findManual(Page<Wxsc> page, String code, String title) {
    return wxscMapper.findManual(page, code, title);
  }

    @Override
    public Result appGetPageList(AppWxscQueryPageDTO dto) {
      if (BeanUtil.isEmpty(dto)){
          return Result.fail("未获取到数据").result(ResultCode.NO_DATA);
      }
        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        String clientNum = guidDTO.getClientNum();
        String language = dto.getLanguage();

        Integer pageIndex = dto.getPageIndex();
        Integer pageSize = dto.getPageSize();

        Page<Wxsc> page = this.lambdaQuery()
                .orderByDesc(Wxsc::getCreateTime)
                .eq(Wxsc::getClientCode,clientNum)
                .eq(Wxsc::getLang,language)
                .page(new Page<>(pageIndex, pageSize));

        if (BeanUtil.isEmpty(page)){
            return Result.ok();
        }

        AppWxscQueryPageVO vo = new AppWxscQueryPageVO();
        vo.setCurrent((int) page.getCurrent());
        vo.setTotal((int) page.getTotal());
        vo.setPages((int) page.getPages());
        vo.setSize((int) page.getSize());

        List<AppWxscVO> appWxscVOS = new ArrayList<>();

        List<Wxsc> records = page.getRecords();
        for (Wxsc record : records) {
            AppWxscVO appWxscVO = new AppWxscVO();
            appWxscVO.setMaintenanceManualId(record.getId());
            appWxscVO.setMaintenanceManualName(record.getScName());
            appWxscVO.setCreateTime(record.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            appWxscVOS.add(appWxscVO);
        }
        vo.setMaintenanceManualLis(appWxscVOS);
        return Result.ok(vo);
    }

    @Override
    public Result<Wxsc> appGetById(AppWxscDTO dto) {
        Integer id = dto.getId();
        String language = dto.getLanguage();

        //根据id查询
        Wxsc wxsc = this.lambdaQuery()
                .eq(Wxsc::getId, id)
                .eq(Wxsc::getLang, language)
                .one();

        if (BeanUtil.isEmpty(wxsc)){
            throw new BadReqException("该维修资料不存在！");
        }
        return Result.ok(wxsc);
    }

    @Override
    public Result deleteById(Integer id) {
        Wxsc byId = this.getById(id);
        if (BeanUtil.isEmpty(byId)){
            throw new BadReqException("该维修手册不存在");
        }

        this.removeById(id);
        return Result.ok();
    }

    @Override
    public Result pushWxzl(Integer id) {
        Wxsc wxsc = this.getById(id);
        if (BeanUtil.isEmpty(wxsc)){
            throw new BadReqException("该维修手册不存在");
        }
        PushInfo pushInfo = new PushInfo();
        pushInfo.setPushInfoType(4);

        MaintenanceManualInfo maintenanceManualInfo = new MaintenanceManualInfo();
        maintenanceManualInfo.setType("0");
        List<Describe> describeList = new ArrayList<>();
        String title = wxsc.getTitle();
        List<Wxsc> wxscList = this.lambdaQuery()
                .eq(Wxsc::getTitle, title)
                .eq(Wxsc::getClientCode,wxsc.getClientCode())
                .eq(Wxsc::getBrandCode,wxsc.getBrandCode())
                .list();
        if (CollectionUtil.isNotEmpty(wxscList)){
            for (Wxsc sc : wxscList) {
                Describe describe = new Describe();
                describe.setLanguage(sc.getLang());
               describe.setDescription(sc.getScName());
                describeList.add(describe);
            }
        }

        maintenanceManualInfo.setDescribeList(describeList);

        pushInfo.setJson(GsonUtils.toJsonString(maintenanceManualInfo));

        String clientCode = wxsc.getClientCode();
        if (StringUtils.isNotBlank(clientCode)){

            Client client = clientService.lambdaQuery()
                    .eq(Client::getNumber, clientCode)
                    .one();

            if (BeanUtil.isEmpty(client)){
                throw new BadReqException("该客户端编号不存在");
            }
            String deviceToken = client.getDeviceToken();
            if (StringUtils.isNotBlank(deviceToken)){
                String[] token = new String[]{deviceToken};
                try {
                    pushUtil.sendAndroidListcastJSON(token,pushInfo);
                } catch (Exception e) {
                    throw new BizException("推送失败");
                }
            }
        }
        return Result.ok();
    }
}
