package com.ruoyi.web.controller.Ytj;


import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.QyInfo;
import com.ruoyi.system.domain.QyInfoPritn;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.service.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import static com.ruoyi.common.utils.ImgUtils.Base64ToImage;
import static com.ruoyi.web.controller.tool.Moneytarnfrom.*;

@Controller
@RequestMapping("/Ytj/qyPrint")
public class QygsPrinterController extends BaseController {

    private String prefix = "Ytj/qyPrint";

    @Autowired
    private IQyInfoService qyInfoService;
    @Autowired
    private IQyInfoPritnService qyInfoPritnService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 打开功能列表
     *
     * @return 页面
     */
    @GetMapping()
    public String index(ModelMap modelMap) {
        modelMap.put("city", Global.getCityName());
        return "Ytj/allIndex";
    }

    /**
     * 打开功能列表
     *
     * @return 页面
     */
    @GetMapping("/qycanvasbg")
    public String qycanvasbg() {
        return "Ytj/qycanvasbg";
    }

    /**
     * 打开刷身份证页面
     *
     * @return 页面
     */
    @GetMapping("/qyRead")
    public String read(Model model) {
        model.addAttribute("city", Global.getCityName());
        return prefix + "/shuaPrint";
    }

    /**
     * 打开刷身份证页面
     *
     * @return 页面
     */
    @GetMapping("/PrintHtml")
    public String PrintHtml(@RequestParam("JingYingCard") String wtcd, Model model) {
        model.addAttribute("city", Global.getCityName());
        return prefix + "/PrintHtml";
    }

    /**
     * 打开刷身份证页面
     *
     * @return 页面
     */
    @GetMapping("/CheckRen")
    public String CheckRen(@RequestParam("JingYingCard") String wtcd, @RequestParam("BSID") String bsid, Model model) {
        model.addAttribute("city", Global.getCityName());
        model.addAttribute("rzdbsocre", Global.getConfig("ruoyi.rzdbsocre"));
        return prefix + "/CheckRen";
    }

    /**
     * 打开刷身份证页面
     *
     * @return 页面
     */
    @GetMapping("/Index")
    public String sfzList(@RequestParam("JingYingCard") String wtcd, Model model) {
        model.addAttribute("city", Global.getCityName());
        model.addAttribute("rzdbsocre", Global.getConfig("ruoyi.rzdbsocre"));
        return prefix + "/Index";
    }

    /**
     * 读取身份证后调取
     *
     * @param request
     * @return 是否存在企业信息
     */
    @PostMapping("/GetData")
    @ResponseBody
    public AjaxResult GetData(HttpServletRequest request) {

        String card = request.getParameter("JingYingCard");
        List<QyInfo> data = qyInfoService.selectQyInfoByCard(card);
        List<QyInfoPritn> qyPrints = qyInfoPritnService.selectQyInfoPritnC(card);
        if (data.size() > 0) {
            return AjaxResult.success("存在的企业信息", data);
        } else {
            return AjaxResult.warn("不存在企业信息", qyPrints);
        }
    }

    /**
     * 打印列表页显示
     *
     * @param
     * @return
     */
    @PostMapping("/GetIndexList")
    @ResponseBody
    public AjaxResult GetIndexList(@RequestParam("SFZ") String card) {

        List<QyInfo> qyInfos = qyInfoService.selectQyInfoByCard(card);
        List<QyInfoPritn> qyPrints = qyInfoPritnService.selectQyInfoPritnC(card);
        for (QyInfoPritn qyp : qyPrints) {
            QyInfo q = new QyInfo();
            q.setQyname(qyp.getQyname());
            q.setBsid(qyp.getBsid());
            q.setFrname(qyp.getFrname());
            q.setXinyongcode(qyp.getXinyongcode());
            q.setIsprintZ(qyp.getIsprintZ());
            q.setIsprintF(qyp.getIsprintF());
            q.setCreatedate(qyp.getCreatedate());
            q.setFlg(qyp.getFlg());
            q.setShenhenote(qyp.getShenhenote());
            qyInfos.add(q);
        }
        if (qyInfos.size() > 0) {
            return AjaxResult.success("存在的企业信息", qyInfos);
        } else {
            return AjaxResult.warn("不存在企业信息");
        }
    }

