package com.zd.laboratory.service.impl;

import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.FileConfigUtils;
import com.zd.common.core.utils.UrlFormatUtils;
import com.zd.common.core.utils.poi.ExcelUtil;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.service.TokenService;
import com.zd.laboratory.domain.LabNotifyplan;
import com.zd.laboratory.domain.vo.LabNotifyplanExcelVO;
import com.zd.laboratory.domain.vo.LabNotifyplanVO;
import com.zd.laboratory.mapper.LabNotifyplanMapper;
import com.zd.laboratory.mqtt.constants.MqttConstants;
import com.zd.laboratory.mqtt.entiy.MessageBody;
import com.zd.laboratory.mqtt.service.impl.CommonSend;
import com.zd.laboratory.service.ILabNotifyplanService;
import com.zd.system.api.domain.SysUser;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 大屏通知计划Service业务层处理
 *
 * @author zd
 * @date 2022-02-16
 */
@Service
public class LabNotifyplanServiceImpl implements ILabNotifyplanService
{
    @Autowired
    private LabNotifyplanMapper labNotifyplanMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CommonSend commonSend;

    @Autowired
    private FileConfigUtils fileConfigUtils;

    /***
     * PC端集合查询
     * @param labNotifyplan
     * @return
     */
    @Override
    public List<LabNotifyplanVO> selectLabNotifyplanListVOPC(LabNotifyplanVO labNotifyplan) {
        return labNotifyplanMapper.selectLabNotifyplanListVO(labNotifyplan);
    }

    /**
     * 查询大屏通知计划
     *
     * @param id 大屏通知计划主键
     * @return 大屏通知计划
     */
    @Override
    public LabNotifyplanVO selectLabNotifyplanById(Long id)
    {
        LabNotifyplanVO labNotifyplanVO = labNotifyplanMapper.selectLabNotifyplanById(id);

        //数据为 工作计划类型时
        if(2==labNotifyplanVO.getType()){
            try {
                //url不为空时解析
                if(labNotifyplanVO.getContentUrl()!=null){
                    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                    ExcelUtil<LabNotifyplanExcelVO> util = new ExcelUtil<LabNotifyplanExcelVO>(LabNotifyplanExcelVO.class);

                    InputStream intstream = null;
                    intstream = new URL(labNotifyplanVO.getContentUrl()).openStream();
                    List<LabNotifyplanExcelVO> excelList = null;
                    excelList = util.importExcel(intstream);
                    /*labNotifyplanVO.setContent(excelList.get(0).getContent());
                    labNotifyplanVO.setCompany(excelList.get(0).getCompany());*/
                    labNotifyplanVO.setExcelList(excelList);
                    //Date date = (Date) sdf.parse(excelList.get(0).getCreateDate());
                    //labNotifyplanVO.setCreateTime(date);
                    labNotifyplanVO.setExcelList(excelList);
                    intstream.close();
                }
            } catch (IOException e) {
                //e.printStackTrace();
                throw new ServiceException("文件解析异常！");
            }catch (Exception e) {
                //e.printStackTrace();
                throw new ServiceException("文件解析异常！");
            }
            /*//组装文件名
            String[] filename= labNotifyplanVO.getContentName().split(";");
            List<String> listFilename= new ArrayList<>();
              for (int i=0;i<filename.length;i++){
                  listFilename.add(filename[i]);
              }
            labNotifyplanVO.setListFilename(listFilename);

            //组装附件
            String[] fileurl= labNotifyplanVO.getContentUrl().split(";");
            List<String> listFileurl= new ArrayList<>();
            for (int i=0;i<fileurl.length;i++){
                listFileurl.add(fileurl[i]);
            }
            labNotifyplanVO.setListFileurl(listFileurl);*/
        }
        return labNotifyplanVO;
    }

    /**
     * 查询大屏通知计划列表
     *
     * @param labNotifyplan 大屏通知计划
     * @return 大屏通知计划
     */
    @Override
    public List<LabNotifyplan> selectLabNotifyplanList(LabNotifyplan labNotifyplan)
    {
        return labNotifyplanMapper.selectLabNotifyplanList(labNotifyplan);
    }

