package com.jojubanking.boot.module.system.controller.app.xytjinfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jojubanking.boot.framework.common.pojo.CommonResult;
import com.jojubanking.boot.framework.idempotent.core.annotation.Idempotent;
import com.jojubanking.boot.module.system.WebLog;
import com.jojubanking.boot.module.system.controller.admin.order.vo.OrderCreateReqVO;
import com.jojubanking.boot.module.system.controller.admin.order.vo.OrderExportReqVO;
import com.jojubanking.boot.module.system.controller.admin.xymain.vo.xyMainCreateReqVO;
import com.jojubanking.boot.module.system.controller.app.xytjinfo.vo.*;
import com.jojubanking.boot.module.system.dal.dataobject.childitem.ChilditemDO;
import com.jojubanking.boot.module.system.dal.dataobject.order.OrderDO;
import com.jojubanking.boot.module.system.dal.dataobject.student.StudentDO;
import com.jojubanking.boot.module.system.dal.dataobject.xyrw.XyrwDO;
import com.jojubanking.boot.module.system.service.childitem.ChilditemService;
import com.jojubanking.boot.module.system.service.item.ItemService;
import com.jojubanking.boot.module.system.service.order.OrderService;
import com.jojubanking.boot.module.system.service.student.StudentService;
import com.jojubanking.boot.module.system.service.xymain.xyMainService;
import com.jojubanking.boot.module.system.service.xyrw.XyrwService;
import com.jojubanking.boot.module.system.util.xytj.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.slf4j.ILoggerFactory;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import static com.jojubanking.boot.framework.common.pojo.CommonResult.success;

@Api(tags = "APP - 订单缴费")
@RestController
@RequestMapping("/member/order-info")
@Validated
@Slf4j
public class AppPayOrderController {
    static RestTemplate restTemplate = new RestTemplate();
    static HttpHeaders headers;
    static {
        headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    }

    @Resource
    private xyMainService xyMainService;
    @Resource
    private ItemService itemService;
    @Resource
    private ChilditemService childitemService;
    @Resource
    private OrderService orderService;
    @Resource
    private StudentService studentService;

    @Resource
    private XyrwService xyrwService;

    @PostMapping("/listOrder")
    @ApiOperation("创建体检信息")
    public HashMap<Object,Object> listOrder(@Valid @RequestBody FeeListVO feeListVO) throws DocumentException {
        //获取下园批次，只取开始状态的批次
        XyrwListReqVO xyrwListReqVO = new XyrwListReqVO();
        xyrwListReqVO.setBatchStatus(1);
        List<XyrwDO> listXyrw = xyrwService.getXyrwSimpleList(xyrwListReqVO);

        DecimalFormat df = new DecimalFormat("0.00");

        List<ChilditemDO> listStand = new ArrayList<>();
        OrderExportReqVO exportReqVO = new OrderExportReqVO();
        exportReqVO.setPaystatus("1");
        exportReqVO.setPatid(feeListVO.getPatid());
        exportReqVO.setBatchno(listXyrw.get(0).getBatchno());
        exportReqVO.setPackageflag(1);
        List<OrderDO> listPackage = orderService.getOrderList(exportReqVO);
        if(listPackage.size() !=0 ){
            ItemListReqVO pageReqVO = new ItemListReqVO();
            pageReqVO.setPackageno("666");
            List<ChilditemDO> list1 = childitemService.getSimpleItemList(pageReqVO);
            for(int i=0; i< list1.size(); i++){
                ChilditemDO newitem = list1.get(i);
                newitem.setItemprice(df.format(Double.parseDouble(list1.get(i).getItemprice())/100));
                listStand.add(newitem);
            }
        }
        exportReqVO.setPaystatus("1");
        exportReqVO.setPatid(feeListVO.getPatid());
        exportReqVO.setBatchno(listXyrw.get(0).getBatchno());
        exportReqVO.setPackageflag(0);
        List<OrderDO> listAddtion = orderService.getOrderList(exportReqVO);

        HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
        resultMap.put("listStand", listStand);
        resultMap.put("listAddtion", listAddtion);
        resultMap.put("errCode","0");
        resultMap.put("errMsg", "");
        return resultMap;
    }

