package com.dr.tushu.jyg.service;
import com.dr.framework.common.dao.CommonMapper;
import com.dr.framework.common.page.Page;
import com.dr.framework.core.orm.sql.support.SqlQuery;
import com.dr.tushu.jyg.entity.JygReader;
import com.dr.tushu.jyg.entity.JygReaderInfo;
import com.dr.tushu.jyg.entity.ilas.Cirfin;
import com.dr.tushu.jyg.entity.ilas.CirfinInfo;
import com.dr.tushu.jyg.entity.ilas.Reader;
import com.dr.tushu.jyg.entity.ywg.BorrowHisIndexInfo;
import com.dr.tushu.jyg.entity.ywg.BorrowHistory;
import com.dr.tushu.jyg.entity.ywg.BorrowHistoryInfo;
import com.dr.tushu.jyg.mapper.IlasMapper;
import com.dr.tushu.jyg.util.ApiDemo;
import com.dr.tushu.jyg.util.RSAUtils;
import com.dr.tushu.jyg.util.TokenUtil;
import com.dr.tushu.jyg.vo.*;
import com.dr.tushu.jyg.vo.RequestEntity;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 嘉峪关图书馆便民卡service
*/
@Service
public class JYGCardService {
static Logger logger = LoggerFactory.getLogger(GuancangService.class);
@Value("${bmk.bmkurl}")
private String API_ADDRESS;
@Value("${ftp.BDaddress}")
private String ftpBD_ADDRESS;
@Value("${ftp.SCaddress}")
private String ftpSCaddress;
@Autowired
RestTemplate restTemplate;
ObjectMapper objectMapper = new ObjectMapper();
@Autowired
CommonMapper commonMapper;
@Autowired
IlasMapper ilasMapper;
@Autowired
FTPClient ftpClient;
/**
* 统一发起请求
*
* @param data
* @return
*/
public String request(Header header, Object data) throws JsonProcessingException {
//准备请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("Jwt", "");
//准备请求参数
Map<String, String> params = new HashMap<>();
RequestEntity requestEntity = new RequestEntity(data, header);
params.put("content", objectMapper.writeValueAsString(requestEntity));
//准备请求体
HttpEntity<String> request = new HttpEntity<>(objectMapper.writeValueAsString(params), headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(API_ADDRESS, HttpMethod.POST, request, String.class);
if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
return responseEntity.getBody();
}
return null;
}
/**
* 交换密钥
*
* @return
*/
public boolean changeRsaKey() throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
Header header = new Header("1001");
Map data = new HashMap();
data.put("publickey", TokenUtil.getStringPublicKey());
request(header, data);
return false;
}
/**
* 查询指定账户的未缴费信息
*
* @return
*/
public List<UserFee> queryjfxinxi(Map map) {
List<UserFee> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
UserFee userfee = new UserFee();
if (i == 0) {
long amount = Long.valueOf(map.get("ptjyyj").toString());
if (amount <= 0) {
userfee.setType("001");
userfee.setAmount(10000);//单位分
list.add(userfee);
}
}
if (i == 1) {
long amount = Long.valueOf(map.get("zxjyyj").toString());
}
if (i == 2) {
long amount = Long.valueOf(map.get("xyfkye").toString());
}
if (i == 3) {
long amount = Long.valueOf(map.get("ptyjqk").toString());
if (amount > 0) {
userfee.setType("002");
userfee.setAmount(amount);//单位分
list.add(userfee);
}
}
if (i == 4) {
long amount = Long.valueOf(map.get("zxyjqk").toString());
if (amount > 0) {
userfee.setType("006");
userfee.setAmount(amount);//单位分
list.add(userfee);
}
}
}
return list;
}
/**
* 借阅信息查询
*
* @param index 分页位置,从1开始默认是1
* @param pageSize 每页条数,默认是100
* @return
*/
public Page borrowPage(Reader reader, int index, int pageSize) {
List<UserBorrow> listborrw = new ArrayList<>();
SqlQuery<BorrowHistory> sqlQuery = SqlQuery.from(BorrowHistory.class, true);
sqlQuery.column(BorrowHisIndexInfo.DTOPERATEDATE, BorrowHisIndexInfo.NOPERATETYPE).join(BorrowHistoryInfo.NHISINDEXID, BorrowHisIndexInfo.NHISINDEXID);
sqlQuery.equal(BorrowHistoryInfo.SZREADERID, reader.getR01B()).orderBy(BorrowHistoryInfo.DTNEEDBACK);
Page page = commonMapper.selectPageByQuery(sqlQuery, pageSize * (index - 1), pageSize * index);
if (page.getData() != null) {
List<BorrowHistory> list = page.getData();
for (int i = 0; i < list.size(); i++) {
BorrowHistory borrowhistory = list.get(i);
UserBorrow userborrow = getuserbrrow(borrowhistory, reader);
listborrw.add(userborrow);
}
page.setData(listborrw);
}
return page;
}
/**
* 获取读者的一卡通信息
*
* @param
* @return
* @throws JSONException
*/
public String getuseractivate(BookUser user) throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Content-Type", "application/x-www-form-urlencoded");
requestHeaders.add("trCode", "5103");
requestHeaders.add("interCode", "1001004");
//设置参数
JSONObject content = new JSONObject();
JSONObject data = new JSONObject();
JSONObject header = new JSONObject();
JSONObject phoneinfo = new JSONObject();
data.put("certno", user.getUserId());
header.put("seq", String.valueOf(System.currentTimeMillis()));
header.put("trdate", getcurtimeYMD(System.currentTimeMillis()) + " " + getcurtimeHMS(System.currentTimeMillis()));
header.put("trcode", "5103");
header.put("source", "REG-02");
header.put("interCode", "1001004");
header.put("trtype", "01");
phoneinfo.put("brand", "iphone");
phoneinfo.put("type", "6plus");
phoneinfo.put("longitude", "31.283529");
phoneinfo.put("latitude", "121.481673");
header.put("phone_info", phoneinfo);
content.put("data", data);
content.put("header", header);
HashMap<String, Object> map = new HashMap<>();
ApiDemo.parseJSON2Map(map, content.toString(), null);
InputStream io = RSAUtils.class.getResourceAsStream("/jygCard.keystore");
String sign = RSAUtils.sign(ApiDemo.getSignStr(map).getBytes("utf-8"), StreamUtils.copyToByteArray(io));
header.put("sign", sign);
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
ArrayList<Object> params = new ArrayList<>();
params.add(content.toString());
postParameters.put("content", params);
//利用容器实现数据封装,发送
HttpEntity<MultiValueMap<String, Object>> entityParam = new HttpEntity<MultiValueMap<String, Object>>(postParameters, requestHeaders);//请求地址,参数,返回值类型
String result = restTemplate.postForObject(API_ADDRESS, entityParam, String.class);
return result;
}
public BMUserInfo getbmuserinfos(BookUser user) {
Phoneinfo phoneinfo = new Phoneinfo();
phoneinfo.put("latitude", "0");
phoneinfo.put("type", "6plus");
phoneinfo.put("os_version", 8.1);
phoneinfo.put("longitude", "0");
phoneinfo.put("brand", "iPhone");
BMUserInfo bmuserinfo = new BMUserInfo();
bmuserinfo.put("seq", String.valueOf(System.currentTimeMillis()));
// bmuserinfo.put("sign","MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKr1Ch8QEQY3gt2wID5I3x46BjNY9inkLNWvgzIBCubiokpIbMJnw/Z7vSkCRkQuojuCMUaAcKp9lmRdiQfQ0wH0dCzSS0vptz4K29OAfRKWtYlRxMsQ1vp85LIZ5T8ikr2/Hdp+qsmn8LUVDjZ32BuA3mV3LX2EuzThmsvzjDerAgMBAAECgYBMAsVsSEV5gScDkHLVnqrtkpj9LZnNyHES1YW8ru/89ll4M7l/uolLx3q0iBlb6Wwij2F/Wk49z7cViu0Jd5TJdvRVSYa0p9z4esQLYBFOjB8owEMmu+cOxUlecGoo9yPea2welO9+Pdeu5csBvbgv4HgVc1O32tS0/5H8WgeaKQJBAO/Yucb4F5y1UO4nrussigtbzg87BeGdHqDvbLbm16RvM/lAjUX4y1FoHnm9lh9hyfYDwK8koTTziiW/Bm+l2kUCQQC2eJGlMaRmA6dpFHuy9aaoPV+CbVBqjmDDS8i2wg2xmMjDIJ/tbfCM+BHK3x9BESzE+GjaH1dNsV7yp1TroWEvAkEAizroPVRvgIzQui9XHzXvvMBCUh0VQO8QhKP4HATNUassJJkQaXoPrOYgKtOffgAqWSG8jO9alX56x4aomc9RcQJAAuPZ+rHUlsEMD8ABTY5Se2utbZVppqZmpfE3Vp2wNdXjqCOGJO6O1sy/C2WJSzCIcv40OvAwI8zhYhqAX9MIhQJBALEDwe0Tfe7v5ZO8S+1KmdawlG8XjKAYAIPsz28OT7yHBA5hwmfFraaNM0aFW7neUCAHBHMnwxXVMUdGXPZCeaM=");
bmuserinfo.put("source", "REG-02");
bmuserinfo.put("trdate", getcurtimeYMD(System.currentTimeMillis()) + " " + getcurtimeHMS(System.currentTimeMillis()));
bmuserinfo.put("trtype", "01");
bmuserinfo.put("interCode", "1001004");
bmuserinfo.put("trcode", "5103");
bmuserinfo.put("phone_info", phoneinfo);
return bmuserinfo;
}
/**
* 欠款缴费缴费接口
*/
List<String> payTypes = Arrays.asList("001", "002", "003", "004", "005", "006", "099");
List<String> paySources = Arrays.asList("001", "002", "003", "004", "005", "099");
@Transactional(rollbackFor = {Exception.class})
public String savedUserPay(UserPay pay, Reader reader) {
String resutvalue = "";
if (pay != null && reader != null) {
if (validatepay(pay)) {
if (pay.getOrder_id() != null) {
SqlQuery<UserPay> sqlQuery = SqlQuery.from(UserPay.class).equal(UserPayInfo.ORDER_ID, pay.getOrder_id());
UserPay userpaytwo = commonMapper.selectOneByQuery(sqlQuery);
if (userpaytwo != null) {
resutvalue = "重复的订单号码!!!";
} else {
if ("001".equals(pay.getType())) {
if (10000. == pay.getAmount()) {
List<Cirfin> lists = getyiqianjhao(reader.getR000(), "Y", "%CW%"); //查询这个人以前是否交过押金
if (lists.size() > 0) {
int intone = getqiankuan(reader.getR000(), "Y", "%CW%");
if (intone == 10000) {
return resutvalue = "你已缴过押金,不需多次缴费";
} else {
zhixingjiaoyajin(lists, reader.getR01B());
}
} else {
int nFin00 = ilasMapper.getxulie();
Cirfin cirfin = getcirfin(nFin00, reader, pay);
commonMapper.insert(cirfin);
}
} else {
return resutvalue = "缴费的押金金额不对!!!";
}
} else if ("002".equals(pay.getType())) {
int intone = getqiankuan(reader.getR000(), "N", "%FW%");
if (intone == pay.getAmount()) { //超期欠款钱数与缴费钱数对比
//查询出超期欠款的数据进行更新处理
List<Cirfin> lists = getqiankuansj(reader.getR000(), "N", "%FW%");
//执行还款
zhixinghuankuan(lists, reader.getR01B());
} else {
return resutvalue = "缴费的普通欠款金额不对!!!";
}
} else if ("006".equals(pay.getType())) {
int intone = getqiankuan(reader.getR000(), "N", "%FZ%");
if (intone == pay.getAmount()) { //专项欠款钱数与缴费钱数对比
//查询出专项外借欠款数据
List<Cirfin> lists = getqiankuansj(reader.getR000(), "N", "%FZ%");
//执行还款
zhixinghuankuan(lists, reader.getR01B());
} else {
return resutvalue = "缴费的专项欠款金额不对!!!";
}
}
pay.setBiaozhi(true);
commonMapper.insert(pay);
resutvalue = "缴费成功!!!";
}
}
}
}
return resutvalue;
}
/**
* 退费
*
* @param pay
* @param reader
* @return
*/
public String refounddelete(UserPay pay, Reader reader) {
String resutvalue = "";
if (pay != null && reader != null) {
if (validatepay(pay)) {
if (pay.getOrder_id() != null) {
SqlQuery<UserPay> sqlQuery = SqlQuery.from(UserPay.class).equal(UserPayInfo.ORDER_ID, pay.getOrder_id());
UserPay userpaytwo = commonMapper.selectOneByQuery(sqlQuery);
if (userpaytwo != null) {
resutvalue = "重复的订单号码!!!";
} else {
if ("005".equals(pay.getType())) {
int sumMoney = ilasMapper.getsummoney(reader.getR000()); //查询当前人缴的押金钱数
if (sumMoney == pay.getAmount()) {
//查询出当前人员的缴费(押金)信息
List<Cirfin> lists = getqiankuansj(reader.getR000(), "Y", "%CW%");
//执行退款
zhixingtuikuan(lists, reader.getR01B());
} else {
return resutvalue = "退回的押金金额不对!!!";
}
} else {
}
commonMapper.insert(pay);
UserPay userpaysan = querydingdanhao(pay);
SqlQuery<UserPay> sqlQuerySan = SqlQuery.from(UserPay.class, true);
sqlQuerySan.set(UserPayInfo.AMOUNT, 0).set(UserPayInfo.BIAOZHI, false).equal(UserPayInfo.ORDER_ID, userpaysan.getOrder_id());
commonMapper.updateIgnoreNullByQuery(sqlQuerySan);
resutvalue = "退费成功!!!";
}
}
}
}
return resutvalue;
}
/**
* 获取一种罚款钱数
*
* @param R000
* @param FINf
* @param FINa
* @return
*/
public int getqiankuan(int R000, String FINf, String FINa) {
return ilasMapper.getquoyouje(R000, FINf, FINa);
}
/**
* 查询出超期欠款(和押金)的数据
*/
public List<Cirfin> getqiankuansj(int R000, String FINf, String FINa) {
SqlQuery<Cirfin> sqlQueryTwo = SqlQuery.from(Cirfin.class);
sqlQueryTwo.equal(CirfinInfo.FINR, R000).equal(CirfinInfo.FINF, FINf).like(CirfinInfo.FINA, FINa);
return commonMapper.selectByQuery(sqlQueryTwo);
}
/**
* 查询人员是否交过费
*
* @param R000
* @return
*/
public List<Cirfin> getyiqianjhao(int R000, String FINf, String FINa) {
SqlQuery<Cirfin> sqlQueryTwo = SqlQuery.from(Cirfin.class).equal(CirfinInfo.FINR, R000).equal(CirfinInfo.FINF, FINf).like(CirfinInfo.FINA, FINa);
return commonMapper.selectByQuery(sqlQueryTwo);
}
/**
* 执行还款
*/
@Transactional(rollbackFor = {Exception.class})
public void zhixinghuankuan(List<Cirfin> lists, String RO1B) {
if (lists.size() > 0) {
String FINf = "C";
String FINz = RO1B + "取消";
for (Cirfin cirfin : lists) {
SqlQuery<Cirfin> sqlQuerySan = SqlQuery.from(Cirfin.class);
sqlQuerySan.set(CirfinInfo.FINF, FINf).set(CirfinInfo.FINZ, FINz).equal(CirfinInfo.FIN00, cirfin.getFIN00());
commonMapper.updateIgnoreNullByQuery(sqlQuerySan);
}
}
}
/**
* 这个人再次缴费
*
* @param lists
* @param RO1B
*/
@Transactional(rollbackFor = {Exception.class})
public void zhixingjiaoyajin(List<Cirfin> lists, String RO1B) {
String FINz = RO1B + "再次缴费";
for (Cirfin cirfin : lists) {
SqlQuery<Cirfin> sqlQuerySan = SqlQuery.from(Cirfin.class);
sqlQuerySan.set(CirfinInfo.FINK, 10000).set(CirfinInfo.FINZ, FINz).equal(CirfinInfo.FIN00, cirfin.getFIN00()).equal(CirfinInfo.FINF, "Y").equal(CirfinInfo.FINA, "CW");
commonMapper.updateIgnoreNullByQuery(sqlQuerySan);
}
}
/**
* 执行退款
*
* @param lists
* @param RO1B
*/
public void zhixingtuikuan(List<Cirfin> lists, String RO1B) {
if (lists.size() > 0) {
String FINz = RO1B + "退款";
for (Cirfin cirfin : lists) {
SqlQuery<Cirfin> sqlQuerySan = SqlQuery.from(Cirfin.class);
sqlQuerySan.set(CirfinInfo.FINK, 0.0).set(CirfinInfo.FINZ, FINz).equal(CirfinInfo.FIN00, cirfin.getFIN00()).equal(CirfinInfo.FINF, "Y").equal(CirfinInfo.FINA, "CW");
commonMapper.updateIgnoreNullByQuery(sqlQuerySan);
}
}
}
/**
* 实现UserBorrow的类
*
* @param borrowhistory
* @return
*/
public UserBorrow getuserbrrow(BorrowHistory borrowhistory, Reader reader) {
UserBorrow userborrow = new UserBorrow();
userborrow.setId(borrowhistory.getNHistoryID() + "");
userborrow.setBookId(borrowhistory.getSzBookID());
userborrow.setBookName(borrowhistory.getSzBookName());
if (borrowhistory.getnOperateType() == 1) {
userborrow.setStatus("002");
} else if (borrowhistory.getnOperateType() == 3) {
userborrow.setStatus("004");
} else if (borrowhistory.getnOperateType() == 2) {
userborrow.setStatus("005");
} else {
userborrow.setStatus("003");
}
userborrow.setRenewDate(borrowhistory.getDtOperateDate().getTime());
userborrow.setStartDate(borrowhistory.getDtOperateDate().getTime());
userborrow.setEndDate(borrowhistory.getDtNeedBack().getTime());
userborrow.setUserId(borrowhistory.getSzReaderID());
userborrow.setUserName(reader.getR01I());
userborrow.setUserType("001");
return userborrow;
}
/**
* 实现UserPay的验证
*
* @param pay
* @return
*/
public Boolean validatepay(UserPay pay) {
Assert.isTrue(payTypes.contains(pay.getType()), "不支持此交易类型");
Assert.isTrue(paySources.contains(pay.getSource()), "不支持此交易来源");
Assert.notNull(pay.getOrder_id(), "订单号不能为空");
Assert.isTrue(pay.getOrder_id().length() == 25, "订单号格式不正确");
Assert.notNull(pay.getCreate_time(), "缴费发起时间不能为空");
Assert.notNull(pay.getPayment_time(), "支付时间不能为空");
Assert.isTrue(pay.getCreate_time() <= pay.getPayment_time(), "支付时间需大于发起时间");
Assert.isTrue(pay.getAmount() >= 0, "缴费金额不能小于0");
Assert.isTrue(pay.getOrder_id() != null, "订单不能为空");
return true;
}
/**
* 获取年月日
*
* @return
*/
protected String getcurtimeYMD(long timedate) {
return DateFormatUtils.format(timedate, "yyyyMMdd");
}
/**
* 获取时分秒
*
* @param timedate
* @return
*/
protected String getcurtimeHMS(long timedate) {
return DateFormatUtils.format(timedate, "HHmmss");
}
protected String getcurtimeYMDHMS(long timedate) {
return DateFormatUtils.format(timedate, "yyyy-MM-dd HH:mm:ss");
}
/**
* 缴费表实现类
*
* @param nFin00
* @param reader
* @param pay
* @return
*/
public Cirfin getcirfin(int nFin00, Reader reader, UserPay pay) {
Cirfin cirfin = new Cirfin();
cirfin.setFIN0(nFin00);
cirfin.setFIN00(nFin00);
cirfin.setFINR(reader.getR000());
cirfin.setFINT("P");
cirfin.setFINA("CW");
cirfin.setFINC("");
cirfin.setFIND("0");
cirfin.setFINF("Y");
cirfin.setFING("");
cirfin.setFINH(1.0D);
cirfin.setFINI(Double.valueOf(getcurtimeYMD(pay.getPayment_time())));
cirfin.setFINJ(Double.valueOf(getcurtimeHMS(pay.getPayment_time())));
cirfin.setFINK(10000);
cirfin.setFINL(reader.getR01B());
cirfin.setFINQ("C");
cirfin.setFINZ("");
return cirfin;
}
/**
* 实现便民卡中的jyg实体类
*
* @return
*/
public JygReader getjygreder(JSONObject ja) {
JygReader jygreader = new JygReader();
try {
jygreader.setId(UUID.randomUUID().toString());
int redid = ilasMapper.getreaderid();
String readerId = "jyg" + String.valueOf(redid);
jygreader.setReaderId(readerId);
jygreader.setReaderName(ja.get("name").toString());
jygreader.setChushengdate("-");
String SEX = ja.get("sex").toString();
if ("男".equals(SEX)) {
jygreader.setSex("M");
} else if ("女".equals(SEX)) {
jygreader.setSex("F");
}
jygreader.setJzaddress(ja.get("address").toString());
jygreader.setAddress("app");
jygreader.setBianmincard(ja.get("cardno").toString());
jygreader.setCardtype("2");
jygreader.setEmile("-");
jygreader.setStatedate(getcurtimeYMD(System.currentTimeMillis()) + getcurtimeHMS(System.currentTimeMillis()));
jygreader.setEnddate("-");
jygreader.setIdcordt(ja.get("certno").toString());
jygreader.setJiankadate(getcurtimeYMD(System.currentTimeMillis()) + getcurtimeHMS(System.currentTimeMillis()));
jygreader.setKaihuguan("app");
jygreader.setPasword("123456");
jygreader.setShoujihao(ja.get("phone").toString());
jygreader.setStatetype("n");
jygreader.setPhoto(ja.get("photo").toString());
jygreader.setFlage(false);
} catch (JSONException e) {
e.printStackTrace();
}
return jygreader;
}
/**
* 更新注册,和未填写卡号的便民卡更新
*
* @return
*/
public boolean updatebincart(JygReader jygreader, JSONObject ja) {
try {
SqlQuery<JygReader> sqlQuerySan = SqlQuery.from(JygReader.class, true);
sqlQuerySan.set(JygReaderInfo.BIANMINCARD, ja.get("cardno").toString());
sqlQuerySan.set(JygReaderInfo.JZADDRESS, ja.get("address").toString());
sqlQuerySan.set(JygReaderInfo.STATETYPE, "n");
sqlQuerySan.equal(JygReaderInfo.ID, jygreader.getId());
commonMapper.updateByQuery(sqlQuerySan);
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
/**
* 验证读者是否存在
*
* @param user
* @return
*/
public boolean getjygreader(BookUser user) {
SqlQuery<JygReader> sqlQuerySan = SqlQuery.from(JygReader.class, true);
sqlQuerySan.equal(JygReaderInfo.IDCORDT, user.getUserId());
List list = commonMapper.selectByQuery(sqlQuerySan);
if (list.size() > 0) {
return true;
} else {
return false;
}
}
public JygReader querjygreader(BookUser user) {
SqlQuery<JygReader> sqlQuerySan = SqlQuery.from(JygReader.class, true);
sqlQuerySan.equal(JygReaderInfo.IDCORDT, user.getUserId());
return commonMapper.selectOneByQuery(sqlQuerySan);
}
public UserPay querydingdanhao(BookUser user) {
SqlQuery<UserPay> sqlQuerySan = SqlQuery.from(UserPay.class, true);
sqlQuerySan.equal(UserPayInfo.USERID, user.getUserId()).equal(UserPayInfo.USERTYPE, user.getUserType()).equal(UserPayInfo.BIAOZHI, true).equal(UserPayInfo.TYPE, "001");
return commonMapper.selectOneByQuery(sqlQuerySan);
}
public UserDetails getuserdetails(BookUser user, JygReader jygreader, boolean flage, int summoney, String userlevel, UserPay userpay) {
UserDetails userdetails = new UserDetails();
userdetails.setUserId(user.getUserId());
userdetails.setUserType(user.getUserType());
userdetails.setUserName(jygreader.getReaderName());
if ("001".equals(userlevel)) {
userdetails.setUserLevel("003");
} else if ("002".equals(userlevel)) {
userdetails.setUserLevel("004");
} else if ("003".equals(userlevel)) {
userdetails.setUserLevel("005");
} else {
userdetails.setUserLevel("002");
}
userdetails.setStatus("已激活");
if (flage) {
userdetails.setHasPayment("已缴押金");
} else {
userdetails.setHasPayment("未缴押金");
}
if (userpay != null) {
userdetails.setAmount(summoney);
userdetails.setOrder_id(userpay.getOrder_id());
userdetails.setPayment_time(userpay.getPayment_time());
userdetails.setPayment_type(Long.valueOf(userpay.getPayment_type()));
} else {
userdetails.setAmount(0);
userdetails.setOrder_id("");
userdetails.setPayment_time(0);
userdetails.setPayment_type(0);
}
return userdetails;
}
/**
* 对账功能
* 每天晚上同步数据 0点同步数据
*
* @throws Exception
*/
@Async
@Transactional(rollbackFor = Exception.class)
@Scheduled(cron = "0 0 5 * * ? ")
public void syncFeeInfo() {
logger.info("开始进行账单对接");
Map zzhuangmap = new HashMap();
List<Map> qxlist = new ArrayList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -1);
date = calendar.getTime();
String dlftpfilePath = "DZMX21001" + sdf.format(date) + ".txt";
String dlfilePath = ftpBD_ADDRESS + "DZMX21001" + sdf.format(date) + ".txt";
String upfilePath = ftpSCaddress + "DZMX21001" + sdf.format(date) + "_RET.txt";
String upftpfilePath = "DZMX21001" + sdf.format(date) + "_RET.txt";
try {
boolean flag = download("192.168.40.6", "jygftp", "jyg2018@drsoft", 21, "", dlftpfilePath, dlfilePath);
if (flag) {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(dlfilePath));
String s = br.readLine();
while (s != null) {
sb.append(s);
String fisetstr = sb.toString();
String[] strinstr = fisetstr.split("\\|");
if (strinstr.length > 4) {
Map map = getdzxq(strinstr);
qxlist.add(map);
} else {
zzhuangmap = getdzzxx(strinstr);
}
sb = new StringBuffer();
s = br.readLine();
}
if (zzhuangmap.size() > 0 && qxlist.size() > 0) {
//执行对账
List<Map> duizhangjg = zhixingduizhang(zzhuangmap, qxlist, sdf.format(date));
if (duizhangjg.size() > 0) {
//将对账结果写入到文件中,上传给对方的ftp上
shengchengwenjian(duizhangjg, upfilePath);
boolean ftpflag = ftpuploadfile("192.168.40.6", "jygftp", "jyg2018@drsoft", 21, "", upfilePath, upftpfilePath);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public Map getdzzxx(String[] strinstr) {
Map map = new HashMap();
map.put("reconciliDate", strinstr[0]); //时间
map.put("reconciliNumber", strinstr[1]); //笔数
map.put("reconciliAmount", strinstr[2]); //金额
return map;
}
public Map getdzxq(String[] strinstr) {
Map map = new HashMap();
map.put("number", strinstr[0]); //序号
map.put("ReconciliDate", strinstr[1]); //时间
map.put("orderId", strinstr[2]); // 订单号
map.put("commodityId", strinstr[3]); //
map.put("amount", strinstr[4]); //金额
map.put("source", strinstr[5]); //
map.put("paymentType", strinstr[6]);
map.put("create_time", strinstr[7]);
map.put("type", strinstr[8]);
return map;
}
public void shengchengwenjian(List<Map> list, String filePath) {
try {
File file = new File(filePath);
List<String> lines = new ArrayList<>();
//如果没有文件就创建
for (int i = 0; i < list.size(); i++) {
Map maptwo = list.get(i);
if (i == 0) {
String qxstrtwo = maptwo.get("reconciliDate") + "|" + maptwo.get("reconciliNumber") + "|" + maptwo.get("reconciliAmount");
lines.add(qxstrtwo);
} else {
String qxstr = maptwo.get("number") + "|" + maptwo.get("ReconciliDate") + "|" + maptwo.get("orderId") + "|" + maptwo.get("user") + "|" + maptwo.get("amount") + "|" + maptwo.get("stuts") + "|" + maptwo.get("meassg");
lines.add(qxstr);
}
}
FileUtils.writeLines(file, lines);
} catch (IOException e) {
logger.warn("生成对账单文件失败", e);
}
}
/**
* 执行对账 并返回对账结果
*/
public List zhixingduizhang(Map map, List<Map> list, String dateno) {
List jgliat = new ArrayList();
//查询系统中前一天的缴费,退费的详细信息
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd HHmmss");
String start = dateno + " 000000";
String end = dateno + " 235959";
try {
long startdate = simpleDateFormat.parse(start).getTime();
long enddate = simpleDateFormat.parse(end).getTime();
SqlQuery<UserPay> sqlQuery = SqlQuery.from(UserPay.class, true);
sqlQuery.greaterThanEqual(UserPayInfo.PAYMENT_TIME, startdate).lessThanEqual(UserPayInfo.CREATE_TIME, enddate);
sqlQuery.equal(UserPayInfo.SOURCE, "005");//只对账便民卡的账
List<UserPay> zslist = commonMapper.selectByQuery(sqlQuery);
if (zslist.size() > 0) {
long reconciliNumber = Long.valueOf(map.get("reconciliNumber").toString());
long paycount = zslist.size();
jgliat.add(map);
//这里是判读传过来的订单是不是存在 (但是没有判断订单中没有的数据)
for (int a = 0; a < list.size(); a++) {
Map maptwo = list.get(a);
String orderId = maptwo.get("orderId").toString();
SqlQuery<UserPay> sqlQuerytwo = SqlQuery.from(UserPay.class, true);
sqlQuerytwo.equal(UserPayInfo.ORDER_ID, orderId);
UserPay userpaytwo = commonMapper.selectOneByQuery(sqlQuerytwo);
if (userpaytwo != null) {
for (int b = 0; b < zslist.size(); b++) {
UserPay userPay = zslist.get(b);
if (userPay != null) {
if (orderId.equals(userPay.getOrder_id())) {
if ("0001".equals(maptwo.get("paymentType").toString())) {
double amount = Double.valueOf(maptwo.get("amount").toString()) * 100;
double amount1 = (double) userPay.getAmount() + 10000.0;
if (amount == amount1) {
Map jgmap = getjiegoumap(maptwo, userPay, "01", "");
jgliat.add(jgmap);
} else {
Map jgmap = getjiegoumap(maptwo, userPay, "02", "订单存在但金额不对");
jgliat.add(jgmap);
}
} else if ("0002".equals(maptwo.get("paymentType").toString())) {
double amount = Double.valueOf(maptwo.get("amount").toString()) * 100;
double amount1 = (double) userPay.getAmount();
if (amount == amount1) {
Map jgmap = getjiegoumap(maptwo, userPay, "01", "");
jgliat.add(jgmap);
} else {
Map jgmap = getjiegoumap(maptwo, userPay, "02", "订单存在但金额不对");
jgliat.add(jgmap);
}
}
}
}
}
} else {
Map jgmap = getjiegoumap(maptwo, userpaytwo, "02", "无此缴费记录");
jgliat.add(jgmap);
}
}
//这里判断查询出来的数据在传过来订单中没有的数据
int length = zslist.size();
int g = 0;
for (int c = length - 1; c < zslist.size(); c--) {
UserPay userPay = zslist.get(c);
for (int d = 0; d < list.size(); d++) {
Map mapsan = list.get(d);
if (userPay.getOrder_id().equals(mapsan.get("orderId"))) {
zslist.remove(c);
}
}
if (c == 0) {
break;
}
}
for (int i = 0; i < zslist.size(); i++) {
UserPay userPaysi = zslist.get(i);
long number = Long.valueOf(map.get("reconciliNumber").toString());
int numbertwo = Integer.valueOf((int) number) + i + 1;
Map jgmap = getjiegoumapcb(numbertwo, userPaysi, "02", "存在此记录,确未发现");
jgliat.add(jgmap);
}
} else {
for (int f = 0; f < list.size(); f++) {
Map mapsi = list.get(f);
Map jgmap = getjiegoumap(mapsi, null, "02", "无此缴费记录");
jgliat.add(mapsi);
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return jgliat;
}
/**
* ftp上传单个文件
*
* @param ftpUrl ftp地址
* @param userName ftp的用户名
* @param password ftp的密码
* @param directory 上传至ftp的路径名不包括ftp地址
* @param srcFileName 要上传的文件全路径名
* @param destName 上传至ftp后存储的文件名
* @throws IOException
*/
public boolean ftpuploadfile(String ftpUrl, String userName, String password, int port, String directory, String srcFileName, String destName) throws IOException {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
boolean result = false;
try {
ftpClient.connect(ftpUrl, port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
File srcFile = new File(srcFileName);
fis = new FileInputStream(srcFile);
// 设置上传目录
ftpClient.changeWorkingDirectory(directory);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("gbk");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
result = ftpClient.storeFile(destName, fis);
ftpClient.logout();
return result;
} catch (NumberFormatException e) {
System.out.println("FTP端口配置错误:不是数字:");
throw e;
} catch (FileNotFoundException e) {
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
/**
*
*
* @param ftpUrl ftp地址
* @param userName ftp的用户名
* @param password ftp的密码
* @param directory 要下载的文件所在ftp的路径名不包含ftp地址
* @param destFileName 要下载的文件名
* @param downloadName 下载后锁存储的文件名全路径
*/
public static boolean download(String ftpUrl, String userName, String password, int port, String directory, String destFileName, String downloadName) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpUrl, port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.changeWorkingDirectory(directory);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream inputStream = ftpClient.retrieveFileStream(destFileName);
Assert.notNull(inputStream, "FTP文件不存在:" + destFileName);
Assert.isTrue(ftpClient.getReplyCode() != 503, "FTP下载文件失败:" + destFileName);
FileUtils.copyInputStreamToFile(inputStream, new File(downloadName));
inputStream.close();
return true;
} catch (Exception e) {
logger.warn("FTP下载文件失败!", e);
} finally {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
logger.warn("关闭FTP连接发生异常!", e);
}
}
return false;
}
/**
* @return
*/
public Map getjiegoumap(Map jgmap, UserPay userPay, String stuts, String meassg) {
Map map = new HashMap();
map.put("number", jgmap.get("number")); //序号
map.put("ReconciliDate", jgmap.get("ReconciliDate")); //时间
map.put("orderId", jgmap.get("orderId")); // 订单号
if (userPay != null && userPay.getUserId() != null)
map.put("user", userPay.getUserId()); //用户
map.put("amount", jgmap.get("amount")); //金额
map.put("stuts", stuts);
map.put("meassg", meassg);
return map;
}
public Map getjiegoumapcb(long number, UserPay userPay, String stuts, String meassg) {
Map map = new HashMap();
map.put("number", number); //序号
map.put("ReconciliDate", userPay.getPayment_time()); //时间
map.put("orderId", userPay.getOrder_id()); // 订单号
map.put("user", userPay.getUserId()); //用户
map.put("amount", userPay.getAmount()); //金额
map.put("stuts", stuts);
map.put("meassg", meassg);
return map;
}
/**
* 验证二维码开门
*/
public String yanzhengcode(String randoncode, String flag) throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Content-Type", "application/x-www-form-urlencoded");
requestHeaders.add("trCode", "5103");
requestHeaders.add("interCode", "1001004");
JSONObject content = new JSONObject();
JSONObject data = new JSONObject();
JSONObject header = new JSONObject();
JSONObject phoneinfo = new JSONObject();
data.put("flag", flag);
data.put("parm", randoncode);
data.put("tradetype", "02");
data.put("trdate", getcurtimeYMDHMS(System.currentTimeMillis()));
header.put("seq", String.valueOf(System.currentTimeMillis()));
header.put("source", "REG-02");
header.put("trdate", getcurtimeYMDHMS(System.currentTimeMillis()));
header.put("trtype", "01");
header.put("interCode", "1001004");
header.put("trcode", "5101");
phoneinfo.put("latitude", "0");
phoneinfo.put("type", "simulator");
phoneinfo.put("os_version", "11.4");
phoneinfo.put("longitude", "0");
phoneinfo.put("brand", "iPhone");
header.put("phone_info", phoneinfo);
content.put("data", data);
content.put("header", header);
HashMap<String, Object> map = new HashMap<>();
ApiDemo.parseJSON2Map(map, content.toString(), null);
InputStream io = RSAUtils.class.getResourceAsStream("/jygCard.keystore");
String sign = RSAUtils.sign(ApiDemo.getSignStr(map).getBytes("utf-8"), StreamUtils.copyToByteArray(io));
header.put("sign", sign);
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
ArrayList<Object> params = new ArrayList<>();
params.add(content.toString());
postParameters.put("content", params);
//利用容器实现数据封装,发送
HttpEntity<MultiValueMap<String, Object>> entityParam = new HttpEntity<MultiValueMap<String, Object>>(postParameters, requestHeaders);//请求地址,参数,返回值类型
String result = restTemplate.postForObject(API_ADDRESS, entityParam, String.class);
return result;
}
}