    /**
     *
     * @param labNotifyplan 大屏通知计划
     * @param request
     * @return
     */
    @Override
    @DataScope(deptAlias = "d" , userAlias = "u", permi = PerPrefix.LABORATORY_NOTIFYPLAN)
    public List<LabNotifyplanVO> selectLabNotifyplanListVO(LabNotifyplanVO labNotifyplan, HttpServletRequest request) {
        List<LabNotifyplanVO> list =labNotifyplanMapper.selectLabNotifyplanListVO(labNotifyplan);
        InputStream intstream =null;
        try {
            //是否需要解析excel 标识 remark=1
            if(list.size()>0 && "1".equals(labNotifyplan.getRemark())){
                ExcelUtil<LabNotifyplanExcelVO> util = new ExcelUtil<LabNotifyplanExcelVO>(LabNotifyplanExcelVO.class);
                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                    //url为空时跳出本次循环
                    if(list.get(0).getContentUrl()!=null) {
                        String baseUrl=request.getServerName() ;
                        String url="";
                        if(baseUrl.contains("192.168")){
                            url=fileConfigUtils.getLocalUrl()+list.get(0).getContentUrl();
                        }else{
                            url=fileConfigUtils.getRemoteUrl()+list.get(0).getContentUrl();
                        }
                        url= UrlFormatUtils.getHttpsORHttpUrl(url);

                        /*//文件访问路径
                        //String url = "http://192.168.1.17:9300//statics/2022/02/18/3d78b3c2-8108-4e78-a419-954e4b71a92a.xls";
                        InputStream intstream = new URL(list.get(0).getContentUrl()).openStream();
                        List<LabNotifyplanExcelVO> excelList = util.importExcel(intstream);
                        //list.get(0).setContent(excelList.get(0).getContent());
                        //list.get(0).setCompany(excelList.get(0).getCompany());
                        Date date = (Date) sdf.parse(excelList.get(0).getCreateDate());
                        String formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
                        //String ss = sdf.format(Date.parse(excelList.get(0).getCreateDate()));
                        *//*Date date = (Date) sdf.parse("Sat Jan 01 10:20:00 CST 2022");
                        String formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);*//*
                        //System.out.println(DateUtils.dateTime("YYYY-mm-dd HH:mm",excelList.get(0).getCreateDate()));
                        //list.get(0).setCreateTime(formatStr);
                        excelList.get(0).setCreateDate(formatStr);
                        list.get(0).setExcelList(excelList);
                        intstream.close();*/
                        //文件访问路径
                        //String url = "http://192.168.1.17:9300//statics/2022/02/18/3d78b3c2-8108-4e78-a419-954e4b71a92a.xls";
                        intstream = new URL(url).openStream();
                        List<LabNotifyplanExcelVO> excelList = util.importExcel(intstream);
                        list.get(0).setExcelList(excelList);
                        intstream.close();
                    }

            }

        } catch (IOException e) {
            //e.printStackTrace();
            if(intstream!=null){
                try {
                    intstream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            throw new ServiceException("文件解析异常！");
        } catch (Exception e) {
            //e.printStackTrace();
            if(intstream!=null){
                try {
                    intstream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            throw new ServiceException("文件解析异常！");
        }
        return list;
    }

    /**
     *
     * @param labNotifyplan 大屏工作计划
     * @param request
     * @return
     */
    @Override
    @DataScope(deptAlias = "d" ,userAlias = "u", permi = PerPrefix.LABORATORY_WORKNOTIFYPLAN)
    public List<LabNotifyplanVO> selectLabWorkNotifyplanListVO(LabNotifyplanVO labNotifyplan, HttpServletRequest request) {
        List<LabNotifyplanVO> list =labNotifyplanMapper.selectLabNotifyplanListVO(labNotifyplan);
        InputStream intstream =null;
        try {
            //是否需要解析excel 标识 remark=1
            if(list.size()>0 && "1".equals(labNotifyplan.getRemark())){
                ExcelUtil<LabNotifyplanExcelVO> util = new ExcelUtil<LabNotifyplanExcelVO>(LabNotifyplanExcelVO.class);
                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                //url为空时跳出本次循环
                if(list.get(0).getContentUrl()!=null) {
                    String baseUrl=request.getServerName() ;
                    String url="";
                    if(baseUrl.contains("192.168")){
                        url=fileConfigUtils.getLocalUrl()+list.get(0).getContentUrl();
                    }else{
                        url=fileConfigUtils.getRemoteUrl()+list.get(0).getContentUrl();
                    }
                    url= UrlFormatUtils.getHttpsORHttpUrl(url);

                        /*//文件访问路径
                        //String url = "http://192.168.1.17:9300//statics/2022/02/18/3d78b3c2-8108-4e78-a419-954e4b71a92a.xls";
                        InputStream intstream = new URL(list.get(0).getContentUrl()).openStream();
                        List<LabNotifyplanExcelVO> excelList = util.importExcel(intstream);
                        //list.get(0).setContent(excelList.get(0).getContent());
                        //list.get(0).setCompany(excelList.get(0).getCompany());
                        Date date = (Date) sdf.parse(excelList.get(0).getCreateDate());
                        String formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
                        //String ss = sdf.format(Date.parse(excelList.get(0).getCreateDate()));
                        *//*Date date = (Date) sdf.parse("Sat Jan 01 10:20:00 CST 2022");
                        String formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);*//*
                        //System.out.println(DateUtils.dateTime("YYYY-mm-dd HH:mm",excelList.get(0).getCreateDate()));
                        //list.get(0).setCreateTime(formatStr);
                        excelList.get(0).setCreateDate(formatStr);
                        list.get(0).setExcelList(excelList);
                        intstream.close();*/
                    //文件访问路径
                    //String url = "http://192.168.1.17:9300//statics/2022/02/18/3d78b3c2-8108-4e78-a419-954e4b71a92a.xls";
                    intstream = new URL(url).openStream();
                    List<LabNotifyplanExcelVO> excelList = util.importExcel(intstream);
                    list.get(0).setExcelList(excelList);
                    intstream.close();
                }

            }

        } catch (IOException e) {
            //e.printStackTrace();
            if(intstream!=null){
                try {
                    intstream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            throw new ServiceException("文件解析异常！");
        } catch (Exception e) {
            //e.printStackTrace();
            if(intstream!=null){
                try {
                    intstream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            throw new ServiceException("文件解析异常！");
        }
        return list;
    }

    /**
     * 新增大屏通知计划
     *
     * @param labNotifyplan 大屏通知计划
     * @return 结果
     */
    @Override
    public int insertLabNotifyplan(LabNotifyplan labNotifyplan, HttpServletRequest request)
    {
        //添加创建人
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        labNotifyplan.setUserId(sysUser.getUserId());
        labNotifyplan.setCreateBy(sysUser.getNickName());
        labNotifyplan.setCreateTime(new Date());
        labNotifyplan.setDeptId(sysUser.getDeptId());
        labNotifyplan.setDeptName(sysUser.getDept().getDeptName());

        InputStream intstream=null;
        try {
            //为工作计划时 解析文件是否合格 主要是时间校验
            if(2==labNotifyplan.getType()){

                String baseUrl=request.getServerName() ;
                String url="";
                if(baseUrl.contains("192.168")){
                    url=fileConfigUtils.getLocalUrl()+ labNotifyplan.getContentUrl();
                }else{
                    url=fileConfigUtils.getRemoteUrl()+ labNotifyplan.getContentUrl();
                }
                url= UrlFormatUtils.getHttpsORHttpUrl(url);

                ExcelUtil<LabNotifyplanExcelVO> util = new ExcelUtil<>(LabNotifyplanExcelVO.class);
                intstream = new URL(url).openStream();
                List<LabNotifyplanExcelVO> excelList = util.importExcel(intstream);
                if(CollectionUtils.isEmpty(excelList)){
                    throw new ServiceException("数据不能为空！");
                    // 时间格式暂不校验
                }
                intstream.close();
            }
        }catch (Exception e) {
            //e.printStackTrace();
            if(intstream!=null){
                try {
                    intstream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            throw new ServiceException("上传文件格式解析异常！");
        }
        int id = labNotifyplanMapper.insertLabNotifyplan(labNotifyplan);
        if(id>0){
            //1通知 2计划
            commonSend.send(MqttConstants.LAB_BIG_VIEW_PLAN, new MessageBody("有新的通知发布。", labNotifyplan.getType()));
        }
        return id;
    }

    /**
     * 修改大屏通知计划
     *
     * @param labNotifyplan 大屏通知计划
     * @return 结果
     */
    @Override
    public int updateLabNotifyplan(LabNotifyplan labNotifyplan)
    {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        labNotifyplan.setUpdateTime(DateUtils.getNowDate());
        labNotifyplan.setUpdateUserid(sysUser.getUserId());
        labNotifyplan.setUpdateUsername(sysUser.getNickName());
        return labNotifyplanMapper.updateLabNotifyplan(labNotifyplan);
    }

    /**
     * 批量删除大屏通知计划
     *
     * @param ids 需要删除的大屏通知计划主键
     * @return 结果
     */
    @Override
    public int deleteLabNotifyplanByIds(Long[] ids)
    {
        return labNotifyplanMapper.deleteLabNotifyplanByIds(ids);
    }

    /**
     * 删除大屏通知计划信息
     *
     * @param id 大屏通知计划主键
     * @return 结果
     */
    @Override
    public int deleteLabNotifyplanById(Long id)
    {
        return labNotifyplanMapper.deleteLabNotifyplanById(id);
    }

    /***
     * 工作计划详情
     * @param labNotifyplan
     * @return
     */
    @Override
    public List<LabNotifyplanVO> listIndexJhDetals(LabNotifyplanVO labNotifyplan, HttpServletRequest request) {
        List<LabNotifyplanVO> list =labNotifyplanMapper.selectLabNotifyplanListVO(labNotifyplan);
        InputStream intstream=null;
        try {
            //是否需要解析excel 标识 remark=1
            if(list.size()>0 && "1".equals(labNotifyplan.getRemark())){
                ExcelUtil<LabNotifyplanExcelVO> util = new ExcelUtil<LabNotifyplanExcelVO>(LabNotifyplanExcelVO.class);
                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);

                        if(list.get(0).getContentUrl()!=null) {
                            String baseUrl=request.getServerName() ;
                            String url="";
                            if(baseUrl.contains("192.168")){
                                url=fileConfigUtils.getLocalUrl()+list.get(0).getContentUrl();
                            }else{
                                url=fileConfigUtils.getRemoteUrl()+list.get(0).getContentUrl();
                            }
                            url= UrlFormatUtils.getHttpsORHttpUrl(url);

                            //文件访问路径
                            //String url = "http://192.168.1.17:9300//statics/2022/02/18/3d78b3c2-8108-4e78-a419-954e4b71a92a.xls";
                            intstream = new URL(url).openStream();
                            List<LabNotifyplanExcelVO> excelList = util.importExcel(intstream);
                            list.get(0).setExcelList(excelList);
                            intstream.close();
                        }
            }
        } catch (IOException e) {
            //e.printStackTrace();
            if(intstream!=null){
                try {
                    intstream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            throw new ServiceException("文件解析异常！");
        } catch (Exception e) {
            //e.printStackTrace();
            if(intstream!=null){
                try {
                    intstream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            throw new ServiceException("文件解析异常！");
        }
        return list;
    }

    public static void main(String[] args) throws ParseException {
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        Date date = (Date) sdf.parse("Sat Jan 01 10:20:00 CST 2022");
        String formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
       //String ss = sdf.format(Date.parse("Sat Jan 01 10:20:00 CST 2022"));
        System.out.println(formatStr);
    }
}
