package com.chenyang.nse.bussiness.service.core.impl;

import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.table.core.previousblobtask.TCorePreviousBlobTaskDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.previousblob.TCorePreviousBlobTask;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.previousblobtask.TCorePreviousBlobTaskVO;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.PreviousBlobTaskService;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class PreviousBlobTaskSerivceImpl implements PreviousBlobTaskService {
   @Autowired
   private TCorePreviousBlobTaskDao tCorePreviousBlobTaskDao;
   @Autowired
   private DataSystemService dataSystemService;

   public List<TCorePreviousBlobTask> querytask(String taskname, PageInfo pageInfo) {
      long count = this.tCorePreviousBlobTaskDao.count();
      pageInfo.setCount(count);
      List<TCorePreviousBlobTask> list = this.tCorePreviousBlobTaskDao.queryByPageInfo(pageInfo, Order.desc("createtime"), new Criterion[]{Restrictions.like("taskname", taskname, MatchMode.ANYWHERE).ignoreCase()});
      return list;
   }

   public List<TCorePreviousBlobTask> isexist(String taskname) {
      List<TCorePreviousBlobTask> list = this.tCorePreviousBlobTaskDao.queryAll(new Criterion[]{Restrictions.eq("taskname", taskname)});
      return list;
   }

   public ResultVO savePreviousBlobTask(TCorePreviousBlobTask tCorePreviousBlobTask) {
      ResultVO rv = new ResultVO("创建失败", false);
      tCorePreviousBlobTask.setCreatetime(new Date());
      this.tCorePreviousBlobTaskDao.save(tCorePreviousBlobTask);
      rv.setMessage("创建成功");
      rv.setResult(true);
      return rv;
   }

   public void removetask(String taskid) {
      this.tCorePreviousBlobTaskDao.removeById(taskid);
   }

   public void executetask(String taskid) {
      TCorePreviousBlobTask blobinfo = (TCorePreviousBlobTask)this.tCorePreviousBlobTaskDao.get(taskid);
      blobinfo.setRunstatus("1");
      this.tCorePreviousBlobTaskDao.update(blobinfo);
      this.tCorePreviousBlobTaskDao.getSession().getTransaction().commit();
      Connection conn = this.dataSystemService.getConnectionByDataSystemId(blobinfo.getDatasourceid());
      PreparedStatement selectPkPs = null;
      PreparedStatement updateBlobPs = null;
      ResultSet rs = null;

      try {
         conn.setAutoCommit(false);
         List<String> e = JdbcTool.getPK(conn, (String)null, blobinfo.getDatasourceschema(), blobinfo.getTablename());
         if (!e.isEmpty()) {
            String selectPkSql = "select " + (String)e.get(0) + " , " + blobinfo.getBlobcloumn() + " from " + blobinfo.getDatasourceschema() + "." + blobinfo.getTablename() + " where " + blobinfo.getBlobcloumn() + " IS NOT NULL";
            selectPkPs = conn.prepareStatement(selectPkSql);
            rs = selectPkPs.executeQuery();
            String updateBlobSql = "update " + blobinfo.getDatasourceschema() + "." + blobinfo.getTablename() + " set " + blobinfo.getBlobcloumn() + " = ? where " + (String)e.get(0) + " = ?";
            int a = 0;

            while(rs.next()) {
               String blobStr = new String(rs.getBytes(blobinfo.getBlobcloumn()));

               try {
                  if (StringUtils.isNotBlank(blobStr)) {
                     String reblobStr = this.maskingblobinfo(blobStr, blobinfo.getMaskinginfo(), rs.getString((String)e.get(0)));
                     if (StringUtils.isNotBlank(reblobStr)) {
                        updateBlobPs = conn.prepareStatement(updateBlobSql);
                        updateBlobPs.setBytes(1, reblobStr.getBytes("UTF-8"));
                        updateBlobPs.setString(2, rs.getString((String)e.get(0)));
                        updateBlobPs.executeUpdate();
                        updateBlobPs.close();
                        ++a;
                        if (a % 100 == 0) {
                           conn.commit();
                        }

                        if (a % 10000 == 0) {
                           System.out.println("已执行" + a + "条数据 主键为" + rs.getString((String)e.get(0)));
                        }
                     }
                  }
               } catch (Exception e1) {
                  FileTool.createFile("/data/blobexception/" + rs.getString((String)e.get(0)) + ".txt");
                  FileTool.writeContentToFile("/data/blobexception/" + rs.getString((String)e.get(0)) + ".txt", blobStr);
                  e1.printStackTrace();
               }
            }

            conn.commit();
            conn.setAutoCommit(true);
            return;
         }
      } catch (Exception e) {
         e.printStackTrace();
         return;
      } finally {
         try {
            if (rs != null) {
               rs.close();
            }

            if (selectPkPs != null) {
               selectPkPs.close();
            }

            JdbcTool.closeConnection(conn);
            this.tCorePreviousBlobTaskDao.getSession().beginTransaction();
            blobinfo.setRunstatus("0");
            this.tCorePreviousBlobTaskDao.update(blobinfo);
            System.out.println("执行完毕");
         } catch (SQLException e) {
            e.printStackTrace();
         }

      }

   }

   public String maskingblobinfo(String blobstr, String maskinginfo, String id) {
      String[] mask = maskinginfo.split(",");
      String nameflg = mask[0];
      String proflg = mask[1];
      String genflg = mask[2];
      String ageflg = mask[3];
      String workflg = mask[4];
      String addflg = mask[5];
      String ethflg = mask[6];
      String marryflg = mask[7];
      String bornflg = mask[8];
      if (nameflg.equals("1") && blobstr.contains("-姓名")) {
         int namenum = (blobstr.length() - blobstr.replaceAll("-姓名", "").length()) / 3;

         for(int i = 0; i < namenum; ++i) {
            String newname = "";
            int namestart = blobstr.substring(this.getCharacterPosition("-姓名", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-姓名", i + 1, blobstr) + 2;
            int nameend = blobstr.substring(namestart, blobstr.length()).indexOf("<") + namestart;
            String name = blobstr.substring(namestart, nameend);

            for(int j = 0; j < name.length(); ++j) {
               newname = newname + "*";
            }

            if (!name.contains("-姓名") && !name.contains("props")) {
               blobstr = blobstr.substring(0, namestart) + newname + blobstr.substring(nameend, blobstr.length());
            } else {
               blobstr = blobstr.substring(0, namestart + 1) + name + blobstr.substring(nameend, blobstr.length());
            }
         }
      } else {
         FileTool.writeContentToFile("/data/blobnote.txt", "**不含姓名信息的" + id + "\n");
      }

      if (proflg.equals("1") && blobstr.contains("-职业")) {
         int pronum = (blobstr.length() - blobstr.replaceAll("-职业", "").length()) / 3;

         for(int i = 0; i < pronum; ++i) {
            String newpro = "";
            int prostart = blobstr.substring(this.getCharacterPosition("-职业", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-职业", i + 1, blobstr) + 1;
            int proend = blobstr.substring(prostart, blobstr.length()).indexOf("<") + prostart;
            String pro = blobstr.substring(prostart, proend);

            for(int j = 0; j < pro.length(); ++j) {
               newpro = newpro + "*";
            }

            if (!pro.contains("-职业") && pro.length() > 0) {
               blobstr = blobstr.substring(0, prostart) + newpro + blobstr.substring(proend, blobstr.length());
            } else {
               blobstr = blobstr.substring(0, prostart) + pro + blobstr.substring(proend, blobstr.length());
            }
         }
      }

      if (genflg.equals("1") && blobstr.contains("-性别")) {
         int gennum = (blobstr.length() - blobstr.replaceAll("-性别", "").length()) / 3;

         for(int i = 0; i < gennum; ++i) {
            String newgender = "";
            int genstart = blobstr.substring(this.getCharacterPosition("-性别", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-性别", i + 1, blobstr) + 1;
            int genend = blobstr.substring(genstart, blobstr.length()).indexOf("<") + genstart;
            String gender = blobstr.substring(genstart, genend);

            for(int j = 0; j < gender.length(); ++j) {
               newgender = newgender + "*";
            }

            if (!gender.contains("-性别") && gender.length() > 0) {
               blobstr = blobstr.substring(0, genstart) + newgender + blobstr.substring(genend, blobstr.length());
            } else {
               blobstr = blobstr.substring(0, genstart) + gender + blobstr.substring(genend, blobstr.length());
            }
         }
      }

      if (ageflg.equals("1")) {
         if (blobstr.contains("-年龄")) {
            int agenum = (blobstr.length() - blobstr.replaceAll("-年龄", "").length()) / 3;
            int max = 90;
            int min = 17;
            Random random = new Random();
            int rannum = random.nextInt(max) % (max - min + 1) + min;
            String newage = Integer.valueOf(rannum).toString();

            for(int i = 0; i < agenum; ++i) {
               int agestart = blobstr.substring(this.getCharacterPosition("-年龄", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-年龄", i + 1, blobstr) + 1;
               int ageend = blobstr.substring(agestart, blobstr.length()).indexOf("<") + agestart;
               String age = blobstr.substring(agestart, ageend);
               if (!age.contains("-年龄") && age.length() > 0) {
                  blobstr = blobstr.substring(0, agestart) + newage + blobstr.substring(ageend, blobstr.length());
               } else {
                  blobstr = blobstr.substring(0, agestart) + age + blobstr.substring(ageend, blobstr.length());
               }
            }
         }

         if (blobstr.contains("-入院年龄")) {
            int hosagenum = (blobstr.length() - blobstr.replaceAll("-入院年龄", "").length()) / 5;
            int max = 90;
            int min = 17;
            Random random = new Random();
            int rannum = random.nextInt(max) % (max - min + 1) + min;
            String newhosage = Integer.valueOf(rannum).toString();

            for(int i = 0; i < hosagenum; ++i) {
               int hosagestart = blobstr.substring(this.getCharacterPosition("-入院年龄", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-入院年龄", i + 1, blobstr) + 1;
               int hosageend = blobstr.substring(hosagestart, blobstr.length()).indexOf("<") + hosagestart;
               String hosage = blobstr.substring(hosagestart, hosageend);
               if (!hosage.contains("-入院年龄") && hosage.length() > 0) {
                  blobstr = blobstr.substring(0, hosagestart) + newhosage + blobstr.substring(hosageend, blobstr.length());
               } else {
                  blobstr = blobstr.substring(0, hosagestart) + hosage + blobstr.substring(hosageend, blobstr.length());
               }
            }
         }
      }

      if (workflg.equals("1") && blobstr.contains("-工作单位")) {
         int worknum = (blobstr.length() - blobstr.replaceAll("-工作单位", "").length()) / 5;

         for(int i = 0; i < worknum; ++i) {
            String newwork = "";
            int workstart = blobstr.substring(this.getCharacterPosition("-工作单位", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-工作单位", i + 1, blobstr) + 4;
            int workend = blobstr.substring(workstart, blobstr.length()).indexOf("<") + workstart;
            String work = blobstr.substring(workstart, workend);

            for(int j = 0; j < work.length(); ++j) {
               newwork = newwork + "*";
            }

            if (!work.contains("-工作单位") && !work.contains("props")) {
               blobstr = blobstr.substring(0, workstart) + newwork + blobstr.substring(workend, blobstr.length());
            } else {
               blobstr = blobstr.substring(0, workstart + 3) + work + blobstr.substring(workend, blobstr.length());
            }
         }
      }

      if (addflg.equals("1") && blobstr.contains("-住址")) {
         int addressnum = (blobstr.length() - blobstr.replaceAll("-住址", "").length()) / 3;

         for(int i = 0; i < addressnum; ++i) {
            String newaddress = "";
            int addressstart = blobstr.substring(this.getCharacterPosition("-住址", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-住址", i + 1, blobstr) + 4;
            int addressend = blobstr.substring(addressstart, blobstr.length()).indexOf("<") + addressstart;
            String address = blobstr.substring(addressstart, addressend);

            for(int j = 0; j < address.length(); ++j) {
               newaddress = newaddress + "*";
            }

            if (!address.contains("-住址") && !address.contains("props")) {
               blobstr = blobstr.substring(0, addressstart) + newaddress + blobstr.substring(addressend, blobstr.length());
            } else {
               blobstr = blobstr.substring(0, addressstart + 3) + address + blobstr.substring(addressend, blobstr.length());
            }
         }
      }

      if (ethflg.equals("1") && blobstr.contains("-民族")) {
         int ethnicnum = (blobstr.length() - blobstr.replaceAll("-民族", "").length()) / 3;
         String[] ethnics = new String[]{"汉族", "回族", "满族", "锡伯族", "藏族", "蒙古族", "壮族", "朝鲜族", "苗族", "维吾尔族", "哈萨克族", "佤族", "彝族"};

         for(int i = 0; i < ethnicnum; ++i) {
            String newethnic = "";
            int ethnicstart = blobstr.substring(this.getCharacterPosition("-民族", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-民族", i + 1, blobstr) + 1;
            int ethnicend = blobstr.substring(ethnicstart, blobstr.length()).indexOf("<") + ethnicstart;
            String ethnic = blobstr.substring(ethnicstart, ethnicend);
            int index = (int)(Math.random() * (double)ethnics.length);
            newethnic = ethnics[index];
            if (!ethnic.contains("-民族") && ethnic.length() > 0) {
               blobstr = blobstr.substring(0, ethnicstart) + newethnic + blobstr.substring(ethnicend, blobstr.length());
            } else {
               blobstr = blobstr.substring(0, ethnicstart) + ethnic + blobstr.substring(ethnicend, blobstr.length());
            }
         }
      }

      if (marryflg.equals("1") && blobstr.contains("-婚姻状况")) {
         int marriagenum = (blobstr.length() - blobstr.replaceAll("-婚姻状况", "").length()) / 5;

         for(int i = 0; i < marriagenum; ++i) {
            String newmarriage = "";
            int marriagestart = blobstr.substring(this.getCharacterPosition("-婚姻状况", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-婚姻状况", i + 1, blobstr) + 1;
            int marriageend = blobstr.substring(marriagestart, blobstr.length()).indexOf("<") + marriagestart;
            String marriage = blobstr.substring(marriagestart, marriageend);

            for(int j = 0; j < marriage.length(); ++j) {
               newmarriage = newmarriage + "*";
            }

            if (!marriage.contains("-婚姻状况") && marriage.length() > 0) {
               blobstr = blobstr.substring(0, marriagestart) + newmarriage + blobstr.substring(marriageend, blobstr.length());
            } else {
               blobstr = blobstr.substring(0, marriagestart) + marriage + blobstr.substring(marriageend, blobstr.length());
            }
         }
      }

      if (bornflg.equals("1") && blobstr.contains("-籍贯")) {
         int bornnum = (blobstr.length() - blobstr.replaceAll("-籍贯", "").length()) / 3;

         for(int i = 0; i < bornnum; ++i) {
            String newborn = "";
            int bornstart = blobstr.substring(this.getCharacterPosition("-籍贯", i + 1, blobstr), blobstr.length()).indexOf(">") + this.getCharacterPosition("-籍贯", i + 1, blobstr) + 4;
            int bornend = blobstr.substring(bornstart, blobstr.length()).indexOf("<") + bornstart;
            String born = blobstr.substring(bornstart, bornend);

            for(int j = 0; j < born.length(); ++j) {
               newborn = newborn + "*";
            }

            if (!born.contains("-籍贯") && !born.contains("props")) {
               blobstr = blobstr.substring(0, bornstart) + newborn + blobstr.substring(bornend, blobstr.length());
            } else {
               blobstr = blobstr.substring(0, bornstart + 3) + born + blobstr.substring(bornend, blobstr.length());
            }
         }
      }

      return blobstr;
   }

   public int getCharacterPosition(String character, int i, String string) {
      Matcher slashMatcher = Pattern.compile(character).matcher(string);
      int mIdx = 0;

      while(slashMatcher.find()) {
         ++mIdx;
         if (mIdx == i) {
            break;
         }
      }

      return slashMatcher.start();
   }

   public TCorePreviousBlobTaskVO queryBlobMaskingTaskVOByID(String taskid) {
      TCorePreviousBlobTaskVO vo = null;
      List<TCorePreviousBlobTaskVO> taskLst = this.tCorePreviousBlobTaskDao.queryBlobMaskingTaskVOByID(taskid);
      if (null != taskLst && taskLst.size() > 0) {
         vo = (TCorePreviousBlobTaskVO)taskLst.get(0);
      }

      return vo;
   }
}
