package com.pcloud.book.group.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.group.biz.GroupMaterialAccountBiz;
import com.pcloud.book.group.biz.WeworkTeacherBiz;
import com.pcloud.book.group.dto.WxWorkTeacherDTO;
import com.pcloud.book.group.entity.GroupMaterialAccount;
import com.pcloud.book.group.entity.WeworkTeacher;
import com.pcloud.book.group.entity.WeworkTeacherBookBind;
import com.pcloud.book.group.enums.UseTypeEnum;
import com.pcloud.book.group.mapper.WeworkTeacherBookBindMapper;
import com.pcloud.book.group.mapper.WeworkTeacherMapper;
import com.pcloud.book.group.vo.WeworkTeacherBookBindPageVO;
import com.pcloud.book.group.vo.WeworkTeacherBookBindVO;
import com.pcloud.book.group.vo.WeworkTeacherVO;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.utils.ParamChecker;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.facade.wechat.material.dto.NewsMaterialTemplateDto;
import com.pcloud.facade.wechat.material.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * WeworkTeacherBizImpl
 *
 * @author guiq
 * @version 1.0
 * @since 2020年9月7日
 */
@Component("weworkTeacherBiz")
@Slf4j
public class WeworkTeacherBizImpl implements WeworkTeacherBiz {

    /**
     * 客服老师素材代码模板
     */
    public static final String WEWORK_TEACHER_MATERIAL_HTML = "<div style='margin:10px 0;box-sizing: border-box;'><header style='display: flex;padding:0 20px;'><img style='width: 60px;height: 60px;'      src='${avatar}'      alt=''><div style='margin-left:10px;flex: 1;height: 60px;display:flex;flex-direction: column;justify-content: space-around;align-items: flex-start;'><div style='color:#000;font-size: 16px;font-weight: bold;'>        ${title}</div><div style='color: #666666;font-size: 14px;font-weight: normal;'>${desc}</div></div></header><div style='margin:55px auto 32px;width: 275px;height: 255px;'><div style='width: 275px;height: 255px;background-color: #ffffff;border-radius: 6px;border: solid 1px #66c84f'><div style='margin-top:-16px;margin-left:53px;width: 168px;height: 32px;line-height: 32px;text-align: center; font-size: 14px;color: #ffffff; background-color: #66c84f;border-radius: 6px;'>长按识别下面二维码</div><div style='height: 23px;display: block;text-align: center;margin: 10px auto;letter-spacing: 6px;'> \uD83D\uDC47\uD83D\uDC47\uD83D\uDC47</div><div style='width: 172px;height:172px;display: block;margin: 0 auto;'><img class='qrcode' src='${qrcodeUrl}' alt=''></div></div></div></div>";


    @Autowired
    private WeworkTeacherMapper weworkTeacherMapper;
    @Autowired
    private MaterialService materialService;
    @Autowired
    private GroupMaterialAccountBiz groupMaterialAccountBiz;
    @Autowired
    private WeworkTeacherBookBindMapper weworkTeacherBookBindMapper;

    @Override
    @ParamLog(value = "新增客服老师")
    @Transactional(rollbackFor = Exception.class)
    public Long addWxworkTeacher(WeworkTeacherVO weworkTeacherVO) {
        // 参数校验
        weworkTeacherVO.checkParam4Add();
        WeworkTeacher weworkTeacher = new WeworkTeacher();
        BeanUtil.copyProperties(weworkTeacherVO, weworkTeacher);

        // 创建永久图文素材
        GroupMaterialAccount account;
        String mediaId;
        String materialUrl;
        try {
            account = groupMaterialAccountBiz.getActiveAccount(UseTypeEnum.THIRD_GROUP.value);
            NewsMaterialTemplateDto dto = new NewsMaterialTemplateDto();
            Map<String, String> placeholderMap = new HashMap<>();
            placeholderMap.put("${avatar}",weworkTeacherVO.getAvatar());
            placeholderMap.put("${qrcodeUrl}",weworkTeacherVO.getQrcode());
            dto.setHtmlTemplate(WEWORK_TEACHER_MATERIAL_HTML.replace("${title}",weworkTeacherVO.getNickname()).replace("${desc}",weworkTeacherVO.getDesc()));
            dto.setAccountId(account.getAccountId());
            dto.setTitle(weworkTeacherVO.getTitle());
            dto.setCoverMediaId(account.getCoverMediaId());
            dto.setPlaceholders(placeholderMap);
            dto.setDigest(weworkTeacherVO.getTitle());
            mediaId = ResponseHandleUtil.parseResponse(materialService.createNewsMaterial4Template(dto), String.class);
            materialUrl = ResponseHandleUtil.parseResponse(materialService.getGroupNewsMaterialByMediaId(mediaId), String.class);
        } catch (Exception e) {
            log.info("[WeworkTeacherBizImpl.addWxworkTeacher] 新增客服老师，创建素材失败!", e);
            throw new BookBizException(BookBizException.ERROR, "新增客服老师，创建素材失败!");
        }

        // 新增客服老师记录
        weworkTeacher.setAccountId(account.getAccountId());
        weworkTeacher.setCreateTime(new Date());
        weworkTeacher.setUpdateTime(new Date());
        weworkTeacher.setMediaId(mediaId);
        weworkTeacher.setMaterialUrl(materialUrl);
        weworkTeacherMapper.insert(weworkTeacher);
        return weworkTeacher.getId();
    }