    /**
     * 更新领取人信息
     *
     * @param
     * @return
     */
    @PostMapping("/UpQyinfo")
    @ResponseBody
    public AjaxResult UpQyinfo(QyInfo info, HttpServletRequest request) {

        String lqrpz= "/QySqImg/"+ DateUtils.datePaths()+"/" + UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        if(Base64ToImage(request.getParameter("lqrphoto"),Global.getProfile()+lqrpz)){
            lqrpz="/profile"+lqrpz;
        }
        String lqrqm= "/QySqImg/"+ DateUtils.datePaths()+"/" + UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        if(Base64ToImage(request.getParameter("lqrqianming"),Global.getProfile()+lqrqm)){
            lqrqm="/profile"+lqrqm;
        }
        info.setLqrphoto(lqrpz);
        info.setLqrqianming(lqrqm);
        info.setLqdate(new Date());
        info.setPrintytjname(request.getParameter("printYtjname"));
        int result = qyInfoService.submitInfo(info);

        if (result == 1) {
            return AjaxResult.success("更新成功");
        } else {
            QyInfoPritn qyInfoPritn = new QyInfoPritn();
            qyInfoPritn.setBsid(info.getBsid());
            qyInfoPritn.setLqrphoto(lqrpz);
            qyInfoPritn.setLqrqianming(lqrqm);
            qyInfoPritn.setLqrname(request.getParameter("sfzm"));
            qyInfoPritn.setLqrcardno(request.getParameter("sfz"));

            qyInfoPritn.setPrintytjname(request.getParameter("printYtjname"));
            qyInfoPritn.setLqdate(new Date());
            int i = qyInfoPritnService.updateQyInfoPritnByBsid(qyInfoPritn);
            if (i == 1) {
                return AjaxResult.success("更新成功");
            }
            return AjaxResult.warn("不存在企业信息");
        }
    }

    /**
     * 返回承诺数页面
     *
     * @param bsid
     * @param card
     * @return
     */
    @GetMapping("/ChengNuoShu")
    public String ChengNuoShu(@RequestParam("BSID") String bsid, @RequestParam("JingYingCard") String card, Model model) {

        model.addAttribute("city", Global.getCityName());
        model.addAttribute("scity", Global.getSuperCity());
        return prefix + "/ChengNuoShu";
    }

    /**
     * 发送短信信息
     */
    @PostMapping("/sendMsgToCompany")
    @ResponseBody
    public AjaxResult sendMsgToCompany(Long id,String companyPhone,String companyName,String KzCompanyPhone,String KzCompanyName,String RenName) {

       /* String url= "http://api.sms.cn/sms/";
        String parme="";
        try{
            QyInfo info= new QyInfo();
            info.setShenhename("kzsh01");
            info.setId(id);

            int i=qyInfoService.updateQyInfo(info);

            System.out.println("刻章推送："+i);
                parme="ac=send&uid=qxspj&pwd=8d18d2eb316841db0998eeb67362ba4c&mobile="+KzCompanyPhone
                        + "&content=" + URLEncoder.encode(companyName + "申请刻章，联系方式："+RenName+" "+companyPhone+"【井陉县行政审批局】","utf-8");
            String result= HttpUtils.sendGet(url,parme);

            System.err.println(result);
        }catch (Exception e) {
            e.printStackTrace();
        }*/
        return AjaxResult.success("ok");
        }

    /**
     * 更新领取人信息
     *
     * @param
     * @return
     */
    @PostMapping("/GetFormData_ChengNuoShu")
    @ResponseBody
    public AjaxResult GetFormData_ChengNuoShu(@RequestParam("BSID") String bsid, @RequestParam("JingYingCard") String card) {

        QyInfo qyInfos = qyInfoService.selectQyInfoByBsId(bsid);
        if (qyInfos != null) {
            return AjaxResult.success("存在的企业信息", qyInfos);
        } else {
            QyInfoPritn qyInfoPritn = qyInfoPritnService.selectQyInfoPritnByBsid(bsid);
            return AjaxResult.success("存在的企业信息", qyInfoPritn);
        }
    }

    /**
     * 返回打印预览页
     *
     * @param bsid
     * @param card
     * @return
     */
    @GetMapping("/PrintLr")
    public String PrintIndexNew(@RequestParam("BSID") String bsid, @RequestParam("JingYingCard") String card, HttpServletResponse response, Model model) throws Exception {
        response.setCharacterEncoding("UTF-8");
        model.addAttribute("city", Global.getCityName());
        QyInfo info = qyInfoService.selectQyInfoByBsId(bsid);
        if (info != null) {
            CreateHtml(info, response);
        } else {
            QyInfoPritn qyInfoPritn = qyInfoPritnService.selectQyInfoPritnByBsid(bsid);
            CreatePrintHtml(qyInfoPritn, response);
        }
        return prefix + "/PrintLr";
    }


