package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.WebSocketServer;
import com.ruoyi.common.utils.redis.RedisUtil;
import com.ruoyi.system.domain.GtInfo;
import com.ruoyi.system.domain.HyDictionary;
import com.ruoyi.system.mapper.YtjMapper;
import com.ruoyi.system.service.IYtjService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ruoyi.common.utils.ImgUtils.Base64ToImage;
import static com.ruoyi.common.utils.http.HttpUtils.sendGet;

/**
 * 参数配置 服务层实现
 *
 * @author ruoyi
 */
@Service
public class YtjServiceImpl implements IYtjService {
    @Autowired
    private YtjMapper ytjMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public int IfExistsRen(String sfzh) {
        int result = ytjMapper.IfExistsRen(sfzh);

        return result;
    }

    @Override
    public List<Map> GetQh() {
        List<Map> map = ytjMapper.GetQh();
        return map;
    }

    @Override
    public List<Map> GetQu(String pid) throws UnsupportedEncodingException {
        try {
            pid = URLDecoder.decode(pid, "utf-8");
            List<Map> map = ytjMapper.GetQu(pid);
            return map;
        } catch (Exception ex) {
            throw ex;
        }
    }

    @Override
    public List<Map> GetHy() throws UnsupportedEncodingException {
        List<Map> map = ytjMapper.GetHy();


        return map;
    }

    @Override
    public List<HyDictionary> GetChildHy(String pid) throws UnsupportedEncodingException {
        List<HyDictionary> map=getChildHy2(pid);
        return map;
    }

    public List<HyDictionary> getChildHy2(String pid) {
        List<HyDictionary> hy1 = ytjMapper.selectHyDictionaryList();
        List<HyDictionary> children = findChildren(pid, hy1);
        return children;
    }

    public List<HyDictionary> findChildren(String parentId, List<HyDictionary> list) {
        List<HyDictionary> tempList = new ArrayList<>();
        for (int i = 0; i <list.size(); i++) {
            HyDictionary item=list.get(i);
            if (item.getParentId().equals(parentId)) {
                List<HyDictionary> getChildeList = findChildren(item.getDataDictionaryDetailId(), list);
                if (getChildeList.size() > 0) {
                    item.setChildren(getChildeList);
                }
                tempList.add(item);
                item=null;
            }
        }

        return tempList;
    }

    @Override
    public List<HyDictionary> GetHymc(String name) throws UnsupportedEncodingException {
        name=java.net.URLDecoder.decode(name, "UTF-8");
        String[] aaa =name.split(",");
        List<HyDictionary> map=ytjMapper.GetHymc(aaa[1]);
        return map;
    }

    @Override
    public List<HyDictionary> GetZzxx(String name) throws UnsupportedEncodingException {
        name=java.net.URLDecoder.decode(name, "UTF-8");
        String[] aaa =name.split(",");
        List<HyDictionary> map=ytjMapper.GetZzxx(aaa[1]);
        return map;
    }

    @Override
    public int SubmitCard(String sfzm, String tximg, String sfzh, String sfzdz, String sjhm) {
        int isok = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH：mm：ss：SSS");
        String now = sdf.format(new Date());
        int ifnot = IfExistsRen(sfzh);
        if (ifnot == 0) {
            isok = ytjMapper.SubmitCard(sfzm, tximg, sfzh, sfzdz, sjhm, now);
        } else {
            isok = ytjMapper.UpdateCard(sfzm, tximg, sfzh, sfzdz, sjhm, now);
        }
        return isok;
    }

    @Override
    public Map GetUserCard(String hm) throws UnsupportedEncodingException {
        try {
            hm = URLDecoder.decode(hm, "utf-8");
            System.err.println("身份证"+hm);
            List<Map> userMap = ytjMapper.GetUserCard(hm);//GtGsYw_Ren 找电话
            List<Map> phoneMap=ytjMapper.GetUserPhone(hm);//gtgsyw 找数据
            Map map=new HashMap();
            map.put("djry",userMap);
            map.put("tjsj",phoneMap);
            return map;
        } catch (Exception ex) {
            throw ex;
        }
    }

    @Override
    public String Check(String b,String zwzh1,String zwzh2,String zwzh3,String c) {
        String ifExists = "";
        String hyname=ytjMapper.getname(c);
        Object list1 =null;
        Object list2 =null;
        Object list3 =null;

        list1 = redisUtil.get(hyname+":"+ToPinyin(zwzh1.replace("", "-").trim()));

        if(zwzh2!=""){
             list2 = redisUtil.get(hyname+":"+ToPinyin(zwzh2.replace("", "-").trim()));
        }
        if(zwzh3!="") {
             list3 = redisUtil.get(hyname + ":" + ToPinyin(zwzh3.replace("", "-").trim()));
        }
        System.err.println(hyname+":"+ToPinyin(zwzh1.replace("", "-").trim())+"----"+hyname+":"+ToPinyin(zwzh2)+"----"+hyname+":"+ToPinyin(zwzh3));
        if (list1!=null) {
            ifExists += zwzh1+" ";
        }
        System.err.println(ifExists);
        if (list2!=null) {
            ifExists += zwzh2+" ";
        }
        System.err.println(ifExists);
        if (list3!=null) {
            ifExists += zwzh3+" ";
        }
        System.err.println(ifExists);
        if (ifExists==null||ifExists.equals(""))
        {
            return "0," + b;
        }
        else
        {
            return "1," + ifExists;//重复名字的字符串
        }
    }