    @Override
    @ParamLog(value = "更新客服老师", isAfterReturn = false)
    @Transactional(rollbackFor = Exception.class)
    public Long updateWxworkTeacher(WeworkTeacherVO weworkTeacherVO) {
        weworkTeacherVO.checkParam4Update();
        WeworkTeacher weworkTeacher = weworkTeacherMapper.selectByPrimaryKey(weworkTeacherVO.getId());
        if (Objects.isNull(weworkTeacher)) {
            log.info("[WeworkTeacherBizImpl.updateWxworkTeacher] 更新客服老师，记录不存在! weworkTeacherVO:{}", weworkTeacherVO);
            throw new BookBizException(BookBizException.ID_NOT_EXIST, "更新客服老师，记录不存在！");
        }
        boolean isChanged = weworkTeacherVO.checkIsChanged(weworkTeacher);
        BeanUtil.copyProperties(weworkTeacherVO, weworkTeacher);
        weworkTeacher.setUpdateTime(new Date());
        weworkTeacherMapper.updateByPrimaryKeySelective(weworkTeacher);

        if (isChanged) {
            // 更新素材
            GroupMaterialAccount account = null;
            try {
                account = groupMaterialAccountBiz.getByAccountId(weworkTeacher.getAccountId());
                NewsMaterialTemplateDto dto = new NewsMaterialTemplateDto();
                Map<String, String> placeholderMap = new HashMap<>();
                placeholderMap.put("${avatar}",weworkTeacherVO.getAvatar());
                placeholderMap.put("${qrcodeUrl}",weworkTeacherVO.getQrcode());
                dto.setHtmlTemplate(WEWORK_TEACHER_MATERIAL_HTML.replace("${title}",weworkTeacherVO.getNickname()).replace("${desc}",weworkTeacherVO.getDesc()));
                dto.setAccountId(account.getAccountId());
                dto.setTitle(weworkTeacherVO.getTitle());
                dto.setCoverMediaId(account.getCoverMediaId());
                dto.setPlaceholders(placeholderMap);
                dto.setDigest(weworkTeacherVO.getTitle());
                dto.setMediaId(weworkTeacher.getMediaId());
                materialService.createNewsMaterial4Template(dto);
            } catch (Exception e) {
                log.info("[WeworkTeacherBizImpl.updateWxworkTeacher] 更新客服老师，更新素材失败! weworkTeacherVO:{}  account:{}", weworkTeacherVO, account);
                throw new BookBizException(BookBizException.ID_NOT_EXIST, "更新客服老师，更新素材失败！");
            }
        }
        return weworkTeacher.getId();
    }

    @Override
    public PageBeanNew<WeworkTeacherVO> getWxworkTeacherList(String name, Integer isOpen, Integer teacherType, Integer currentPage, Integer numPerPage) {
        int offset = numPerPage * currentPage;
        Integer count = weworkTeacherMapper.count4WxworkTeacherList(name, isOpen, teacherType);
        if (Objects.isNull(count) || count < 1) {
            return new PageBeanNew<>();
        }
        List<WeworkTeacherVO> list = weworkTeacherMapper.getWxworkTeacherList(name, isOpen, teacherType, offset, numPerPage);
        return new PageBeanNew<>(currentPage, numPerPage, count, list);
    }