    private String substr1(String str) {
        if (str == null) {
            return "";
        }
        str = str.substring(str.length() - 1, str.length());
        return str;
    }


    //在一体机上申请的信息，
    public void CreateHtml(QyInfo info, HttpServletResponse response) throws Exception {
        //查询个体数据
        response.setCharacterEncoding("UTF-8");

        //①创建配置对象
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);//注意:这里需要传递一个版本

        String path = null;
        String path1 = null;
        if (System.getProperty("user.dir").indexOf("bin") != -1) {
            String[] t = System.getProperty("user.dir").split("bin");
            path = t[0] + "/webapps/ROOT/WEB-INF/classes/templates/";
            path1 = "";
        } else {
            path1 = "";
            path = System.getProperty("user.dir") + "/ruoyi-admin/src/main/resources/templates/";
        }
        File f = new File(path);
        File f1 = new File(path);

        //②读取模板文件夹
        cfg.setDirectoryForTemplateLoading(f);//设置要加载的模板文件的路径
        //③设置模板的编码格式
        cfg.setDefaultEncoding("UTF-8");
        //④获取模板对象
        Template template = cfg.getTemplate("qyPrintZ.ftl");//hello.ftl是模板名称
        Template template1 = cfg.getTemplate("qyPrintF.ftl");//hello.ftl是模板名称
        //⑤创建数据模型(这里使用map类型)  --[数据模型可以是List、Map对象 注意:Map类型的key必须是String类型]
        HashMap<String, Object> map = new HashMap<>();
        String stt = null;
        stt = info.getQyname();
        String yue = null;
        String Pdate = dateToStr(info.getShenhedate());
        String Pdate1 = dateToStr(info.getQyclrq());
        if (Integer.valueOf(Pdate.substring(5, 7)) < 10) {
            yue = Pdate.substring(6, 7);
        } else {
            yue = Pdate.substring(5, 7);
        }
        String qynx = "";
        if (!info.getQyjyqx().equals("长期")) {
            qynx = Buildtime(info.getQynx(), info.getShenhedate());
        }
        map.put("xinyongcode", info.getXinyongcode());
        map.put("frname", info.getFrname());
        map.put("jycs", info.getQyjycs());
        map.put("qyname", stt);
        map.put("zczj", digitUppercase(info.getQyzczj()));
        map.put("lx", info.getQylx());
        map.put("qynx", qynx);
        map.put("jyfw", info.getQyjyfw());

        String shr = substr1(info.getShenhename());
        String st1 = "";
        String st2 = info.getZzcode();

        List<SysDictData> dictData = dictDataService.selectDictDataByType("shenqingly");

//        map.put("zzcode", shr + st1 + st2);
        map.put("zzcode","");

        if (info.getQyjyfw().length() > 550 && info.getQyjyfw().length() <= 750) {
            map.put("jyfwcd", 53);
        } else if (info.getQyjyfw().length() > 750 && info.getQyjyfw().length() <= 1050) {
            map.put("jyfwcd", 47);
        } else if (info.getQyjyfw().length() > 1050 && info.getQyjyfw().length() <= 1500) {
            map.put("jyfwcd", 39);
        } else if (info.getQyjyfw().length() > 1500) {
            map.put("jyfwcd", 30);
        } else {
            map.put("jyfwcd", 60);
        }
        map.put("cldate", Pdate1);


