package com.engine.htsc.hthy.web;

import com.alibaba.fastjson.JSONObject;
import com.api.doc.detail.util.DocDownloadCheckUtil;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.htsc.hthy.service.HtscMettingService;
import com.engine.htsc.hthy.service.impl.HhtscMeetingServiceImpl;
import org.eclipse.swt.custom.StyleRange;
import weaver.conn.RecordSet;
import weaver.docs.qc969424.util.QC969424RequestBaseUtil;
import weaver.docs.qc969424.util.QC969424SyncauthRequestUtil;
import weaver.docs.qc969424.util.QC969424Util;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

public class HtscMeetingAction {

    public HtscMettingService getService(HttpServletRequest request, HttpServletResponse response){
        User user = HrmUserVarify.getUser( request, response );
        return  (HtscMettingService) ServiceUtil.getService(HhtscMeetingServiceImpl.class,user);
    }

    @GET
    @Path("/updateHyZt")
    @Produces({MediaType.TEXT_PLAIN})
    public String updateHyZt(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            RecordSet rs = new RecordSet();
            Map<String,Object> param = ParamUtil.request2Map(request);
            String billid = Util.null2String(param.get("billid"));
            String zt = Util.null2String(param.get("zt"));
            if(!"".equals(billid) && !"".equals(zt)){
                String sql = " update uf_hywh set hyzt="+zt+" where id in("+billid+")";
                boolean flag = rs.execute(sql);
                if(flag){
                    apidatas.put("flag", "1");
                }else{
                    apidatas.put("flag", "0");
                }
            }
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/gethyqddata")
    @Produces({MediaType.TEXT_PLAIN})
    public String getHyqdData(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            Map<String,Object> param = ParamUtil.request2Map(request);
            apidatas.putAll(this.getService(request,response).getHyqdData(param));;
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/gethymbdata")
    @Produces({MediaType.TEXT_PLAIN})
    public String getHymbData(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            Map<String,Object> param = ParamUtil.request2Map(request);
            apidatas.putAll(this.getService(request,response).getHymbData(param));;
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/gethytzsj")
    @Produces({MediaType.TEXT_PLAIN})
    public String gethytzsj(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();

        RecordSet rs = new RecordSet();
        try {
            Map<String,Object> param = ParamUtil.request2Map(request);

            String hysj = Util.null2String(param.get("hysj"));
            String tqtzts = Util.null2String(Util.null2String(param.get("tqtzts")),"0");
            String tqlctzts = Util.null2String(Util.null2String(param.get("tqlctzts")),"0");

            String hytzsj = "";
            String hylctzsj = "" ;
            if(!"".equals(hysj)){

                String sql = "select to_char(to_date('"+hysj+"','yyyy-mm-dd hh24:mi')-"+tqtzts+",'yyyy-mm-dd hh24:mi') as hytzsj from dual" ;
                rs.execute(sql);
                if(rs.next()){
                    hytzsj = Util.null2String(rs.getString("hytzsj"));
                }

                sql = "select to_char(to_date('"+hysj+"','yyyy-mm-dd hh24:mi')-"+tqlctzts+",'yyyy-mm-dd hh24:mi') as hylctzsj from dual" ;
                rs.execute(sql);
                if(rs.next()){
                    hylctzsj = Util.null2String(rs.getString("hylctzsj"));
                }
            }

            apidatas.put("hytzsj",hytzsj);
            apidatas.put("hylctzsj",hylctzsj);
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/gethyxxbymail")
    @Produces({MediaType.TEXT_PLAIN})
    public String getHyxxByMail(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            Map<String,Object> param = ParamUtil.request2Map(request);
            apidatas.putAll(this.getService(request,response).getHyxxByMail(param));
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/updatechryzt")
    @Produces({MediaType.TEXT_PLAIN})
    public String updatechryzt(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        BaseBean bb = new BaseBean();

        try {
            RecordSet rs = new RecordSet();
            Map<String,Object> param = ParamUtil.request2Map(request);
            String billid = Util.null2String(param.get("billid"));
            String zt = Util.null2String(param.get("zt"));
            if(!"".equals(billid) && !"".equals(zt)){
                String sql = " update uf_hyxx set sfxs="+zt+" where id in("+billid+")";
                boolean flag = rs.execute(sql);
                if(flag) {

                    sql = " delete from uf_hymb_dt1 where xm in(" + billid + ") ";
                    boolean flag1 = rs.execute(sql);

                    sql = " delete from uf_hymb_dt2 where xm in(" + billid + ") ";
                    boolean flag12 = rs.execute(sql);

                    if (flag1 && flag12) {
                        apidatas.put("flag", "1");
                    } else {
                        apidatas.put("flag", "0");
                    }

                    if (!"".equals(billid)) {
                        String[] userid = billid.split(",");

                        for (int k = 0; k < userid.length; k++) {
                            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
                            Map<String, String> map = null;
                            sql = "  select * from uf_hymb where instr(','||hyzcrx||',',','||'"+userid[k]+"'||',')>0 ";
                            bb.writeLog("sql:" + sql);
                            rs.execute(sql);
                            while (rs.next()) {
                                map = new HashMap<String, String>();
                                String mbid = Util.null2String(rs.getString("id"));
                                String hylxxz = Util.null2String(rs.getString("hylxfzzd"));
                                map.put("mbid", mbid);
                                map.put("hylxxz", hylxxz);
                                list.add(map);
                            }
                            bb.writeLog("list:" + list.size());
                            for (int i = 0; i < list.size(); i++) {
                                Map<String, String> datamap = list.get(i);
                                String mbid = Util.null2String(datamap.get("mbid"));
                                String hylxxz = Util.null2String(datamap.get("hylxxz"));

                                bb.writeLog("mbid:" + mbid);
                                bb.writeLog("hylxxz:" + hylxxz);

                                List<String> dt3list = new ArrayList<String>();
                                rs.execute(" select hyzcr from uf_hyry_dt3  where mainid in (select id from uf_hyry where hylx = '" + hylxxz + "')");
                                while (rs.next()) {
                                    String hyzcr = Util.null2String(rs.getString("hyzcr"));
                                    dt3list.add(hyzcr);
                                }

                                String zhrids = "";
                                for (String hyzcr : dt3list) {
                                    rs.execute(" select id,zwx,yx,ryxm from uf_hyxx where sfxs = 0 and zwx = " + hyzcr);
                                    while (rs.next()) {
                                        String zhrid = Util.null2String(rs.getString("id"));
                                        zhrids += zhrids == "" ? zhrid : "," + zhrid;
                                    }
                                }
                                bb.writeLog("zhrids:" + zhrids);

                                sql = " update uf_hymb set hyzcrx='" + zhrids + "' where id=" + mbid;
                                bb.writeLog("sql:" + sql);
                                rs.executeUpdate(sql);
                            }
                        }
                    }
                }
            }
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/updatehylx")
    @Produces({MediaType.TEXT_PLAIN})
    public String updatehylx(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            RecordSet rs = new RecordSet();
            Map<String,Object> param = ParamUtil.request2Map(request);
            String billid = Util.null2String(param.get("billid"));
            String zt = Util.null2String(param.get("zt"));
            if(!"".equals(billid) && !"".equals(zt)){
                String sql = " update uf_hylx set sfxs="+zt+" where id in("+billid+")";
                boolean flag = rs.execute(sql);
                if(flag){
                    apidatas.put("flag", "1");
                }else{
                    apidatas.put("flag", "0");
                }
            }
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/updatehybq")
    @Produces({MediaType.TEXT_PLAIN})
    public String updatehybq(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            RecordSet rs = new RecordSet();
            Map<String,Object> param = ParamUtil.request2Map(request);
            String billid = Util.null2String(param.get("billid"));
            String zt = Util.null2String(param.get("zt"));
            if(!"".equals(billid) && !"".equals(zt)){
                String sql = " update uf_bq set sfxs="+zt+" where id in("+billid+")";
                boolean flag = rs.execute(sql);
                if(flag){
                    apidatas.put("flag", "1");
                }else{
                    apidatas.put("flag", "0");
                }
            }
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }



    @GET
    @Path("/sendMailbymetting")
    @Produces({MediaType.TEXT_PLAIN})
    public String sendMailbymetting(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            RecordSet rs = new RecordSet();
            Map<String,Object> param = ParamUtil.request2Map(request);
            apidatas.putAll(this.getService(request,response).sendMailByMeeting(param));;
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/gethyzt")
    @Produces({MediaType.TEXT_PLAIN})
    public String gethyzt(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            RecordSet rs = new RecordSet();
            Map<String,Object> param = ParamUtil.request2Map(request);
            String billid = Util.null2String(param.get("billid"));
            int count = 0;
            String sql = " select id from uf_hywh where id= " +billid+
                    " and substr(uf_hywh.hysj,0,10) >= to_char(sysdate,'yyyy-mm-dd') ";
            rs.execute(sql);
            if(rs.next()){
                count++;
            }

            if(count  >0){
                apidatas.put("hyzt", "1");
            }else{
                apidatas.put("hyzt", "0");
            }

            int dt4count = 0;
            sql = " select count(1) as cou from uf_hywh_dt4 where mainid="+billid ;
            rs.execute(sql);
            if(rs.next()){
                dt4count = Util.getIntValue(Util.null2String(rs.getString("cou")));
            }
            apidatas.put("dt4count", dt4count);

            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }




    @GET
    @Path("/download")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public Response downloadByField(@Context HttpServletRequest request, @Context HttpServletResponse response){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();
        String iszip = "";
        String imageFileName = "";
        String fileRealPath = "";
        String fileId = "" ;
        String wjmc = request.getParameter("wjid");
        bs.writeLog("wjmc:"+wjmc);
        String sql = "  select t1.fileid,t1.imageFileId,t1.imageFileName,t1.imageFileType,t1.imageFileUsed,t1.fileRealPath,t1.isZip,t1.isencrypt,t1.filesize,t1.downloads,t1.miniimgpath,t1.imgsize,t1.isFTP,t1.FTPConfigId,t1.isaesencrypt,t1.aescode,t1.tokenKey,t1.storageStatus,t1.comefrom,t2.imagefilename as realname  from ImageFile t1 inner join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t2.docid = '"+wjmc+"'";
        bs.writeLog("sql:"+sql);
        rs.execute(sql);
        if (rs.next())
        {
            fileId = Util.null2String(rs.getString("fileid"));
            imageFileName = Util.null2String(rs.getString("realname"));
            if (imageFileName.equals("")) {
                imageFileName = Util.null2String(rs.getString("imageFileName"));
            }
            fileRealPath = Util.null2String(rs.getString("fileRealPath"));
            iszip = Util.null2String(rs.getString("isZip"));
        }

        bs.writeLog("imageFileName:"+imageFileName);
        bs.writeLog("fileRealPath:"+fileRealPath);
        bs.writeLog("iszip:"+iszip);
        InputStream is = null;
        try {
            if(!"".equals(imageFileName)){
                try {
                    imageFileName = URLEncoder.encode(imageFileName.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            File file = new File(fileRealPath);
            if(file.exists())
            {
                if (iszip.equals("1")) {
                    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
                    if (zipInputStream.getNextEntry() != null) {
                        is = new BufferedInputStream(zipInputStream);
                    }
                } else {
                    is = new BufferedInputStream(new FileInputStream(file));
                }
            }else{
                if(!"".equals(fileId))
                {
                    boolean bool = QC969424Util.openQc969424();
                    bs.writeLog("bool:"+bool);
                    if (bool) {
                        QC969424RequestBaseUtil QC969424RequestBaseUtil = new QC969424RequestBaseUtil();
                        String token = QC969424Util.getToken();
                        if (token == null || "".equals(token)) {
                            QC969424RequestBaseUtil.getToken();
                        }
                        QC969424SyncauthRequestUtil qC969424SyncauthRequestUtil = new QC969424SyncauthRequestUtil();
                        is = qC969424SyncauthRequestUtil.download(fileId);
                    }
                }
            }

            return Response
                    .ok(is)
                    .header("Content-disposition","attachment;filename=" +imageFileName)
                    .header("ragma", "No-cache")
                    .header("Cache-Control", "no-cache").build();

        } catch (Exception e) {
            e.printStackTrace();
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }



    @GET
    @Path("/getWjid")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public String getWjid(@Context HttpServletRequest request, @Context HttpServletResponse response) {

        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            RecordSet rs = new RecordSet();
            Map<String,Object> param = ParamUtil.request2Map(request);
            String dtid = Util.null2String(param.get("dtid"));
            String wjids = "";

            if (!"".equals(dtid))
            {
                dtid = "'" + dtid.replace(",", "','") + "'";
                String sql = " select wjmc from UF_HYWH_DT5 t where t.id in(" + dtid + ")";
                rs.execute(sql);
                while (rs.next())
                {
                    String wjmc = Util.null2String(rs.getString("wjmc"));
                    wjids += wjids == "" ? wjmc : ","+wjmc ;
                }
            }
            String imagefileids = "" ;
            if(!"".equals(wjids))
            {
                String sql =" select l.* from ( \n" +
                        " select imagefileid, \n" +
                        " row_number() over(partition by docid order by imagefileid desc) as xh \n" +
                        " from docimagefile \n" +
                        " where docid in("+wjids+") \n" +
                        " ) l where l.xh=1 \n " ;

                rs.execute(sql);
                while (rs.next()){
                    String imagefileid = Util.null2String(rs.getString("imagefileid"));
                    String fileid = DocDownloadCheckUtil.checkPermission(imagefileid, null);
                    imagefileids += imagefileids == "" ? fileid : ","+fileid ;
                }
            }
            apidatas.put("imagefileids", imagefileids);
            apidatas.put("wjids", wjids);
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }

}