    @PostMapping("/updateOrder")
    @ApiOperation("创建体检信息")
    @WebLog(description = "updateOrder")
    public HashMap<Object,Object> updateOrder(@Valid @RequestBody FeeUpdateVO feeUpdateVO) throws DocumentException {
        //根据收据号更新支付状态
        //获取下园批次，只取开始状态的批次
        XyrwListReqVO xyrwListReqVO = new XyrwListReqVO();
        xyrwListReqVO.setBatchStatus(1);
        List<XyrwDO> listXyrw = xyrwService.getXyrwSimpleList(xyrwListReqVO);

        OrderDO orderDO = new OrderDO();
        orderDO.setOrderno(feeUpdateVO.getOrderid());

        orderDO.setPaystatus("1");
        orderService.updateOrderByNotify(orderDO);

        //更新学生表的缴费标识
        StudentDO studenDO = new StudentDO();
        studenDO.setOrderno(feeUpdateVO.getOrderid());
        studenDO.setBatchno(listXyrw.get(0).getBatchno());

        studenDO.setFeeflag(1);
        studentService.updateOrderByNotify(studenDO);

        HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
        resultMap.put("errCode","0");
        resultMap.put("errMsg", "");
        return resultMap;
    }

    @PostMapping("/confirmOrder")
    @ApiOperation("创建体检信息")
    @WebLog(description = "confirmOrder")
    public HashMap<Object,Object> confirmOrder(@Valid @RequestBody FeeInfoVO feeInfoVO) throws DocumentException {
        //预结算的时候 更新sjh
        //获取下园批次，只取开始状态的批次
        XyrwListReqVO xyrwListReqVO = new XyrwListReqVO();
        xyrwListReqVO.setBatchStatus(1);
        List<XyrwDO> listXyrw = xyrwService.getXyrwSimpleList(xyrwListReqVO);

        //更新必选体检项目
        ItemListReqVO pageReqVO = new ItemListReqVO();
        String packageNo = "";
        for(int j=0; j<feeInfoVO.getDetail().size(); j++){
            pageReqVO.setItemname(feeInfoVO.getDetail().get(j).getYpmc());
            List<ChilditemDO> list1 = childitemService.getSimpleItemList(pageReqVO);
            for(int i=0; i<list1.size(); i++){
                packageNo = list1.get(i).getPackageno();
                break;
            }
            if(!packageNo.equals("")){
                //只要取到packageno，就退出，以为基础包就一个代码
                //更新order表
                OrderDO orderDO = new OrderDO();
                orderDO.setBatchno(listXyrw.get(0).getBatchno());
                orderDO.setPatid(feeInfoVO.getPatid());
                orderDO.setPackageno(packageNo);

                orderDO.setPaystatus("0");
                orderDO.setSjh(feeInfoVO.getSjh());
                orderDO.setOrderno(feeInfoVO.getOrderId());
                orderService.updateOrderByPay(orderDO);

                break;
            }
        }

        //更新可选体检项目
        String itemname = "";
        for(int j=0; j<feeInfoVO.getDetail().size(); j++){
            OrderExportReqVO exportReqVO = new OrderExportReqVO();
            exportReqVO.setItemname(feeInfoVO.getDetail().get(j).getYpmc());
            exportReqVO.setBatchno(listXyrw.get(0).getBatchno());
            exportReqVO.setPatid(feeInfoVO.getPatid());
            List<OrderDO> lstorder = orderService.getOrderList(exportReqVO);

            if(lstorder.size() != 0){
                //更新order表
                OrderDO orderDO = new OrderDO();
                orderDO.setBatchno(listXyrw.get(0).getBatchno());
                orderDO.setPatid(feeInfoVO.getPatid());
                orderDO.setItemname(feeInfoVO.getDetail().get(j).getYpmc());
                //可选项包编号总是0
                orderDO.setPackageno("0");

                orderDO.setPaystatus("0");
                orderDO.setSjh(feeInfoVO.getSjh());
                orderDO.setOrderno(feeInfoVO.getOrderId());
                orderService.updateOrderByPay(orderDO);
            }
        }

        //更新学生表的缴费标识
        StudentDO studenDO = new StudentDO();
        studenDO.setPatid(feeInfoVO.getPatid());
        studenDO.setBatchno(listXyrw.get(0).getBatchno());

        studenDO.setOrderno(feeInfoVO.getOrderId());
        studentService.updateOrderByConfirm(studenDO);

        HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
        resultMap.put("errCode","0");
        resultMap.put("errMsg", "");
        return resultMap;
    }

