package com.zjrs.ggfw.yjt.bpo.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.mohrss.leaf.core.framework.domain.bpo.impl.BPOImpl;
import org.mohrss.leaf.core.framework.web.controller.AjaxResponse;
import com.zjrs.ggfw.shbzk.bpo.ShbzkBPO;
import com.zjrs.ggfw.yjt.bpo.YjtBPO;
import com.zjrs.ggfw.yjt.dto.KyeDTO;
import com.zjrs.ggfw.yjt.dto.XfmxDTO;
import com.zjrs.ggfw.yjt.util.HttpClientUtil;
import com.zjrs.ggfw.yjt.util.SignUtil;
import com.zjrs.ggfw.yjt.util.YjtConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class YjtBPOImpl extends BPOImpl implements YjtBPO {

    private static final Logger LOG = LoggerFactory.getLogger(YjtBPOImpl.class);
    @Autowired
    YjtConfig config;

    @Resource
    private ShbzkBPO shbzkBPO;
    @Override
    public AjaxResponse upayDetail(XfmxDTO dto) throws Exception {
        AjaxResponse ajaxResponse = new AjaxResponse();
        Object cardNO=shbzkBPO.queryCardNO(dto.getAac147(),dto.getXm(),dto.getSscs());
        if(cardNO==null){
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("不存在对应医保卡信息");
            return ajaxResponse;
        }
        String url =config.getXfmxURL()+ "?GetTable=UpayDetail&CardNO="+cardNO;
        Map map=new HashMap<>();
        String rnd= SignUtil.getUUID();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String dataString = dateFormat.format(date);
        map.put("version",config.getVersion());
        String sign=SignUtil.privateKeySign(config,map);
        map.put("sign",sign);
        Map cont=new HashMap<>();
        cont.put("date",dto.getBeginDate()+":"+dto.getEndDate());
        //cont.put("date",dto.getBeginDate()+"-01"+":"+getLastDay(dto.getEndDate()));
        //0：全部；1：消费； 2：退费；
        cont.put("type","0");
        map.put("cont",cont);
        JSONObject json = new JSONObject(map);

        String responseJson=new HttpClientUtil().qqjk(url,json.toString());
        JSONObject jsonObject = JSONObject.parseObject(responseJson);
        jsonObject = JSONObject.parseObject(jsonObject.get("cont").toString());
        jsonObject = JSONObject.parseObject(jsonObject.get("UpayDetail").toString());
        int rowcount=0;

        List<Map<String,Object>> list=new ArrayList<>();
        for(int i=0;i<rowcount;i++){
            Map<String,Object> m=new HashMap<>();
            JSONArray data = jsonObject.getJSONArray("row"+i);
            m.put("jysj",data.get(0));
            m.put("jysh",data.get(3));
            list.add(m);
        }
        ajaxResponse.setData("total",list.size());
        ajaxResponse.setData("data",list);
        return ajaxResponse;
    }

    @Override
    public AjaxResponse getBalance(KyeDTO dto) throws Exception {
        AjaxResponse ajaxResponse = new AjaxResponse();
        Object cardNO=shbzkBPO.queryCardNO(dto.getAac147(),dto.getXm(),dto.getSscs());

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = dateFormat.format(now);
        // sha1 处理秘钥
        String key = "mediCardNo="+cardNO+"&merId="+config.getMerId()+"&tradeDateTime="
                + time + "&key="+config.getKey();
        key = SignUtil.sha1(key).toUpperCase();
        // 根据医保账号方式读取余额
        String url = config.getKyeURL();
        key = "param={'tradeDateTime':'" + time
                + "','mediCardNo':'"+cardNO;
        JSONObject jsonObject = null;
        try{
            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
            long num=Long.parseLong(jsonObject.get("balance").toString());
            float d = (float)num/100;
            DecimalFormat df = new DecimalFormat("0.00");//保留2位小数
            String s = df.format(d);
            ajaxResponse.setData("balance",s);
            return ajaxResponse;
        }catch (Exception e){
            ajaxResponse.setData("balance","0.00");
            e.printStackTrace();
            return ajaxResponse;
        }
    }
    public String getLastDay(String month){
        // 获取当月的天数（需完善）
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 定义当前期间的1号的date对象
        Date date = null;
        try {
            date = dateFormat.parse(month+"-01");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH,1);//月增加1天
        Date voucherDate = calendar.getTime();
        return dateFormat.format(voucherDate);
    }
}
