package com.xunmei.core.edu.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunmei.common.core.constant.Constants;
import com.xunmei.common.core.constant.ErrorMsgConstants;
import com.xunmei.common.core.constant.SecurityConstants;
import com.xunmei.common.core.domain.R;
import com.xunmei.common.core.domain.edu.domain.SysLearningMaterials;
import com.xunmei.common.core.domain.edu.dto.SysLearningMaterialsPageDto;
import com.xunmei.common.core.domain.edu.vo.SysLearningMaterialsPageVo;
import com.xunmei.common.core.utils.DateHelper;
import com.xunmei.common.core.utils.DateUtils;
import com.xunmei.common.core.web.page.TableDataInfo;
import com.xunmei.common.security.utils.SecurityUtils;
import com.xunmei.core.edu.mapper.SysLearningMaterialsMapper;
import com.xunmei.core.edu.service.ISysLearningMaterialsService;
import com.xunmei.system.api.RemoteOrgService;
import com.xunmei.system.api.domain.SysOrg;
import com.xunmei.system.api.function.RemoteCallHandlerExecutor;
import com.xunmei.system.api.function.RemoteCallHandlerExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

/**
 * 学习资料Service业务层处理
 *
 * @author xunmei
 * @date 2023-08-21
 */
@Service
public class SysLearningMaterialsServiceImpl extends ServiceImpl<SysLearningMaterialsMapper, SysLearningMaterials> implements ISysLearningMaterialsService {
    @Autowired
    private SysLearningMaterialsMapper sysLearningMaterialsMapper;
    @Autowired
    private RemoteOrgService remoteOrgService;

    @Override
    public TableDataInfo selectPage(SysLearningMaterialsPageDto sysLearningMaterials) {
        Page<SysLearningMaterialsPageVo> page;
        //分页
        if (ObjectUtil.isAllNotEmpty(sysLearningMaterials.getPageNum(), sysLearningMaterials.getPageSize())) {
            page = new Page<>(sysLearningMaterials.getPageNum(), sysLearningMaterials.getPageSize());
        } else {
            page = new Page<>();
        }
        dealParentOrgId(sysLearningMaterials);
        sysLearningMaterials.setUserId(SecurityUtils.getUserId());
        //获取数据
        page = sysLearningMaterialsMapper.selectPageData(page, sysLearningMaterials);
        for (SysLearningMaterialsPageVo record : page.getRecords()) {
            extractStringFromUrl(record);
        }
        //抓换为TableDataInfo适配前端
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setMsg("操作成功");
        tableDataInfo.setCode(200);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        return tableDataInfo;
    }

    private void dealParentOrgId(SysLearningMaterialsPageDto sysLearningMaterials) {
        SysOrg sysOrg = remoteOrgService.selectSysOrgById(sysLearningMaterials.getOrgId(), SecurityConstants.INNER);
       // SysOrg sysOrg = r.getData();
        if (sysOrg == null || ObjectUtil.isEmpty(sysOrg.getPath())) {
            throw new RuntimeException("机构不存在或机构信息缺失!");
        }
        String[] split = sysOrg.getPath().split("-");
        List<Long> list = new ArrayList<>();
        Stream.of(split).forEach(s -> list.add(Long.valueOf(s)));
        list.remove(sysLearningMaterials.getOrgId());
        sysLearningMaterials.setOrgIdList(list);
    }

    public void extractStringFromUrl(SysLearningMaterialsPageVo record) {
        if (ObjectUtil.isEmpty(record.getFile()) || !record.getFile().contains(Constants.HTTP)) {
            return;
        }
        // 获取最后一个斜杠的索引
        int lastSlashIndex = record.getFile().lastIndexOf("/");
        // 获取最后一个斜杠后面的字符串
        record.setFile(record.getFile().substring(lastSlashIndex + 1));
    }

    /**
     * 查询学习资料
     *
     * @param id 学习资料主键
     * @return 学习资料
     */
    @Override
    public SysLearningMaterials selectSysLearningMaterialsById(Long id) {
        return sysLearningMaterialsMapper.selectById(id);
    }

