package com.ruoyi.web.controller.system;

import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.GtgsYwUser;
import com.ruoyi.system.domain.QyInfoPritn;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.IGtgsYwUserService;
import com.ruoyi.system.service.IQyInfoPritnService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * 企业打印列表Controller
 *
 * @author ruoyi
 * @date 2020-01-10
 */
@Controller
@RequestMapping("/system/qypritn")
public class QyInfoPritnController extends BaseController
{
    private String prefix = "system/qypritn";

    @Autowired
    private IQyInfoPritnService qyInfoPritnService;
    @Autowired
    private IGtgsYwUserService gtgsYwUserService;
    @GetMapping()
    public String pritn()
    {
        return prefix + "/pritn";
    }

    /**
     * 查询企业打印列表列表
     */
    @RequiresPermissions("system:pritn:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(QyInfoPritn qyInfoPritn)
    {
        //当前登录的用户
        SysUser user= ShiroUtils.getSysUser();
//        qyInfoPritn.setShenhenameid(user.getUserId().toString());
        if(!user.isAdmin()){
            qyInfoPritn.setShenhename(user.getUserName());
        }
        startPage();
        List<QyInfoPritn> list = qyInfoPritnService.selectQyInfoPritnList(qyInfoPritn);
        return getDataTable(list);
    }

    /**
     * 导出企业打印列表列表
     */
    @RequiresPermissions("system:pritn:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(QyInfoPritn qyInfoPritn)
    {
        List<QyInfoPritn> list = qyInfoPritnService.selectQyInfoPritnList(qyInfoPritn);
        ExcelUtil<QyInfoPritn> util = new ExcelUtil<QyInfoPritn>(QyInfoPritn.class);
        return util.exportExcel(list, "pritn");
    }

    /**
     * 新增企业打印列表
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }







    /**
     * 新增保存企业打印列表
     */
    @RequiresPermissions("system:pritn:add")
    @Log(title = "企业打印列表", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(QyInfoPritn qyInfoPritn)
    {
        SysUser user = ShiroUtils.getSysUser();
        String maxZzcode=qyInfoPritnService.selectMaxZzCode();
        if(StringUtils.isEmpty(maxZzcode)){
            maxZzcode="0";
        }
        qyInfoPritn.setZzcode(String.valueOf(Integer.parseInt(maxZzcode)+1));
        qyInfoPritn.setShenhename(user.getUserName());
        qyInfoPritn.setShenhenameid(user.getUserId().toString());
        qyInfoPritn.setBsid(UUID.randomUUID().toString().replaceAll("-",""));
        qyInfoPritn.setZhucehao(UUID.randomUUID().toString().replaceAll("-",""));
        qyInfoPritn.setFlg("2");
        qyInfoPritn.setCreatedate(new Date());
        qyInfoPritn.setShenhedate(new Date());
        return toAjax(qyInfoPritnService.insertQyInfoPritn(qyInfoPritn));
    }

    /**
     * 修改企业打印列表
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        QyInfoPritn qyInfoPritn = qyInfoPritnService.selectQyInfoPritnById(id);
        mmap.put("qyInfoPritn", qyInfoPritn);
        return prefix + "/edit";
    }

    /**
     * 修改保存企业打印列表
     */
    @RequiresPermissions("system:pritn:edit")
    @Log(title = "企业打印列表", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(QyInfoPritn qyInfoPritn)
    {
        return toAjax(qyInfoPritnService.updateQyInfoPritn(qyInfoPritn));
    }

    /**
     * 删除企业打印列表
     */
    @RequiresPermissions("system:pritn:remove")
    @Log(title = "企业打印列表", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(qyInfoPritnService.deleteQyInfoPritnByIds(ids));
    }

    /**
     * 现在档案
     */
    @GetMapping( "/Download")
    @ResponseBody
    public AjaxResult qyprint()
    {
        String data= HttpUtils.sendGet("http://localhost:5000/","");
        return AjaxResult.success("ok",data);
    }

    /**
     * 档案
     */
    @GetMapping( "/qylist")
    public String qylist(String type,String typeid,ModelMap modelMap)
    {
        modelMap.put("type",type);
        modelMap.put("typeid",typeid);
        return prefix+"/qylist";
    }
    /**
     * 查看详细信息
     */
    @GetMapping( "/getQyInfo")
    public String getQyInfo(String sqh,String type,String typeid,String qylx,ModelMap modelMap) throws UnsupportedEncodingException {
        if(type.equals("0")){
            modelMap.put("qyInfoPritn",  qyInfoPritnService.selectBySqh(sqh));
        }else {
            GtgsYwUser gtgsYwUser=gtgsYwUserService.selectGtgsYwUserByRemark(ShiroUtils.getSysUser().getRemark());
            String msg;
//            msg="{\"Qywtrxm\": \"张丽娟\", \"WtrCardNo\": \"130124198703094560\", \"QyName\": \"石家庄正广通物业管理有限公司\", \"QyLx\": \"内资企业\", \"Qyjyfw\": \"物业管理。物业服务、停车场管理服务、保洁服务；房屋修缮；园林绿化养护；房屋租赁、汽车租赁；仓储服务（危险化学品、易燃易爆品除外）；企业管理咨询（金融、证券、期货、投资、教育咨询除外。（依法须经批准的项目，经相关部门批准后方可开展经营活动）**\", \"Qyjycs\": \"河北省石家庄市栾城区樊家屯人大路156号\", \"Qyclrq\": \"2020-06-01\", \"Qyyyqz\": \"2020-06-01 至 长期\", \"Qyzczj\": \"10.000000 万人民币\", \"xinyongCode\": \"91130124MA0F1X719C\"}";
            msg = HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/slxx", "appNo=" + URLEncoder.encode(String.valueOf(sqh),"utf-8")+"&appTypeId="+typeid+"&loginName=" +
                    URLEncoder.encode( gtgsYwUser.getUsername(),"utf-8")+"&password="+ URLEncoder.encode(gtgsYwUser.getPassword(),"utf-8")+"&loginUserId="+
                    URLEncoder.encode(gtgsYwUser.getUserid(),"utf-8")+"&loginDeptId="+ URLEncoder.encode(gtgsYwUser.getDetpid(),"utf-8"));
            Map<String, String> m = (Map<String, String>) JSONUtils.parse(msg);
            QyInfoPritn qyInfoPritn = new QyInfoPritn();
            qyInfoPritn.setBsid(UUID.randomUUID().toString());
            qyInfoPritn.setFrname(StringUtils.trim(m.get("FrName") + ""));
            qyInfoPritn.setWtrcardno(StringUtils.trim(m.get("WtrCardNo")+""));
            qyInfoPritn.setQylx(m.get("Qylx")+"");
            switch (qylx){
                case "内资公司":qyInfoPritn.setQylb("1");
                    break;
                case "内资分公司":qyInfoPritn.setQylb("2");
                    break;
                case "内资非公司企业法人":qyInfoPritn.setQylb("3");
                    break;
                case "内资非公司企业法人分支机构":qyInfoPritn.setQylb("4");
                    break;
                case "个人独资企业":qyInfoPritn.setQylb("5");
                    break;
                case "个人独资企业分支机构":qyInfoPritn.setQylb("6");
                    break;
                case "合伙企业":qyInfoPritn.setQylb("7");
                    break;
                case "合伙企业分支机构":qyInfoPritn.setQylb("8");
                    break;
                case "农民专业合作社":qyInfoPritn.setQylb("9");
                    break;
                case "农民专业合作社分支机构":qyInfoPritn.setQylb("10");
                    break;
                default :
                    qyInfoPritn.setQylb("1");
                    System.out.println("未知等级");
            }


            qyInfoPritn.setQyjyfw(StringUtils.trim(m.get("Qyjyfw")+""));
            qyInfoPritn.setQyjycs(StringUtils.trim(m.get("Qyjycs")+""));
            qyInfoPritn.setQyclrq(DateUtils.parseDate(StringUtils.trim(m.get("Qyclrq"))));
            qyInfoPritn.setQyname(StringUtils.trim(m.get("QyName") + ""));
            if (StringUtils.trim(m.get("Qyyyqz")).indexOf("长期")!=-1) {
                qyInfoPritn.setQyjyqx("长期");
            } else if (!m.get("Qyyyqz").equals("")){
                qyInfoPritn.setQyyyqz(DateUtils.parseDate(StringUtils.trim(m.get("Qyyyqz")).substring(13,m.get("Qyyyqz").length())));
            }
            qyInfoPritn.setQynx(StringUtils.trim(m.get("Qyyyqz")));

            qyInfoPritn.setZhucehao(StringUtils.trim(sqh));
            qyInfoPritn.setQyzczj(StringUtils.trim(m.get("Qyzczj") + "").replace(" 万人民币",""));
            qyInfoPritn.setXinyongcode(StringUtils.trim(m.get("xinyongCode") + ""));
            qyInfoPritn.setErweimabase64(getImg(StringUtils.trim(m.get("xinyongCode") + "")));
            qyInfoPritn.setShenhename(ShiroUtils.getSysUser().getUserName());
            qyInfoPritn.setShenhedate(new Date());
            qyInfoPritn.setFlg("2");
            modelMap.put("qyInfoPritn",qyInfoPritn);
        }
        return prefix+"/edit";
    }




    /**
     * 企业信息列表
     * type : 1-云窗 2-网上预申报 3- 窗口办理
     */
    @PostMapping( "/index")
    @ResponseBody
    public TableDataInfo index(@RequestParam("type")String type, @RequestParam("typeid")String typeid, @RequestParam("pageNum")String pageNum)
    {
        TableDataInfo td = new TableDataInfo();
        SysUser user = ShiroUtils.getSysUser();
        GtgsYwUser gtgsYwUser=gtgsYwUserService.selectGtgsYwUserByRemark(user.getRemark());
        if(gtgsYwUser==null){
            return  td;
        }
        String userDetwail="&loginName="+gtgsYwUser.getUsername()+"&password="+gtgsYwUser.getPassword()+"&authId="+
                gtgsYwUser.getAuthid()+"&loginDeptId="+gtgsYwUser.getDetpid()+"&loginUserId="+gtgsYwUser.getUserid();
        String data;
            data= HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/sllb","type="+type+"&appTypeId="+typeid+"&pageNo="+pageNum+userDetwail);
//            data="{\"data\": [{\"sqh\": \"13012403202005280020\", \"qymc\": \"河北安邦供应链管理有限公司\", \"qylx\": \"内资公司\", \"djlx\": \"变更登记\", \"sqrq\": \"2020-05-28 14:01:45\", \"sljg\": \"栾城区市场监督管理局\", \"zt\": \"核准通过\"},{\"sqh\": \"13012403202005280020\", \"qymc\": \"河北安邦供应链管理有限公司\", \"qylx\": \"内资公司\", \"djlx\": \"变更登记\", \"sqrq\": \"2020-05-28 14:01:45\", \"sljg\": \"栾城区市场监督管理局\", \"zt\": \"核准通过\"}], \"page\": \"2\", \"code\": \"0\"}";
       if(data.equals("")){
           return  td;
       }
        Map<String, Object> m = (Map<String, Object>) JSONUtils.parse(data);
        System.out.println("Code:"+m.get("code"));
        if(m.get("code").equals("302")){
            return td;
        }
        List<Map> l = (List<Map>) m.get("data");

        td.setTotal(Integer.parseInt(m.get("page") + ""));
        td.setCode(0);
        List<QyInfoPritn> rows = new ArrayList<QyInfoPritn>();
        for (int i = 0; i < l.size(); i++) {
            QyInfoPritn gpt = new QyInfoPritn();
            gpt.setBsid(UUID.randomUUID().toString());
            gpt.setQylx(l.get(i).get("qylx") + "");
            gpt.setQyname(l.get(i).get("qymc") + "");
            gpt.setZhucehao(l.get(i).get("sqh") + "");
            gpt.setLaiyuan(l.get(i).get("sljg") + "");
            gpt.setCreatedate(DateUtils.parseDate(l.get(i).get("sqrq")));
            rows.add(gpt);
        }
        td.setRows(rows);
        return td;
    }




    /**
     * 企业信息下载
     */
    @PostMapping( "/downQyinfo")
    @ResponseBody
    public AjaxResult downQyinfo(String data){

        List<Map<String, String>> list=(List<Map<String, String>>) JSONUtils.parse(data);
        SysUser user = ShiroUtils.getSysUser();
        GtgsYwUser gtgsYwUser=gtgsYwUserService.selectGtgsYwUserByRemark(user.getRemark());
        int a=0;
        for (Map li:list) {
            if(StringUtils.isEmpty(String.valueOf(li.get("sqh")))){
                continue;
            }
            String isBsid= qyInfoPritnService.selectByAppNo(String.valueOf(li.get("sqh")));
            System.out.println("是否已存在"+isBsid);
            if(StringUtils.isNotEmpty(isBsid)){
                continue;
            }
            String msg;
            try {
//                msg="{\"Qywtrxm\": \"张丽娟\", \"FrName\": \"李春\",\"WtrCardNo\": \"130124198703094560\", \"QyName\": \"石家庄正广通物业管理有限公司\", \"QyLx\": \"内资企业\", \"Qyjyfw\": \"物业管理。物业服务、停车场管理服务、保洁服务；房屋修缮；园林绿化养护；房屋租赁、汽车租赁；仓储服务（危险化学品、易燃易爆品除外）；企业管理咨询（金融、证券、期货、投资、教育咨询除外。（依法须经批准的项目，经相关部门批准后方可开展经营活动）**\", \"Qyjycs\": \"河北省石家庄市栾城区樊家屯人大路156号\", \"Qyclrq\": \"2020-06-01\", \"Qyyyqz\": \"2020-06-01 至 长期\", \"Qyzczj\": \"10.000000 万人民币\", \"xinyongCode\": \"91130124MA0F1X719C\"}";
                msg = HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/slxx", "appNo=" + URLEncoder.encode(String.valueOf(li.get("sqh")),"utf-8")+"&appTypeId="+li.get("typeid")+"&loginName=" +
                        URLEncoder.encode( gtgsYwUser.getUsername(),"utf-8")+"&password="+ URLEncoder.encode(gtgsYwUser.getPassword(),"utf-8")+"&loginUserId="+
                        URLEncoder.encode(gtgsYwUser.getUserid(),"utf-8")+"&loginDeptId="+ URLEncoder.encode(gtgsYwUser.getDetpid(),"utf-8"));
            } catch (Exception e) {
                msg = "error: "+ e.getMessage();
                logger.error("error: "+ e.getMessage());
            }


            Map<String, String> m = (Map<String, String>) JSONUtils.parse(msg);
            QyInfoPritn qyInfoPritn = new QyInfoPritn();
            qyInfoPritn.setBsid(UUID.randomUUID().toString());
            qyInfoPritn.setFrname(StringUtils.trim(m.get("FrName") + ""));
            qyInfoPritn.setWtrcardno(StringUtils.trim(m.get("WtrCardNo")+""));
            qyInfoPritn.setQylx(m.get("Qylx")+"");
            switch (String.valueOf(li.get("qylx"))){
                case "内资公司":qyInfoPritn.setQylb("1");
                    break;
                case "内资分公司":qyInfoPritn.setQylb("2");
                    break;
                case "内资非公司企业法人":qyInfoPritn.setQylb("3");
                    break;
                case "内资非公司企业法人分支机构":qyInfoPritn.setQylb("4");
                    break;
                case "个人独资企业":qyInfoPritn.setQylb("5");
                    break;
                case "个人独资企业分支机构":qyInfoPritn.setQylb("6");
                    break;
                case "合伙企业":qyInfoPritn.setQylb("7");
                    break;
                case "合伙企业分支机构":qyInfoPritn.setQylb("8");
                    break;
                case "农民专业合作社":qyInfoPritn.setQylb("9");
                    break;
                case "农民专业合作社分支机构":qyInfoPritn.setQylb("10");
                    break;
                default :
                    qyInfoPritn.setQylb("1");
                    System.out.println("未知等级");
            }
            qyInfoPritn.setQyjyfw(StringUtils.trim(m.get("Qyjyfw")+""));
            qyInfoPritn.setQyjycs(StringUtils.trim(m.get("Qyjycs")+""));
            qyInfoPritn.setQyclrq(DateUtils.parseDate(StringUtils.trim(m.get("Qyclrq"))));
            qyInfoPritn.setQyname(StringUtils.trim(m.get("QyName") + ""));
            if(li.get("typeid").equals("02")){
                if(li.get("type").equals("tabs-3")){
                    qyInfoPritn.setLaiyuan("窗口收件代办(设立)");
                }else if(li.get("type").equals("tabs-4")){
                    qyInfoPritn.setLaiyuan("全程电子化申请(设立)");
                }else if(li.get("type").equals("tabs-7")){
                    qyInfoPritn.setLaiyuan("一窗通(设立)");
                }
            }else {
                if(li.get("type").equals("tabs-3")){
                    qyInfoPritn.setLaiyuan("窗口收件代办(变更)");
                }else if(li.get("type").equals("tabs-4")){
                    qyInfoPritn.setLaiyuan("全程电子化申请(变更)");
                }else if(li.get("type").equals("tabs-5")){
                    qyInfoPritn.setLaiyuan("网上预申报(变更)");
                }
            }
            if (StringUtils.trim(m.get("Qyyyqz")).indexOf("长期")!=-1) {
                qyInfoPritn.setQyjyqx("长期");
            } else if(!m.get("Qyyyqz").equals("")){
                qyInfoPritn.setQyyyqz(DateUtils.parseDate(StringUtils.trim(m.get("Qyyyqz")).substring(13,m.get("Qyyyqz").length())));
            }
            qyInfoPritn.setQynx(StringUtils.trim(m.get("Qyyyqz")));
            qyInfoPritn.setZhucehao(StringUtils.trim(li.get("sqh") + ""));
            qyInfoPritn.setQyzczj(StringUtils.trim(m.get("Qyzczj") + "").replace(" 万人民币",""));
            qyInfoPritn.setXinyongcode(StringUtils.trim(m.get("xinyongCode") + ""));

            String maxZzcode=qyInfoPritnService.selectMaxZzCode();
            if(StringUtils.isEmpty(maxZzcode)){
                maxZzcode="0";
            }
            qyInfoPritn.setZzcode(String.valueOf(Integer.parseInt(maxZzcode)+1));

            qyInfoPritn.setErweimabase64(getImg(StringUtils.trim(m.get("xinyongCode") + "")));
//            qyInfoPritn.setLaiyuan(StringUtils.trim(li.get("sqly") + ""));
            qyInfoPritn.setShenhename(ShiroUtils.getSysUser().getUserName());
            qyInfoPritn.setCreatedate(DateUtils.parseDate(StringUtils.trim(String.valueOf(li.get("sqrq")))));
            qyInfoPritn.setShenhedate(new Date());
            qyInfoPritn.setFlg("2");
            a+=qyInfoPritnService.insertQyInfoPritn(qyInfoPritn);
        }
     return toAjax(a);

    }


    private static String strNetImageToBase64;
    public static String getImg(String xycode){
        String urlgs=Global.getConfig("ruoyi.gsdz")+":8005/gtdj/licence.do?method=toTowDimCode&appNo=&uniScid="+xycode+"&certTypeId=41";
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(urlgs);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            try {
                InputStream is = conn.getInputStream();
                // 将内容读取内存中
                System.err.println(111);
                int len = -1;
                while ((len = is.read(by)) != -1) {
                    data.write(by, 0, len);
                }
                System.err.println(222);
                // 对字节数组Base64编码
                BASE64Encoder encoder = new BASE64Encoder();
                strNetImageToBase64 = encoder.encode(data.toByteArray());
                System.out.println("网络图片转换Base64:" + strNetImageToBase64);
                // 关闭流
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  strNetImageToBase64;
    }











}
