package com.huiju.estateagents.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.service.impl.TaUserServiceImpl;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.WxQrCodeUtils;
import com.huiju.estateagents.entity.TaMiniapp;
import com.huiju.estateagents.entity.TaPersonBuilding;
import com.huiju.estateagents.entity.TaPersonVisitRecord;
import com.huiju.estateagents.entity.TaQrcode;
import com.huiju.estateagents.excel.QrCodeStatistics.QrCodeNewPersonNum;
import com.huiju.estateagents.excel.QrCodeStatistics.QrCodeVisitNum;
import com.huiju.estateagents.excel.QrCodeStatistics.QrCodeVisitPersonNum;
import com.huiju.estateagents.mapper.TaMiniappMapper;
import com.huiju.estateagents.mapper.TaQrcodeMapper;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.service.ITaQrcodeService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 二维码管理表 服务实现类
 * </p>
 *
 * @author fxf
 * @since 2020-05-20
 */
@Service
public class TaQrcodeServiceImpl extends ServiceImpl<TaQrcodeMapper, TaQrcode> implements ITaQrcodeService {

    private Logger logger = LoggerFactory.getLogger(TaQrcodeServiceImpl.class);

    @Autowired
    private TaQrcodeMapper taQrcodeMapper;

    @Autowired
    private TaMiniappMapper taMiniappMapper;

    @Autowired
    private IMiniAppService iMiniAppService;

    @Autowired
    private TaUserServiceImpl taUserService;

    /**
     * 条件查询二维码列表
     *
     * @param pageNum
     * @param pageSize
     * @param targetType
     * @param targetName
     * @param channelId
     * @param buildingId
     * @param orgId
     * @return
     */
    @Override
    public ResponseBean listQrCodeByCondition(Integer pageNum, Integer pageSize, String targetType, String targetName, Integer channelId,
                                              String buildingId, Integer userId, Integer orgId, List<TaPersonBuilding> personBuildingList) {
        ResponseBean responseBean = new ResponseBean();

        TaUser taUser = taUserService.getById(userId);
        if (taUser != null && taUser.getIsAdmin() != null && taUser.getIsAdmin()) {
            userId = null;
        }

        IPage<TaQrcode> pg = new Page<>(pageNum, pageSize);
        responseBean.addSuccess(taQrcodeMapper.listQrCodeByCondition(pg, targetType, targetName, channelId, buildingId, userId, orgId, personBuildingList));
        return responseBean;
    }

    /**
     * 保存二维码信息
     *
     * @param taQrcode
     * @param userId
     * @param orgId
     * @return
     */
    @Override
    public ResponseBean saveQrcode(TaQrcode taQrcode, Integer userId, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();

        // 校验是否已有相同的数据
        QueryWrapper<TaQrcode> qrcodeQueryWrapper = new QueryWrapper<>();
        qrcodeQueryWrapper.eq("org_id", orgId);
        if (StringUtils.isBlank(taQrcode.getBuildingId())) {
            qrcodeQueryWrapper.isNull("building_id");
        } else {
            qrcodeQueryWrapper.eq("building_id", taQrcode.getBuildingId());
        }
        if (null == taQrcode.getChannelId()) {
            qrcodeQueryWrapper.isNull("channel_id");
        } else {
            qrcodeQueryWrapper.eq("channel_id", taQrcode.getChannelId());
        }
        qrcodeQueryWrapper.eq("target_type", taQrcode.getTargetType());
        qrcodeQueryWrapper.eq("target_id", taQrcode.getTargetId());
        qrcodeQueryWrapper.gt("status", CommConstant.STATUS_DELETE);
        List<TaQrcode> taQrCodeCheckList = taQrcodeMapper.selectList(qrcodeQueryWrapper);
        if (CollectionUtils.isNotEmpty(taQrCodeCheckList)) {
            responseBean.addError("请勿重复提交");
            return responseBean;
        }

        // 保存数据
        taQrcode.setOrgId(orgId);
        taQrcode.setCreateUser(userId);
        taQrcode.setCreateDate(LocalDateTime.now());
        taQrcode.setStatus(CommConstant.STATUS_NORMAL);
        if (!save(taQrcode)) {
            responseBean.addError("fail");
            return responseBean;
        }

        // 获取appId
        QueryWrapper<TaMiniapp> taMiniappQuery = new QueryWrapper<>();
        taMiniappQuery.eq("org_id", orgId);
        TaMiniapp taMiniapp = taMiniappMapper.selectOne(taMiniappQuery);

        // 生成二维码
        String paramsStr = WxQrCodeUtils.generateSceneAndPage(taQrcode.getTargetType(), "",
                taQrcode.getTargetId(), taQrcode.getTargetType(), String.valueOf(taQrcode.getChannelId()), String.valueOf(taQrcode.getQrCodeId()), taQrcode.getBuildingId());
        ResponseBean qrCodeResult = iMiniAppService.getQrCode(paramsStr, taMiniapp.getMiniappId());
        if (qrCodeResult != null && ResponseBean.CODE_SUCCESS == qrCodeResult.getCode()) {
            // 更新数据
            taQrcode.setQrCodeUrl((String) qrCodeResult.getData());
            if (updateById(taQrcode)) {
                responseBean.addSuccess(taQrcode);
                return responseBean;
            }
        }
        removeById(taQrcode.getQrCodeId());
        responseBean.addError("fail");
        return responseBean;
    }