    /**
     * 查询学习资料列表
     *
     * @param sysLearningMaterials 学习资料
     * @return 学习资料
     */
    @Override
    public List<SysLearningMaterials> selectSysLearningMaterialsList(SysLearningMaterials sysLearningMaterials) {
        return sysLearningMaterialsMapper.selectList(new QueryWrapper<>(sysLearningMaterials));
    }

    /**
     * 新增学习资料
     *
     * @param sysLearningMaterials 学习资料
     * @return 结果
     */
    @Override
    public int insertSysLearningMaterials(SysLearningMaterials sysLearningMaterials) {
        sysLearningMaterials.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        sysLearningMaterials.setCreateTime(DateUtils.getNowDate());
        sysLearningMaterials.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        sysLearningMaterials.setUpdateTime(DateUtils.getNowDate());
        sysLearningMaterials.setIsOpen(0);
         SysOrg sysOrg = remoteOrgService.selectSysOrgById(sysLearningMaterials.getOrgId(), SecurityConstants.INNER);
       // SysOrg sysOrg = r.getData();
        if (sysOrg != null) {
            sysLearningMaterials.setOrgName(sysOrg.getName());
            sysLearningMaterials.setOrgPath(sysOrg.getPath());
        }
        return sysLearningMaterialsMapper.insert(sysLearningMaterials);
    }

    /**
     * 修改学习资料
     *
     * @param sysLearningMaterials 学习资料
     * @return 结果
     */
    @Override
    public int updateSysLearningMaterials(SysLearningMaterials sysLearningMaterials) {
        sysLearningMaterials.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        sysLearningMaterials.setUpdateTime(DateUtils.getNowDate());
        return sysLearningMaterialsMapper.updateById(sysLearningMaterials);
    }

    /**
     * 批量删除学习资料
     *
     * @param ids 需要删除的学习资料主键
     * @return 结果
     */
    @Override
    public int deleteSysLearningMaterialsByIds(Long[] ids) {
        return sysLearningMaterialsMapper.deleteBatchIds(Arrays.asList((ids)));
    }

    /**
     * 删除学习资料信息
     *
     * @param id 学习资料主键
     * @return 结果
     */
    @Override
    public int deleteSysLearningMaterialsById(Long id) {
        return sysLearningMaterialsMapper.deleteById(id);
    }

    @Override
    public int editOpen(Long id, Integer isOpen) {
        SysLearningMaterials sysLearningMaterials = sysLearningMaterialsMapper.selectById(id);
        if (sysLearningMaterials != null) {
            sysLearningMaterials.setIsOpen(isOpen);
            sysLearningMaterials.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
            sysLearningMaterials.setUpdateTime(DateUtils.getNowDate());
            return sysLearningMaterialsMapper.updateById(sysLearningMaterials);
        }
        return 0;
    }

    @Override
    public void export(SysLearningMaterialsPageDto sysLearningMaterials, HttpServletResponse response) throws
            IOException {
        SysOrg sysOrg = RemoteCallHandlerExecutor.executeRemoteCall(() -> remoteOrgService.selectOrgById(sysLearningMaterials.getOrgId(), SecurityConstants.INNER), ErrorMsgConstants.QUERY_ORG_DATA_ERROR);

        sysLearningMaterials.setPageSize((long) Integer.MAX_VALUE);
        final TableDataInfo tableDataInfo = this.selectPage(sysLearningMaterials);
        if (ObjectUtil.isEmpty(tableDataInfo.getRows())) {
            throw new RuntimeException("导出数据为空!");
        }
        List<SysLearningMaterialsPageVo> list = (List<SysLearningMaterialsPageVo>) tableDataInfo.getRows();

        //在内存操作，写到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("title", "资料标题");
        writer.addHeaderAlias("knowledgeName", "资料类型");
        writer.addHeaderAlias("orgName", "所属机构");
        writer.addHeaderAlias("isOpen", "是否公开");
        writer.addHeaderAlias("createBy", "上传人");
        writer.addHeaderAlias("createTime", "上传时间");

        //只保留别名的数据
        writer.setOnlyAlias(true);
        // 默认配置
        writer.write(list, true);
        // 设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        // 设置标题
        String fileName = URLEncoder.encode("【" + sysOrg.getName() + "】-学习资料" + DateHelper.getDateString(new Date()), "UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        //将Writer刷新到OutPut
        writer.flush(outputStream, true);
        outputStream.close();
        writer.close();


    }
}
