package com.ruoyi.web.controller.system;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.framework.util.ShiroUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.GtgsYwUser;
import com.ruoyi.system.domain.Gtgsyw;
import com.ruoyi.system.domain.GtgsywPrintList;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.GtgsywPrintListService;
import com.ruoyi.system.service.IGtgsYwUserService;
import com.ruoyi.system.service.IGtgsywService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
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.*;

/**
 * @Author: Abeiv
 * @Description:
 * @Date: 2019-12-9 9:57
 */
@Controller()
@RequestMapping("/system/cprint")
public class CPrintController extends BaseController {
    private String prefix = "system/print";
    @Autowired
    private GtgsywPrintListService gtgsywPrintListService;
    @Autowired
    private IGtgsYwUserService gtgsYwUserService;
    @Autowired
    private IGtgsywService gtgsywService;


    @GetMapping("/syn")
    public String syn() {
        System.err.println(prefix + "/index");
        return prefix + "/index";
    }
    @GetMapping("/addinfo")
    public String addinfo() {

        return prefix + "/listInfo";
    }


    /**
     * 新增企业打印列表
     */
    @GetMapping("/getEwmImg")
    @ResponseBody
    public String getEwmImg(String xinyongCode)
    {

        return getImg(xinyongCode);
    }
    /**
     * 添加数据
     *
     * @return
     */
    @Log(title = "单条添加同步信息",businessType = BusinessType.INSERT)
    @PostMapping("/saveinfo")
    @ResponseBody
    public AjaxResult saveinfo(GtgsywPrintList gtgsywPrintList) {

        gtgsywPrintList.setBsid((UUID.randomUUID().toString()));
        String maxZzcode=gtgsywService.selectMaxZzCode();
        if(StringUtils.isEmpty(maxZzcode)){
            maxZzcode="0";
        }
        gtgsywPrintList.setZzcode(String.valueOf(Integer.parseInt(maxZzcode)+1));
        gtgsywPrintList.setIsprint(0);
        gtgsywPrintList.setIsprintF(0);
        gtgsywPrintList.setSczttype("个体工商户");
        gtgsywPrintList.setShenqinglaiyuan("后台添加");
        gtgsywPrintList.setShenherenname(ShiroUtils.getSysUser().getUserName());
        return toAjax(gtgsywPrintListService.insert(gtgsywPrintList));
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo getList(GtgsywPrintList gtgsywPrintList) {

        SysUser user=ShiroUtils.getSysUser();
        if(!user.isAdmin()){
            gtgsywPrintList.setShenherenname(user.getUserName());
        }
        startPage();
        List<GtgsywPrintList> l = gtgsywPrintListService.selectAll(gtgsywPrintList);
        return getDataTable(l);
    }

    @Log(title = "获取同步信息列表",businessType = BusinessType.OTHER)
    @PostMapping("/requestList")
    @ResponseBody
    public TableDataInfo requestList(@RequestParam("type") int type,@RequestParam("typeid") String typeid, @RequestParam("pageNum")String pageNum) {
        logger.debug("___________request____________________>"+getRequest().getParameter("pageNum"));
        SysUser user = ShiroUtils.getSysUser();
        GtgsYwUser gtgsYwUser=gtgsYwUserService.selectGtgsYwUserByRemark(user.getRemark());
        if(gtgsYwUser==null) {
            TableDataInfo a = new TableDataInfo();
            return a;
        }
        String userDetail = "&loginName=" + gtgsYwUser.getUsername() + "&password=" + gtgsYwUser.getPassword() + "&authId=" +
                gtgsYwUser.getAuthid() + "&loginDeptId=" + gtgsYwUser.getDetpid() + "&loginUserId=" + gtgsYwUser.getUserid();

        String data;
        if(type==0){
            data = HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/getWindList", "pageNum="+getRequest().getParameter("pageNum")+"&appTypeId="+typeid+userDetail);
        }else{
            data = HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/getOnlineWindList", "pageNum="+getRequest().getParameter("pageNum")+"&appTypeId="+typeid+userDetail);
        }
        Map<String, Object> m = (Map<String, Object>) JSONUtils.parse(data);
        TableDataInfo td = new TableDataInfo();
        td.setTotal(Integer.parseInt(m.get("total") + ""));
        td.setCode(0);
        List<Map> l = (List<Map>) m.get("data");
        List<GtgsywPrintList> rows = new ArrayList<GtgsywPrintList>();
        for (int i = 0; i < l.size(); i++) {
            GtgsywPrintList gpt = new GtgsywPrintList();
            gpt.setBsid(UUID.randomUUID().toString());
            gpt.setJingyingren(l.get(i).get("master") + "");
            gpt.setZwzh(l.get(i).get("name") + "");
            gpt.setAppno(l.get(i).get("appNo") + "");
            gpt.setShenqingdate(l.get(i).get("date") + "");
            gpt.setEcode(l.get(i).get("toUrl") + "");
            rows.add(gpt);
        }
        td.setRows(rows);
        System.err.println(rows.toString());
        return td;
    }
    @Log(title = "获取同步信息",businessType = BusinessType.OTHER)
    @PostMapping("/requestInfo")
    @ResponseBody
    public AjaxResult getInfo(String toUrl, String uuid) {
        SysUser user = ShiroUtils.getSysUser();
        GtgsYwUser gtgsYwUser=gtgsYwUserService.selectGtgsYwUserByRemark(user.getRemark());

        if (!StringUtils.isEmpty(toUrl)) {
            String userDetail="&loginName="+gtgsYwUser.getUsername()+"&password="+gtgsYwUser.getPassword()+"&authId="+
                    gtgsYwUser.getAuthid()+"&loginDeptId="+gtgsYwUser.getDetpid()+"&loginUserId="+gtgsYwUser.getUserid();
            String data = HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/getinfo", "appNo=" + toUrl+userDetail);
            Map<String, String> m = (Map<String, String>) JSONUtils.parse(data);
            GtgsywPrintList gpt = new GtgsywPrintList();
            gpt.setXinyongcode(StringUtils.trim(m.get("code")));
            gpt.setJingyingren(StringUtils.trim(m.get("master")));
            gpt.setZwzh(StringUtils.trim(m.get("name")));
            gpt.setZuchengxingshi(StringUtils.trim(m.get("formation")));
            gpt.setJingyingchangsuo(StringUtils.trim(m.get("address")));
            gpt.setJingyingfanwei(StringUtils.trim(m.get("range")));
            gpt.setZhucetime(DateUtils.parseDate(StringUtils.trim(m.get("date"))));
            gpt.setJingyingcard(StringUtils.trim(m.get("cetfNoOperator")));
            gpt.setXingbie(StringUtils.trim(m.get("sexIdOperator")));
            gpt.setJingyingcard(StringUtils.trim(m.get("cetfNoOperator")));
            gpt.setJiatingzhuzhi(StringUtils.trim(m.get("addressOperator")));
            gpt.setJingyingrenphone(StringUtils.trim(m.get("phone")));
            return success(JSONObject.toJSONString(gpt));
        } else {
            GtgsywPrintList gpt = gtgsywPrintListService.selectByPrimaryKey(uuid);
            return success(JSONObject.toJSONString(gpt));
        }
    }


    @GetMapping("/getInfo")
    public String getInfoHtml(Model mav, String url, String bsid) {
        String pageName;
        if (!StringUtils.isEmpty(url)) {
            mav.addAttribute("url", url);
            pageName = prefix + "/info";
        } else {
            mav.addAttribute("bsid", bsid);
            pageName = prefix + "/listInfo";
        }
        return pageName;
    }

    /**
     * 添加数据
     *
     * @return
     */
    @Log(title = "单条添加同步信息",businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(String shenqingdate, String bsid, String url, String typeid,String type, String appNo) throws UnsupportedEncodingException {

        String isBsid= gtgsywPrintListService.selectByAppNo(appNo);
        if(StringUtils.isNotEmpty(isBsid)){
            return AjaxResult.warn("请勿重复下载");
        }
        SysUser user = ShiroUtils.getSysUser();
        GtgsYwUser gtgsYwUser=gtgsYwUserService.selectGtgsYwUserByRemark(user.getRemark());
        String data = HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/getinfo", "appNo=" + URLEncoder.encode(appNo,"utf-8")+"&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(data);
        GtgsywPrintList gpt = new GtgsywPrintList();
        gpt.setXinyongcode(StringUtils.trim(m.get("code")));
        gpt.setJingyingren(StringUtils.trim(m.get("master")));
        gpt.setZwzh(StringUtils.trim(m.get("name")));
        gpt.setZuchengxingshi(StringUtils.trim(m.get("formation")));
        gpt.setJingyingchangsuo(StringUtils.trim(m.get("address")));
        gpt.setJingyingfanwei(StringUtils.trim(m.get("range")));
        gpt.setShenherenname(user.getUserName());
        gpt.setShenqingdate(shenqingdate);
        gpt.setZhucetime(DateUtils.parseDate(StringUtils.trim(m.get("date"))));
        System.err.println("date:---->"+m.get("date"));
        gpt.setBsid(bsid);
        gpt.setJingyingcard(StringUtils.trim(m.get("cetfNoOperator")));
        gpt.setXingbie(StringUtils.trim(m.get("sexIdOperator")));
        gpt.setJingyingcard(StringUtils.trim(m.get("cetfNoOperator")));
        gpt.setJiatingzhuzhi(StringUtils.trim(m.get("addressOperator")));
        gpt.setJingyingrenphone(StringUtils.trim(m.get("phone")));
        gpt.setIsprint(0);
        gpt.setAppno(appNo);
        gpt.setIsprintF(0);
        gpt.setSczttype("个体工商户");
        gpt.setErweimabase64(getImg(StringUtils.trim(m.get("code"))));
        gpt.setUpdateTime(DateUtils.getNowDate());
        gpt.setShenhedate(DateUtils.getNowDate());
        gpt.setUpdatetime(DateUtils.getNowDate());
        if(type.equals("0")){
            if(typeid.equals("02")){
                gpt.setShenqinglaiyuan("窗口数据下载(设立)");
            }else {
                gpt.setShenqinglaiyuan("窗口数据下载(变更)");
            }
        }else {
            if(typeid.equals("02")){
                gpt.setShenqinglaiyuan("云窗在线数据下载(设立)");
            }else {
                gpt.setShenqinglaiyuan("云窗在线数据下载(变更)");
            }
        }
        String maxZzcode=gtgsywService.selectMaxZzCode();
        if(StringUtils.isEmpty(maxZzcode)){
            maxZzcode="0";
        }
        gpt.setZzcode(String.valueOf(Integer.parseInt(maxZzcode)+1));
        gtgsywPrintListService.insert(gpt);
        return success("添加成功");
    }

    @GetMapping("/getList")
    public String ListHtml(@RequestParam("type") int type, @RequestParam("typeid") String typeid, ModelMap modelMap) {
        modelMap.put("type",type);
        modelMap.put("typeid",typeid);
        return prefix + "/list";
    }

    @Log(title = "证照打印删除", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(gtgsywPrintListService.deleteGtgsywByIds(ids));
    }

    /**
     * 批量添加数据
     *
     * @return
     */
    @Log(title = "多条添加同步信息", businessType = BusinessType.INSERT)
    @PostMapping("/addAll")
    @ResponseBody
    public AjaxResult addAll(String data) {
        List<Map<String, String>> l = (List<Map<String, String>>) JSONUtils.parse(data);
        SysUser user = ShiroUtils.getSysUser();
        GtgsYwUser gtgsYwUser=gtgsYwUserService.selectGtgsYwUserByRemark(user.getRemark());
        int a = 0;
        for (int i = 0; i < l.size(); i++) {
            if(StringUtils.isEmpty(l.get(i).get("appno"))){
                continue;
            }
            String isBsid= gtgsywPrintListService.selectByAppNo(String.valueOf(StringUtils.isEmpty(l.get(i).get("appno"))));
            if(StringUtils.isNotEmpty(isBsid)){
                continue;
            }
            String msg;
            try {
                msg = HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/getinfo", "appNo=" + URLEncoder.encode(l.get(i).get("appno"),"utf-8")+"&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);
            GtgsywPrintList gpt = new GtgsywPrintList();
            gpt.setXinyongcode(StringUtils.trim(m.get("code")));
            gpt.setJingyingren(StringUtils.trim(m.get("master")));
            gpt.setShenherenname(user.getUserName());
            gpt.setZwzh(StringUtils.trim(m.get("name")));
            gpt.setZuchengxingshi(StringUtils.trim(m.get("formation")));
            gpt.setJingyingchangsuo(StringUtils.trim(m.get("address")));
            gpt.setJingyingfanwei(StringUtils.trim(m.get("range")));
            gpt.setShenqingdate(l.get(i).get("shenqingdate"));
            gpt.setZhucetime(DateUtils.parseDate(StringUtils.trim(m.get("date"))));
            gpt.setBsid(l.get(i).get("bsid"));
            gpt.setJingyingcard(StringUtils.trim(m.get("cetfNoOperator")));
            gpt.setXingbie(StringUtils.trim(m.get("sexIdOperator")));
            gpt.setJingyingcard(StringUtils.trim(m.get("cetfNoOperator")));
            gpt.setJiatingzhuzhi(StringUtils.trim(m.get("addressOperator")));
            gpt.setJingyingrenphone(StringUtils.trim(m.get("phone")));
            gpt.setIsprint(0);
            gpt.setAppno(l.get(i).get("appno"));
            gpt.setIsprintF(0);
            gpt.setSczttype("个体工商户");
            gpt.setErweimabase64(getImg(StringUtils.trim(m.get("code"))));
            gpt.setUpdateTime(DateUtils.getNowDate());
            gpt.setShenhedate(DateUtils.getNowDate());
            gpt.setUpdatetime(DateUtils.getNowDate());
            String maxZzcode=gtgsywService.selectMaxZzCode();
            if(StringUtils.isEmpty(maxZzcode)){
                maxZzcode="0";
            }
            gpt.setZzcode(String.valueOf(Integer.parseInt(maxZzcode)+1));
            a += gtgsywPrintListService.insertSelective(gpt);
        }
        return toAjax(a);
    }

    @Log(title = "修改抓取个体工商户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updata")
    @ResponseBody
    public AjaxResult updata(GtgsywPrintList gpt){
        logger.debug(gpt.toString());
        return toAjax(gtgsywPrintListService.updateByPrimaryKeySelective(gpt));
    }

    @GetMapping("/MyDemoTest")
    public String MyDemoTest() {
        return "/demo/demo";
    }



    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;
    }




}
