package thyyxxk.webserver.service.mzpayqrcode;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.Capacity;
import thyyxxk.webserver.dao.his.mzpayqrcode.MzPayQrcodeDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.mzpayqrcode.PatInfo;
import thyyxxk.webserver.entity.mzpayqrcode.RoughIndex;
import thyyxxk.webserver.service.externalhttp.ThmzSystem;
import thyyxxk.webserver.utils.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dj
 */
@Slf4j
@Service
public class MzPayQrcodeService {
    private final MzPayQrcodeDao dao;
    private static final String MZ_PAY_QRCODE_URL = "http://192.168.200.3/wxserver/wxApi/genMzPayQrcode";
    private static final int MIN_PATIENT_ID_LENGTH = 7;
    private final ThmzSystem thmz;
    @Value("${thmz-api-url}")
    private String thmzApiUrl;

    @Autowired
    public MzPayQrcodeService(MzPayQrcodeDao dao, ThmzSystem thmz) {
        this.dao = dao;
        this.thmz = thmz;
    }

    private PatInfo getPatientInfo(String patientId) {
        String socialNo = dao.selectSocialNoByPatientId(patientId);
        JSONObject obj = new JSONObject();
        obj.put("patIdType", 11);
        obj.put("patIdNo", socialNo);
        return thmz.queryPatientInfo(thmzApiUrl, obj);
    }

    public ResultVo<List<Map<String, String>>> getRoughList(String patientId) {
        if (null == patientId || patientId.length() < MIN_PATIENT_ID_LENGTH) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请输入正确的门诊ID号。");
        }
        patientId = patientId.trim();
        JSONObject obj = new JSONObject();
        obj.put("patCardType", 21);
        obj.put("patCardNo", patientId);
        obj.put("hisOrdNum", "");
        Map<String, Object> hrgRes = thmz.getMzChargeDetailForUnPaid(thmzApiUrl, obj);
        if (null == hrgRes) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "网络服务错误！");
        }
        if ((int) hrgRes.get("resultCode") != 0 ) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, hrgRes.get("resultMessage").toString());
        }
        List<Map<String, String>> list = FilterUtil.cast(hrgRes.get("data"));
        for (Map<String, String> item : list) {
            item.put("fixedAmt", DecimalUtil.divide(String.valueOf(item.get("totalAmt")), "100", 2));
        }
        return ResultVoUtil.success(list);
    }

    @SuppressWarnings("unchecked")
    public ResultVo<JSONObject> getDetailFees(RoughIndex param) {
        PatInfo patInfo = getPatientInfo(param.getPatientId());
        if (null == patInfo || null == patInfo.getResultCode() || 0 != patInfo.getResultCode()) {
            return ResultVoUtil.fail(ExceptionEnum.INTERNAL_SERVER_ERROR, "无法获取到患者个人信息！");
        }
        JSONObject obj = new JSONObject();
        obj.put("patCardType", 21);
        obj.put("patCardNo", param.getPatientId());
        obj.put("hisOrdNum", param.getHisOrdNum());
        Map<String, Object> hrgRes = thmz.getChargeDetailByHisOrdNum(thmzApiUrl, obj);
        if (null == hrgRes) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "网络服务错误！");
        }
        if ((int) hrgRes.get("resultCode") != 0 ) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, hrgRes.get("resultMessage").toString());
        }
        List<Map<String, String>> list = FilterUtil.cast(hrgRes.get("data"));
        JSONObject retObj = new JSONObject();
        retObj.put("list", makeSimpleData(list));
        RestTemplate restTemplate = new RestTemplate();
        ResultVo<String> qrResult = restTemplate.postForObject(MZ_PAY_QRCODE_URL, param, ResultVo.class);
        if (null == qrResult || qrResult.getCode() != ExceptionEnum.SUCCESS.getCode()) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请求微信支付二维码失败，请联系管理员。");
        }
        retObj.put("wxQrcode", qrResult.getData());
        return ResultVoUtil.success(retObj);
    }

    private JSONArray makeSimpleData(List<Map<String, String>> arr) {
        JSONArray array = new JSONArray();
        Map<String, String> map = new HashMap<>(Capacity.DEFAULT);
        for (Map<String, String> item : arr) {
            final String itemType = "".equals(item.get("itemType")) ?
                    " - " : item.get("itemType");
            String execDeptName = "".equals(item.get("execDeptName")) ?
                    " - " : item.get("execDeptName");
            String execDeptAddress = "".equals(item.get("execDeptAddress")) ?
                    " - " : item.get("execDeptAddress");
            if ("静脉采血".equals(item.get("itemName"))) {
                execDeptName = "急诊抽血室";
                execDeptAddress = "门诊大楼一楼";
            }
            String key = itemType + "^" + execDeptName + "^" + execDeptAddress;
            if (!map.containsKey(key)) {
                map.put(key, String.valueOf(item.get("itemTotalFee")));
            } else {
                String fee = DecimalUtil.add(String.valueOf(map.get(key)), String.valueOf(item.get("itemTotalFee")));
                map.replace(key, fee);
            }
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String[] keys = entry.getKey().split("\\^");
            JSONObject obj = new JSONObject();
            obj.put("itemType", keys[0]);
            obj.put("execDeptName", keys[1]);
            obj.put("execDeptAddress", keys[2]);
            obj.put("itemTotalFee", entry.getValue());
            obj.put("fixedAmt", DecimalUtil.divide(entry.getValue(), "100", 2));
            array.add(obj);
        }
        return array;
    }
}