    @Override
    public List<WeworkTeacherVO> queryAll(Long bookId) {
        if (Objects.nonNull(bookId)){
            WeworkTeacherBookBind bind = weworkTeacherBookBindMapper.getByBookId(bookId);
            if (Objects.nonNull(bind) && StrUtil.isNotBlank(bind.getWeworkTeacherArr())){
                List<Long> longs = JSONObject.parseArray(bind.getWeworkTeacherArr(), Long.class);
                if (CollUtil.isEmpty(longs)){
                    return new ArrayList<>();
                }
                return weworkTeacherMapper.getMaterialByIds(longs);
            }
        }
        return weworkTeacherMapper.queryAll();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTeacherById(Long id) {
        weworkTeacherMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindBookWxworkTeacher(WeworkTeacherBookBindVO bindVO) {
        bindVO.checkParam4Bind();
        WeworkTeacherBookBind weworkTeacherBookBind = new WeworkTeacherBookBind();
        BeanUtil.copyProperties(bindVO, weworkTeacherBookBind);
        weworkTeacherBookBind.setUpdateTime(new Date());
        if (Objects.isNull(weworkTeacherBookBindMapper.getByBookId(bindVO.getBookId()))){
            weworkTeacherBookBind.setCreateTime(new Date());
        }
        weworkTeacherBookBind.setWeworkTeacherArr(JSONObject.toJSONString(bindVO.getTeacherList()));
        weworkTeacherBookBindMapper.insertOrUpdate(weworkTeacherBookBind);
    }

    @Override
    public void deleteBookWxworkTeacher(Long bookId) {
        weworkTeacherBookBindMapper.deleteByBookId(bookId);
    }

    @Override
    public PageBeanNew<WeworkTeacherBookBindPageVO> getBookWxworkTeacherList(String name, Integer currentPage, Integer numPerPage) {
        ParamChecker.checkPageParamIsAbsent(currentPage, numPerPage, "分页参数错误！");
        List<WeworkTeacherBookBindPageVO> pageList = new ArrayList<>();
        int offset = currentPage * numPerPage;
        int count = weworkTeacherBookBindMapper.count4BookWxworkTeacherList(name);
        if (count == 0) {
            return new PageBeanNew<>();
        }

        List<WeworkTeacherBookBind> list = weworkTeacherBookBindMapper.getBookWxworkTeacherList(name, offset, numPerPage);
        List<Long> ids = new ArrayList<>();

        if (CollUtil.isNotEmpty(list)) {
            for (WeworkTeacherBookBind weworkTeacherBookBind : list) {
                if (StrUtil.isNotBlank(weworkTeacherBookBind.getWeworkTeacherArr())) {
                    ids.addAll(JSONObject.parseArray(weworkTeacherBookBind.getWeworkTeacherArr(), Long.class));
                }
            }
        }

        if (CollUtil.isNotEmpty(ids)) {
            // 查询教师集合
            List<WeworkTeacher> teachers = weworkTeacherMapper.listByIds(ids);
            Map<Long, WeworkTeacher> teacherMap = teachers.stream().collect(Collectors.toMap(WeworkTeacher::getId, weworkTeacher -> weworkTeacher));
            if (CollUtil.isNotEmpty(teacherMap)) {
                for (WeworkTeacherBookBind weworkTeacherBookBind : list) {
                    WeworkTeacherBookBindPageVO pageVO = new WeworkTeacherBookBindPageVO();
                    BeanUtil.copyProperties(weworkTeacherBookBind, pageVO);
                    ArrayList<WeworkTeacher> arrayList = new ArrayList<>();
                    if (StrUtil.isNotBlank(weworkTeacherBookBind.getWeworkTeacherArr())) {
                        List<Long> parseArray = JSONObject.parseArray(weworkTeacherBookBind.getWeworkTeacherArr(), Long.class);
                        for (Long aLong : parseArray) {
                            if (Objects.nonNull(teacherMap.get(aLong))){
                                arrayList.add(teacherMap.get(aLong));
                            }
                        }
                    }
                    pageVO.setTeacherList(arrayList);
                    pageList.add(pageVO);
                }
            }
        }
        return new PageBeanNew<>(currentPage, numPerPage, count, pageList);
    }

    @Override
    public String getOneTeacherQrcode() {
        return weworkTeacherMapper.getOneTeacherQrcode();
    }

    @Override
    @ParamLog("根据teacherIds获取企业微信客服")
    public Map<Long, WxWorkTeacherDTO> getWxWorkTeacherByIds(List<Long> teacherIds) {
        return weworkTeacherMapper.getWxWorkTeacherByIds(teacherIds);
    }

}
