package com.jojubanking.boot.module.system.service.order;

import com.alibaba.fastjson.JSONObject;
import com.jojubanking.boot.module.system.controller.admin.student.vo.StudentExportReqVO;
import com.jojubanking.boot.module.system.controller.app.xytjinfo.vo.XyrwListReqVO;
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.framework.tjfiles.TjfilesProperties;
import com.jojubanking.boot.module.system.service.student.StudentService;
import com.jojubanking.boot.module.system.service.xyrw.XyrwService;
import com.jojubanking.boot.module.system.util.xytj.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.jojubanking.boot.module.system.controller.admin.order.vo.*;
import com.jojubanking.boot.module.system.dal.dataobject.order.OrderDO;
import com.jojubanking.boot.framework.common.pojo.PageResult;

import com.jojubanking.boot.module.system.convert.order.OrderConvert;
import com.jojubanking.boot.module.system.dal.mysql.order.OrderMapper;

import static com.jojubanking.boot.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jojubanking.boot.module.system.enums.ErrorCodeConstants.*;

/**
 * 检查项目订单 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private StudentService studentService;
    @Resource
    private TjfilesProperties tjfilesProperties;
    @Resource
    private XyrwService xyrwService;

    @Override
    public Long createOrder(OrderCreateReqVO createReqVO) {
        // 插入
        OrderDO order = OrderConvert.INSTANCE.convert(createReqVO);
        orderMapper.insert(order);
        // 返回
        return order.getId();
    }

    @Override
    public void updateOrderByPay(OrderDO tjOrderDO){
        orderMapper.updateOrderByPay(tjOrderDO);
    }

    @Override
    public void updateOrderAfter24(){
//        update xytj_order set deleted = true WHERE DATE(create_time) = CURDATE() - INTERVAL 1 DAY  AND TIME(create_time) < '24:00:00'
//        and (paystatus != '1' or  paystatus IS NULL)")" +
//        StudentExportReqVO exportReqVO = new StudentExportReqVO();
//        List<StudentDO> list = studentService.getStudentList(exportReqVO);

        //取出paystatus为0 的记录
        //orderno非空，查询缴费记录，如果已缴费则更新paystatus 为1
        List<OrderDO> lstOrder = orderMapper.selectOrderAfter24();
        log.info("tj 定时查询订单号,total：" + lstOrder.size());
        for(int i=0 ; i<lstOrder.size();i++) {
            OrderDO order = lstOrder.get(i);
            if(order.getOrderno() != null && order.getDeleted() == false){
                //如果订单号不为空，并且没有删除，则查询缴费记录
                log.info("tj 定时查询订单号:" + lstOrder.get(i).getOrderno());
                //paystatus 如果是0，就去微信复核一下，如果已支付就更新student和order表的标识，并更新list的feeflag
                String ipport = tjfilesProperties.getIpport();
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("out_trade_no", lstOrder.get(i).getOrderno());
                String res = HttpClientUtil.doPost(ipport + "/api/wxpay/findWxPayResult", jsonParam);
                log.info("tj 定时查询订单号返回:" + res);

                JSONObject jsonResult = JSONObject.parseObject(res);
                if (jsonResult.get("errCode").equals("0")) {
                    JSONObject data = jsonResult.getJSONObject("data");
                    if (data.get("tradeState").equals("SUCCESS")) {
                        log.info("定时查询，确认该学生已付款");

                        //更新student表的feeflag和order表的paystatus
                        //根据收据号更新支付状态
                        //获取下园批次，只取开始状态的批次
                        XyrwListReqVO xyrwListReqVO = new XyrwListReqVO();
                        xyrwListReqVO.setBatchStatus(1);
                        List<XyrwDO> listXyrw = xyrwService.getXyrwSimpleList(xyrwListReqVO);

                        OrderDO orderDO = new OrderDO();
                        orderDO.setOrderno(lstOrder.get(i).getOrderno());

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

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

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

            }
        }
        log.info("开始定时查询，软删除paystatus为0的订单");
        orderMapper.updateOrderAfter24();
        log.info("结束定时查询，软删除paystatus为0的订单");
    }

    @Override
    public void updateOrderByNotify(OrderDO tjOrderDO){
        orderMapper.updateOrderByNotify(tjOrderDO);
    }

    @Override
    public void updateOrder(OrderUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateOrderExists(updateReqVO.getId());
        // 更新
        OrderDO updateObj = OrderConvert.INSTANCE.convert(updateReqVO);
        orderMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrder(Long id) {
        // 校验存在
        this.validateOrderExists(id);
        // 删除
        orderMapper.deleteById(id);
    }

    private void validateOrderExists(Long id) {
        if (orderMapper.selectById(id) == null) {
            throw exception(ORDER_NOT_EXISTS);
        }
    }

    @Override
    public OrderDO getOrder(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public List<OrderDO> getOrderList(Collection<Long> ids) {
        return orderMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<OrderDO> getOrderPage(OrderPageReqVO pageReqVO) {
        return orderMapper.selectPage(pageReqVO);
    }

    @Override
    public List<OrderDO> getOrderList(OrderExportReqVO exportReqVO) {
        return orderMapper.selectList(exportReqVO);
    }

    @Override
    public List<OrderSumRespVO> getOrderSumList(String batchno, String schoolName, String className,
                                                String itemname, Integer sex, String dateRangeStart, String dateRangeEnd){
        return orderMapper.getSumList( batchno,  schoolName,  className, itemname,  sex,  dateRangeStart,  dateRangeEnd);
    }

}