    @PostMapping("/payorder")
    @ApiOperation("创建体检信息")
    @WebLog(description = "payorder")
    @Idempotent(timeout = 10, message = "重复请求，请稍后重试")
    public HashMap<Object,Object> payorder(@Valid @RequestBody xyMainOrderVO xyOrderVO) throws DocumentException {
        List<HashMap<Object,Object>> listSuccess = new ArrayList<>();;
        List<HashMap<Object,Object>> listFail = new ArrayList<>();;

        //获取下园批次，只取开始状态的批次
        XyrwListReqVO xyrwListReqVO = new XyrwListReqVO();
        xyrwListReqVO.setBatchStatus(1);
        List<XyrwDO> listXyrw = xyrwService.getXyrwSimpleList(xyrwListReqVO);

        //自动生成订单号
        // 设置六位数支付订单号
//        String payOrderNo = "TJ" + VeDate.getNo(6);

        //处理基础项目
//        "iteminfo": [
//        {
//            "packageflag": 1,
//                "packageno": "666",
//                "itemflag": 0,
//                "itemno": "验光、视网膜视力检查、龋齿防护、儿童入托体检新、静脉采血(检验科)、儿童体检血常规新(体检)、体检肝功(体检)",
//                "itemname": "基础项目",
//                "itemprice": "89.66",
//                "id": 121,
//                "createTime": 1704881523000,
//                "checked": true
//        }
//	],
        //基础套餐，1. 获取套餐明细
        //2.轮询套餐中的子项目，开单

        //处理可选项目 1.轮询可选项目开单
//        "itemkxinfo": [
//        {
//            "packageflag": 0,
//                "packageno": "0",
//                "itemflag": 1,
//                "itemno": "250308008",
//                "itemname": "血清骨钙素测定",
//                "itemprice": "56.00",
//                "id": 133,
//                "createTime": 1704881689000,
//                "checked": true
//        }
//	   ]
        //如果是package，更新itemno为明细,后期还要优化
        JSONArray jsonPArray = xyOrderVO.getIteminfo();
        if(jsonPArray.size() != 0){
            Double number = 0.00;
            ItemListReqVO pageReqVO = new ItemListReqVO();
            pageReqVO.setPackageno("666");

            List<ChilditemDO> list1 = childitemService.getSimpleItemList(pageReqVO);
            for(int i=0; i<list1.size(); i++){
                String lcflag = String.valueOf(list1.get(i).getItemflag());
                String ypdm = "";
                String lcxmdm = "";
                String lcxmbz = "";
                if(lcflag.equals("1")) {
                    ypdm = list1.get(i).getItemno();
                    lcxmdm = "0";
                    lcxmbz = "1";
                }else {
                    ypdm = "0";
                    lcxmdm = list1.get(i).getItemno();
                    lcxmbz = "2";
                }
                HashMap<Object,Object> zdkdMap = WSUtil.zdkd(xyOrderVO.getPatid(),ypdm,  lcxmdm, lcxmbz,
                        list1.get(i).getItemname(), list1.get(i).getZxks());
                if("0".equals(zdkdMap.get("errCode"))) {
                    log.info(lcxmdm + "：开单成功");

                    //基础项目，order表中应该只有一条记录
                    //插入order表
//                    OrderCreateReqVO createReqVO = new OrderCreateReqVO();
//                    createReqVO.setPatid(xyOrderVO.getPatid());
//                    createReqVO.setItemno(list1.get(i).getItemno());
//                    createReqVO.setItemprice(list1.get(i).getItemprice());
//                    createReqVO.setBatchno(listXyrw.get(0).getBatchno());
//                    createReqVO.setItemflag(list1.get(i).getItemflag());
//                    createReqVO.setItemname(list1.get(i).getItemname());
//                    createReqVO.setOrderno("");
//                    createReqVO.setPackageflag(1);
//                    createReqVO.setPackageno("666");
//                    orderService.createOrder(createReqVO);
                    number += Double.parseDouble(list1.get(i).getItemprice());
                    listSuccess.add(zdkdMap);
                }else{
                    log.info(lcxmdm + "：开单失败");
                    listFail.add(zdkdMap);
                }
            }

            //基础项目，order表中应该只有一条记录
            //插入order表
            DecimalFormat df = new DecimalFormat("0.00");

            OrderCreateReqVO createReqVO = new OrderCreateReqVO();
            createReqVO.setPatid(xyOrderVO.getPatid());
            createReqVO.setItemno("0");
            createReqVO.setItemprice(df.format(number/100));
            createReqVO.setBatchno(listXyrw.get(0).getBatchno());
            createReqVO.setItemflag(0);
            createReqVO.setItemname("乙肝两对半");
            createReqVO.setOrderno("");
            createReqVO.setPackageflag(1);
            createReqVO.setPackageno("666");
            createReqVO.setPaystatus("0");
            createReqVO.setSchoolName(xyOrderVO.getSchoolName());
            createReqVO.setClassName(xyOrderVO.getClassName());
            createReqVO.setName(xyOrderVO.getName());
            createReqVO.setNationid(xyOrderVO.getNationId());
            //设置开单科室信息
            createReqVO.setKdks("1071");
            createReqVO.setKdksname("健康管理科");

            //更新性别
            //从身份证号计算年龄和性别
            String idCardNumber = xyOrderVO.getNationId();
            IDCardParser parser = new IDCardParser(idCardNumber);
            parser.parse();

            String birthDate = parser.getBirthDate();
            int gender = parser.getGender();
            createReqVO.setSex(gender);
            orderService.createOrder(createReqVO);

        }

        JSONArray jsonArray = xyOrderVO.getItemkxinfo();
        // 使用for循环遍历JSONArray
        for (int j = 0; j < jsonArray.size(); j++) {
            JSONObject jsonObject = jsonArray.getJSONObject(j);
            // 处理jsonObject
            String lcflag = jsonObject.getString("itemflag");
            String ypdm = "";
            String lcxmdm = "";
            String lcxmbz = "";
            if(lcflag.equals("1")) {
                ypdm = jsonObject.getString("itemno");
                lcxmdm = "0";
                lcxmbz = "1";
            }else {
                ypdm = "0";
                lcxmdm = jsonObject.getString("itemno");
                lcxmbz = "2";
            }
            HashMap<Object,Object> zdkdMap = WSUtil.zdkd(xyOrderVO.getPatid(),ypdm,  lcxmdm, lcxmbz,
                    jsonObject.getString("itemname"), jsonObject.getString("zxks"));
            if("0".equals(zdkdMap.get("errCode"))) {
                log.info(lcxmdm + "：开单成功");
                //插入order表
                OrderCreateReqVO createReqVO = new OrderCreateReqVO();
                createReqVO.setPatid(xyOrderVO.getPatid());
                createReqVO.setItemno(jsonObject.getString("itemno"));
                createReqVO.setItemprice(jsonObject.getString("itemprice"));
                createReqVO.setBatchno(listXyrw.get(0).getBatchno());
                createReqVO.setItemflag(jsonObject.getInteger("itemflag"));
                createReqVO.setItemname(StringUtils.deleteWhitespace(jsonObject.getString("itemname")));
                createReqVO.setOrderno("");
                createReqVO.setPackageflag(0);
                createReqVO.setPackageno("0");
                createReqVO.setName(xyOrderVO.getName());
                createReqVO.setSchoolName(xyOrderVO.getSchoolName());
                createReqVO.setClassName(xyOrderVO.getClassName());
                createReqVO.setNationid(xyOrderVO.getNationId());
                //设置开单科室信息
                createReqVO.setKdks(jsonObject.getString("kdks"));
                createReqVO.setKdksname(jsonObject.getString("kdksname"));
                createReqVO.setZxks(jsonObject.getString("zxks"));
                createReqVO.setZxksname(jsonObject.getString("zxksname"));
                //更新性别
                //从身份证号计算年龄和性别
                String idCardNumber = xyOrderVO.getNationId();
                IDCardParser parser = new IDCardParser(idCardNumber);
                parser.parse();

                String birthDate = parser.getBirthDate();
                int gender = parser.getGender();
                createReqVO.setSex(gender);

                orderService.createOrder(createReqVO);

                listSuccess.add(zdkdMap);
            }else{
                log.info(lcxmdm + "：开单失败");
                listFail.add(zdkdMap);

            }

        }

        HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
        resultMap.put("list",listSuccess);
        resultMap.put("listF",listFail);
        resultMap.put("errCode","0");
        resultMap.put("errMsg", "");
        return resultMap;
    }