    /**
     * 汉字转为拼音
     * @param chinese
     * @return
     */
    public static String ToPinyin(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }



    public static String getHanziPinYin(String hanzi) {
        String result = null;
        if(null != hanzi && !"".equals(hanzi)) {
            char[] charArray = hanzi.toCharArray();
            StringBuffer sb = new StringBuffer();
            for (char ch : charArray) {
                // 逐个汉字进行转换， 每个汉字返回值为一个String数组（因为有多音字）
                String[] stringArray = PinyinHelper.toHanyuPinyinStringArray(ch);
                if(null != stringArray) {
                    // 把第几声这个数字给去掉
                    sb.append(stringArray[0].replaceAll("\\d", ""));
                }
            }
            if(sb.length() > 0) {
                result = sb.toString();
            }
        }
        return result;
    }
    @Override
    public List<Map> GetFw(String a) throws UnsupportedEncodingException {
        a = URLDecoder.decode(a, "utf-8");
        List<HyDictionary> list=ytjMapper.GetID(a);
        String ID=list.get(0).getDataDictionaryDetailId();
        List<Map> map=ytjMapper.GetFw(ID);
        Map nameMap=new HashMap();
        Map fwMap=new HashMap();
        List<Map> rtnMap=new ArrayList<Map>();
        String[] fw=null;
        for(int i=0;i<map.size();i++){
            String fwString=map.get(i).get("fullName").toString();
            fw=fwString.split(",");
            nameMap.put("fullName",a);
            fwMap.put("children",fw);
            rtnMap.add(i,nameMap);
            rtnMap.get(i).put("children",fw);
        }
        return rtnMap;
    }

    @Override
    public List<Map> GetCailiao(String hyid) throws UnsupportedEncodingException {
        List<Map> clList = ytjMapper.GetCailiao(hyid);
        return clList;
    }

    @Override
    public int SendCailiao(String bsid,String clname,String clindex,String clsrc){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String now = sdf.format(new Date());
        int isok=ytjMapper.SendCailiao(bsid,clname,clindex,clsrc,now);
        return  isok;
    }

    @Override
    public int DelCailiao(String bsid,String clname,String clindex) throws UnsupportedEncodingException {
        clname = URLDecoder.decode(clname, "utf-8");
        int isok=ytjMapper.DelCailiao(bsid,clname,clindex);
        return  isok;
    }

    @Override
    public int SubmitForm(HttpServletRequest request) throws UnsupportedEncodingException {
        GtInfo info=new GtInfo();
        String xgflg = request.getParameter("xgflg");

        info.setBSID(request.getParameter("bsid"));

        String a = request.getParameter("jycsq");
        info.setNsXzq(request.getParameter("xzq"));
        String b = getname(request.getParameter("jycsz"));
        info.setNsdXj(b);
        String c = "";
        if (request.getParameter("jycsc") != null && request.getParameter("jycsc")!="")
        {
            c = getname(request.getParameter("jycsc"));
        }
        info.setNsdXc(c);
        String s = request.getParameter("xxdz");
        String ss="";
        if (b == c)
        {
            ss = Global.getSuperCity() + a  + s;//拼接经营场所
        }
        else
        {
//            ss = "河北省"+Global.getSuperCity() + a  + s;//拼接经营场所
            ss =  a  + s;//拼接经营场所
        }
        info.setJingYingChangSuo(ss);
        info.setScZtType("个体工商户");
        String e = request.getParameter("xyzh");
        info.setZwzh(request.getParameter(e));//选用的字号
        info.setZwzh1(request.getParameter("zwzh1"));
        info.setZwzh2(request.getParameter("zwzh2"));
        info.setZwzh3(request.getParameter("zwzh3"));
        if (info.getZwzh1() == "" && info.getZwzh2() == "" && info.getZwzh3() == "" )
        {
            info.setZwzh("***");//如果都为空就是没有字号，默认***
        }
        String l = request.getParameter("result");
        String[] ll = l.split(",");//行业分类截取
//        String hh = gehy2(ll[1]);//获得值
        info.setHangYe(getname(request.getParameter("HY1")));
        info.setHangYe1(ll[0]);
        info.setHangYe2(ll[2]);
        info.setHangYe3(ll[1]);
        info.setMingChengHangYe(request.getParameter("hymc"));
        info.setZuZhiXingShi(request.getParameter("zzxx"));
        info.setZuChengXingShi(request.getParameter("zcxx"));
        info.setZiJinShuE(request.getParameter("zczb"));//注册资本
        info.setJingYingFanWei(request.getParameter("jyfw"));
        info.setCongYeRenShu(Integer.parseInt(request.getParameter("cyrs")));
        info.setJingYingRen(request.getParameter("jyzxm"));
        info.setXingBie(request.getParameter("jyzxb"));
        info.setMinZu(request.getParameter("jyzmz"));
        info.setJiaTingZhuZhi(request.getParameter("jyzzz"));
        info.setBanFaJiGou(request.getParameter("sfzjg"));
       /* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String now = sdf.format(new Date());
        info.setBanFaJiGou(now);*/
        info.setJingYingRenPhone(request.getParameter("jyzdh"));
        info.setJingYingCard(request.getParameter("jyzsfz"));

        String sfztxPath= "/sqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        if(Base64ToImage(request.getParameter("jyztx"),Global.getProfile()+sfztxPath)){
            info.setJingYingCardTouXiang("/profile"+sfztxPath);//身份证头像
        }