        String ewm = info.getErweimabase64();
        map.put("ewm", ewm);
        map.put("nian", Pdate.substring(0, 4));
        map.put("yue", yue);
        map.put("ri", Pdate.substring(8, 10));
        //⑥将模板和数据模型合并 --> 输出模板,生成文件
        PrintWriter pw = new PrintWriter(new File(f, path1 + "Ytj/PrintHtml/" + info.getXinyongcode() + "qyPrintZ.html"));
        PrintWriter pw1 = new PrintWriter(new File(f1, path1 + "Ytj/PrintHtml/" + info.getXinyongcode() + "qyPrintF.html"));
        template.process(map, pw);//合并  map:数据模型  pw:输出流对象
        template1.process(map, pw1);//合并  map:数据模型  pw:输出流对象
        pw.close();//关闭流
        pw1.close();//关闭流
    }

    /**
     * 从网上下载下来的信息，用于执照打印
     *
     * @param info
     * @param response
     * @throws Exception
     */
    public void CreatePrintHtml(QyInfoPritn info, HttpServletResponse response) throws Exception {
        //查询个体数据
        response.setCharacterEncoding("UTF-8");

        //①创建配置对象
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);//注意:这里需要传递一个版本

        String path = null;
        String path1 = null;
        if (System.getProperty("user.dir").indexOf("bin") != -1) {
            String[] t = System.getProperty("user.dir").split("bin");
            path = t[0] + "/webapps/ROOT/WEB-INF/classes/templates/";
            path1 = "";
        } else {
            path1 = "";
            path = System.getProperty("user.dir") + "/ruoyi-admin/src/main/resources/templates/";
        }
        File f = new File(path);
        File f1 = new File(path);

        //②读取模板文件夹
        cfg.setDirectoryForTemplateLoading(f);//设置要加载的模板文件的路径
        //③设置模板的编码格式
        cfg.setDefaultEncoding("UTF-8");
        //④获取模板对象
        Template template;
        Template template1;
        if ("1,3,9".contains(info.getQylb())) {
            template = cfg.getTemplate("QyTemplates/qyPrintZone.ftl");//hello.ftl是模板名称
            template1 = cfg.getTemplate("QyTemplates/qyPrintFone.ftl");//hello.ftl是模板名称
        } else if (info.getQylb().equals("7")) {
            template = cfg.getTemplate("QyTemplates/qyPrintZthree.ftl");//hello.ftl是模板名称
            template1 = cfg.getTemplate("QyTemplates/qyPrintFthree.ftl");//hello.ftl是模板名称
        } else {
            template = cfg.getTemplate("QyTemplates/qyPrintZtwo.ftl");//hello.ftl是模板名称
            template1 = cfg.getTemplate("QyTemplates/qyPrintFtwo.ftl");//hello.ftl是模板名称
        }

        //⑤创建数据模型(这里使用map类型)  --[数据模型可以是List、Map对象 注意:Map类型的key必须是String类型]
        HashMap<String, Object> map = new HashMap<>();
        String stt = null;
        stt = info.getQyname();
        String yue = null;
        String Pdate = dateToStr(info.getShenhedate());
        String Pdate1 = dateToStr(info.getQyclrq());
        if (Integer.valueOf(Pdate.substring(5, 7)) < 10) {
            yue = Pdate.substring(6, 7);
        } else {
            yue = Pdate.substring(5, 7);
        }
        map.put("xinyongcode", info.getXinyongcode());
        map.put("frname", info.getFrname());
        map.put("jycs", info.getQyjycs());
        map.put("qyname", stt);
        map.put("zczj", digitUppercase(info.getQyzczj()));
        map.put("lx", info.getQylx());
        if ("长期".equals(info.getQyjyqx())) {
            map.put("qynx", "");
        } else {
            map.put("qynx", info.getQynx());
        }

        map.put("jyfw", info.getQyjyfw());
        map.put("cldate", Pdate1);

        String shr = substr1(info.getShenhename());
        String st1 = "";
        String st2 = info.getZzcode();
    /*    List<SysDictData> dictData = dictDataService.selectDictDataByType("shenqingly");
        for (SysDictData data : dictData) {
            if (info.getPrintytjname().equals(data.getDictLabel())) {
                st1 = data.getDictValue();
            }
        }*/