    /**
     * 获取二维码统计
     *
     * @param qrCodeId
     * @param orgId
     * @return
     */
    @Override
    public ResponseBean getStatisticData(Integer qrCodeId, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();

        // 获取二维码信息
        TaQrcode taQrcode = taQrcodeMapper.selectById(qrCodeId);
        if (taQrcode == null) {
            responseBean.addError("fail");
            return responseBean;
        }

        // 查询访问总人数
        Integer visitPersons = taQrcodeMapper.getVisitPersons(qrCodeId, orgId);

        // 查询访问总次数
        Integer visitNum = taQrcodeMapper.getVisitNum(qrCodeId, orgId);

        // 查询新增用户数
        Integer newPersons = taQrcodeMapper.getNewPersons(qrCodeId, orgId);

        // 组装反参
        JSONObject resultObj = new JSONObject();
        resultObj.put("visitPersons", visitPersons);
        resultObj.put("visitNum", visitNum);
        resultObj.put("newPersons", newPersons);
        resultObj.put("qrCodeInfo", taQrcode);
        responseBean.addSuccess(resultObj);
        return responseBean;
    }

    @Override
    public ResponseBean getStatisticRecord(Integer type, Integer pageNum, Integer pageSize, Integer qrCodeId, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        IPage<TaPersonVisitRecord> pg = new Page<>(pageNum, pageSize);
        switch (type) {
            case 1:
                responseBean.addSuccess(taQrcodeMapper.getVisitPersonsRecord(pg, qrCodeId, orgId));
                break;
            case 2:
                responseBean.addSuccess(taQrcodeMapper.getVisitNumRecord(pg, qrCodeId, orgId));
                break;
            case 3:
                responseBean.addSuccess(taQrcodeMapper.getNewPersonsRecord(pg, qrCodeId, orgId));
                break;
            default:
                responseBean.addError("fail");
                break;
        }
        return responseBean;
    }

    @Override
    public void getStatisticRecordExport(Integer type, Integer qrCodeId, Integer orgId, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        String fileName;
        switch (type) {
            case 1:
                List<QrCodeVisitPersonNum> records = taQrcodeMapper.getVisitPersonsRecordExport(qrCodeId, orgId);
                fileName = URLEncoder.encode("访问人数", "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                EasyExcel.write(response.getOutputStream(), QrCodeVisitPersonNum.class).sheet("访问人数").doWrite(records);
                break;
            case 2:
                List<QrCodeVisitNum> records2 = taQrcodeMapper.getVisitNumRecordExport(qrCodeId, orgId);
                fileName = URLEncoder.encode("访问次数", "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                EasyExcel.write(response.getOutputStream(), QrCodeVisitNum.class).sheet("访问次数").doWrite(records2);
                break;
            case 3:
                List<QrCodeNewPersonNum> records3 = taQrcodeMapper.getNewPersonsRecordExport(qrCodeId, orgId);
                fileName = URLEncoder.encode("新增注册用户", "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                EasyExcel.write(response.getOutputStream(), QrCodeNewPersonNum.class).sheet("新增注册用户").doWrite(records3);
                break;
            default:
                break;
        }
    }
}