        //把base64转为图片路径
        String paizhaoPath= "/sqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        if(Base64ToImage(request.getParameter("paizhao"),Global.getProfile()+paizhaoPath)){
            info.setPaiZhao("/profile"+paizhaoPath);   //拍照头像
        }

        String qmPath= "/sqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        if(Base64ToImage(request.getParameter("QianMing"),Global.getProfile()+qmPath)){
            info.setQianMing("/profile"+qmPath);//手写签名
        }

        info.setRzduibiScore(request.getParameter("rzduibiScore"));//得分
        info.setShenqinglaiyuan(request.getParameter("xxly"));
        info.setFwghyt(request.getParameter("fwghyt"));//房屋规划用途
        info.setIsJc(request.getParameter("isjcHid"));//是否军产
        info.setJycsSy(Integer.parseInt(request.getParameter("jycssy")));//经营场所属于（1非住宅、2住宅、3军产）
        info.setZzSxID(request.getParameter("zzHid"));//多证合一
        info.setIsDy(Integer.parseInt(request.getParameter("isdyHid")));//是否为党员
        info.setZzmm(request.getParameter("zzmm"));//政治面貌
        info.setWhcd(request.getParameter("whcd"));//文化程度
        info.setZyzk(request.getParameter("zyzk"));//职业状况
        info.setJycscq(request.getParameter("jycscq"));//经营场所产权
        info.setType(request.getParameter("type"));//type
        info.setShenQingDate(new Date());//申请时间
        int isok=ytjMapper.SubmitForm(info);
        if(isok==1){
            try {
                WebSocketServer.sendInfo("个体户："+request.getParameter("jyzxm") +"的申请消息!请及时查办","1");
            } catch (IOException es) {
                es.printStackTrace();
                System.err.println(e);
            }
        }
        return  isok;
    }

    public String gehy2(String hy) throws UnsupportedEncodingException {
        String gehy = ytjMapper.gehy2(hy);
        return gehy;
    }
    public String getname(String str) throws UnsupportedEncodingException {
        String rtnStr = ytjMapper.getname(str);
        return rtnStr;
    }

    @Override
    public int GetShenHeNum() throws UnsupportedEncodingException{
        int num=ytjMapper.GetShenHeNum();
        return  num;
    }
	@Override
    public Map GetCardInfo(String hm) throws UnsupportedEncodingException {
        try {
            Map map = ytjMapper.GetCardInfo(hm);
            return map;
        } catch (Exception ex) {
            throw ex;
        }
    }
    @Override
    public String GetHyname(String pid) throws UnsupportedEncodingException {
        try {
          String map = ytjMapper.GetHyname(pid);
            return map;
        } catch (Exception ex) {
            throw ex;
        }
    }

    /**
     * 发送url 返会信息
     * @param card
     * @param name
     * @return
     */
    private static  Pattern pattern = Pattern.compile("<td( .*?)?>.*?</td>");
    private static  Pattern pattern1 = Pattern.compile("<font.*?>(.*?)</font>");
    @Override
    public  List<String> CheckRz(String card, String name, HttpServletResponse response){
         String url= Global.getConfig("ruoyi.gsdz")+":8005/gtdj/regApp.do";
         String param="method=validPopMultiIdCardCheck&appNo=&etpsNm=***&etpsType=9500&appTypeId=02&regOrgan=130107&validHasSpecial=&branchEtpsName=***&agentName=&agentCertNo=&contactName="+name+"&contactCertNo="+card+"&ignoreReason=";
        //  String url = "http://192.168.1.5/rz.html";
        String html=sendGet(url,param);
        List<String> ren=new ArrayList<String>();
        Matcher matcher = pattern.matcher(html);
        String html1="";
        while (matcher.find()) {
           html1=html1+matcher.group();
        }
        Matcher matcher1 = pattern1.matcher(html1);
        while (matcher1.find()) {
            ren.add(matcher1.group(1).trim());
            System.out.println("HTML111:"+matcher1.group(1));
        }
        return ren;
    }

    @Override
    public String selectByRemark(String remark){
        return ytjMapper.selectByRemark(remark);
    }


}