//        map.put("zzcode", shr + st1 + st2);
        map.put("zzcode", "");
        if (info.getQyjyfw().length() > 550 && info.getQyjyfw().length() <= 750) {
            map.put("jyfwcd", 53);
        } else if (info.getQyjyfw().length() > 750 && info.getQyjyfw().length() <= 1050) {
            map.put("jyfwcd", 47);
        } else if (info.getQyjyfw().length() > 1050 && info.getQyjyfw().length() <= 1500) {
            map.put("jyfwcd", 39);
        } else if (info.getQyjyfw().length() > 1500) {
            map.put("jyfwcd", 30);
        } else {
            map.put("jyfwcd", 60);
        }
        map.put("djlx", info.getQylb());
        String ewm = info.getErweimabase64();
        map.put("ewm", ewm);
        map.put("nian", Pdate.substring(0, 4));
        map.put("yue", yue);
        map.put("ri", Pdate.substring(8, 10));
        //⑥将模板和数据模型合并 --> 输出模板,生成文件
        PrintWriter pw = new PrintWriter(new File(f, path1 + "Ytj/PrintHtml/" + info.getXinyongcode() + "qyPrintZ.html"));
        PrintWriter pw1 = new PrintWriter(new File(f1, path1 + "Ytj/PrintHtml/" + info.getXinyongcode() + "qyPrintF.html"));
        template.process(map, pw);//合并  map:数据模型  pw:输出流对象
        template1.process(map, pw1);//合并  map:数据模型  pw:输出流对象
        pw.close();//关闭流
        pw1.close();//关闭流
    }

    /**
     * 返回打印预览页
     *
     * @param bsid
     * @param
     * @return
     */
    @GetMapping("/Printing")
    @ResponseBody
    public AjaxResult Printing(@RequestParam("BSID") String bsid, @RequestParam("bs") Integer bs, Model model) {

        String print = "1";
        Date date = new Date();
        QyInfo info = qyInfoService.selectQyInfoByBsId(bsid);
        if (info != null) {
            if (bs == 1 && info.getIsprintZ().equals("0")) {
                info.setIsprintZ(print);
                info.setPrintzdate(date);
                System.err.println("打印时间===" + info.getPrintzdate());
                qyInfoService.updateQyInfo(info);
                if (qyInfoService.updateQyInfo(info) == 1) {
                    SysConfig sysConfig = new SysConfig();
                    sysConfig.setConfigKey("zbzz");
                    List<SysConfig> sysConfigs = sysConfigService.selectConfigList(sysConfig);
                    sysConfig = sysConfigs.get(0);
                    sysConfig.setConfigValue(String.valueOf(Integer.parseInt(sysConfig.getConfigValue()) - 1));
                    sysConfigService.updateConfig(sysConfig);
                }
                return AjaxResult.success("操作成功", info);
            } else if (bs == 0 && info.getIsprintF().equals("0")) {
                info.setIsprintF(print);
                info.setPrintfdate(date);
                if (qyInfoService.updateQyInfo(info) == 1) {
                    SysConfig sysConfig = new SysConfig();
                    sysConfig.setConfigKey("zbzz");
                    List<SysConfig> sysConfigs = sysConfigService.selectConfigList(sysConfig);
                    sysConfig = sysConfigs.get(0);
                    sysConfig.setConfigValue(String.valueOf(Integer.parseInt(sysConfig.getConfigValue()) - 1));
                    sysConfigService.updateConfig(sysConfig);
                }
                return AjaxResult.success("操作成功", info);
            } else if (bs == 3) {
                return AjaxResult.success("您已打印该文件,请勿重复操作", info);
            } else {
                return AjaxResult.warn("出现错误,请联系管理员解决");
            }
        } else {
            QyInfoPritn qyInfoPritn = qyInfoPritnService.selectQyInfoPritnByBsid(bsid);
            qyInfoPritn.setBsid(bsid);
            if (bs == 1) {
                qyInfoPritn.setIsprintZ(print);
                qyInfoPritn.setPrintzdate(date);
                qyInfoPritnService.updateQyInfoPritnByBsid(qyInfoPritn);
                return AjaxResult.success("操作成功", qyInfoPritn);
            } else if (bs == 0) {
                qyInfoPritn.setIsprintF(print);
                qyInfoPritn.setPrintfdate(date);
                qyInfoPritnService.updateQyInfoPritnByBsid(qyInfoPritn);
                return AjaxResult.success("操作成功", qyInfoPritn);
            } else if (bs == 3) {
                return AjaxResult.success("您已打印该文件,请勿重复操作", qyInfoPritn);
            }
        }
        return AjaxResult.warn("出现错误,请联系管理员解决");
    }


    /**
     * @param
     * @return 打印副本页面
     */
    @GetMapping("/fuben")
    public String printfu(@RequestParam("XinYongCode") String XinYongCode, HttpServletResponse response) {

        response.setContentType("text/html;charset=utf-8");
        return "Ytj/PrintHtml/" + XinYongCode + "qyPrintF.html";
        //  return prefix+"/PrintForm_FNew";
    }

    /**
     * @param
     * @return 打印正本页面
     */
    @GetMapping("/zhengben")
    public String printzheng(@RequestParam("XinYongCode") String XinYongCode, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        return "Ytj/PrintHtml/" + XinYongCode + "qyPrintZ.html";
        //    return prefix+"/PrintFormZheng";
    }


}

