    /* -----------------------------------------------------银联商务支付信息-------------------------------------------------- */

    /**
     * @description 获取银联商务支付信息
     * @author dqzhang
     * @created 2021年11月19日 下午5:31:26
     * @return
     * @throws Exception
     */
    @RequestMapping("/getPayRequest")
    @ResponseBody
    public Object getPayRequest(String openid,String totalAmount,String patid,String cardno,String cardtype) throws Exception{

        cardno = StringDUtil.removeSpaces(cardno);
        if("".equals(cardno)) {
            HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
            resultMap.put("errCode", "noCardNo");
            resultMap.put("errMsg", "卡号不能为空！");
            return resultMap;
        }
        //先判断卡号是否已挂失
//        HashMap<Object,Object> map1 = WSUtil.getPatient(cardno, cardtype);
//        String errCode = StringDUtil.changeNullToEmpty(map1.get("errCode"));
//        if("0".equals(errCode)) {
//            HashMap<Object,Object> patientMap = (HashMap<Object, Object>) ((List)map1.get("list")).get(0);
//            log.debug("patientMap"+patientMap);
//            String ghbz = StringDUtil.changeNullToEmpty(patientMap.get("gsbz"));
//            if("1".equals(ghbz)) {
//                HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
//                resultMap.put("errCode", "LossReported");
//                resultMap.put("errMsg", "卡已挂失/停用，请至窗口处理！");
//                return resultMap;
//            }
//
//            String pid = StringDUtil.changeNullToEmpty(patientMap.get("patid"));
//            if("".equals(pid)) {
//                HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
//                resultMap.put("errCode", "IDCardNotAllowed");
//                resultMap.put("errMsg", "身份证不能充值，请选择其它卡！");
//                return resultMap;
//            }
//        }else {
//            HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
//            resultMap.put("errCode", map1.get("errCode"));
//            resultMap.put("errMsg", map1.get("errMsg"));
//            return resultMap;
//        }

        BigDecimal bd = new BigDecimal(totalAmount).multiply(new BigDecimal(100));
        totalAmount = bd.intValue()+"";
        TreeMap<Object,Object> map = new TreeMap<Object,Object>();
        //map.put("msgId", "12YK");
        map.put("msgSrcId", "12YK");
        map.put("msgSrc", "WWW.KRLSFYBJ.COM");
        map.put("msgType", "wx.unifiedOrder");
        map.put("requestTimestamp", DateDUtil.getTheCurrentTime());
        String merOrderId = "12YK"+DateDUtil.DateToStrPlus("yyyyMMddHHmmssSSS", new Date())/* + StringDUtil.randomInt(3)*/;
        map.put("merOrderId", merOrderId);
        map.put("mid", "898652880620011");
        map.put("tid", "65954193");
        map.put("totalAmount", totalAmount);
        map.put("subOpenId", openid);
        map.put("tradeType", "MINI");
        map.put("signType", "SHA256");
        String key = "KfG8PnwGSK8AXQFKtyfQnKi3x5kcZtDkWX2tctAMhcF5e6Ax";
        StringBuilder str = new StringBuilder();
        for(Map.Entry<Object, Object> e: map.entrySet()) {
            str.append(e.getKey());
            str.append("=");
            str.append(e.getValue());
            str.append("&");
        }
        str.deleteCharAt(str.length()-1);
        str.append(key);
        String sign = EncryptUtil.getSHA256Str(str.toString());
        map.put("sign", sign.toUpperCase());
        String url = "https://qr.chinaums.com/netpay-route-server/api/";
        String requestData = JSON.toJSONString(map);
        HttpEntity<String> entity = new HttpEntity<String>(requestData, headers) ;
        ResponseEntity<HashMap> resp =restTemplate.exchange(url, HttpMethod.POST, entity, HashMap.class);
        HashMap respBody = resp.getBody();
        //支付信息写入本地数据库
        try {
            String ec = StringDUtil.changeNullToEmpty(respBody.get("errCode"));
            if("SUCCESS".equals(ec)) {
                url =  StatusDefine.IP_PORT+"/api/addPayRequest";
                HashMap<Object,Object> requestMap = new HashMap<Object,Object>();
                requestMap.put("merOrderId", merOrderId);
                requestMap.put("totalAmount", totalAmount);
                requestMap.put("orderText", JSON.toJSONString(respBody));
                requestMap.put("patid", patid);
                requestMap.put("openid", openid);
                requestMap.put("status", respBody.get("status"));
                String requestBody = JSON.toJSONString(requestMap);
                entity = new HttpEntity<String>(requestBody, headers) ;
                ResponseEntity<HashMap> result =restTemplate.exchange(url, HttpMethod.POST, entity, HashMap.class);
                HashMap resultMap = result.getBody();
                if(!"0".equals(resultMap.get("errCode"))) {
                    log.error("写入下单信息失败"+resultMap.get("errMsg"));
                }
            }else {
                log.error("下单信息异常"+JSON.toJSONString(respBody));
            }
        } catch (Exception e1) {
            log.error("写入下单信息失败"+e1.toString());
        }
        return resp.getBody();
    }

}
