package org.jeecg.modules.api.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.api.bean.PageBean;
import org.jeecg.modules.api.service.OrderService;
import org.jeecg.modules.api.utils.CommonUtils;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.pay.MpWxPayService;
import org.jeecg.modules.studytourActivity.entity.StudytourActivity;
import org.jeecg.modules.studytourActivity.service.IStudytourActivityService;
import org.jeecg.modules.studytourOrder.entity.StudytourOrder;
import org.jeecg.modules.studytourOrder.entity.StudytourOrderPerson;
import org.jeecg.modules.studytourOrder.service.IStudytourOrderPersonService;
import org.jeecg.modules.studytourOrder.service.IStudytourOrderService;
import org.jeecg.modules.studytourPerson.entity.StudytourPerson;
import org.jeecg.modules.studytourPerson.service.IStudytourPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    /******************************************************************************************************************/
    //支付接口
    @Autowired
    private MpWxPayService mpWxPayService;
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    //用户信息
    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    //研学活动信息
    @Resource
    private IStudytourActivityService studytourActivityService;
    //订单信息
    @Resource
    private IStudytourOrderService studytourOrderService;
    //出行人信息
    @Resource
    private IStudytourPersonService studytourPersonService;
    //订单出行人信息
    @Resource
    private IStudytourOrderPersonService studytourOrderPersonService;
    /******************************************************************************************************************/


    //我的订单-查询订单列表
    @Override
    public Result<?> queryOrderList(String token, StudytourOrder studytourOrder, PageBean pageBean) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //返回信息
        String massege = "";
        //分页信息
        Page<StudytourOrder> page = null;
        //查询信息
        LambdaQueryChainWrapper<StudytourOrder> query = null;
        //返回信息
        Page<StudytourOrder> pageList = null;

        try{
            //分页
            page = new Page<StudytourOrder>(pageBean.getPageNo(), pageBean.getPageSize());
            query = studytourOrderService
                    .lambdaQuery();

            //组装查询条件
            if(StringUtils.isNotBlank(studytourOrder.getStatus())){
                //订单状态
                query.eq(StudytourOrder::getStatus, studytourOrder.getStatus());
            }
            //订单所属
            query.eq(StudytourOrder::getUserId, hanHaiMember.getId());
            //按照创建时间降序排列
            query.orderByDesc(StudytourOrder::getCreateTime);

            //获取订单信息
            pageList = query.page(page);

            return Result.OK("订单列表", pageList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("订单列表查询失败");
        }
    }

    //我的订单-查询订单详情
    @Override
    public Result<?> queryOrderById(String token, String orderId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //返回信息
        String massege = "";

        try{
            //订单信息
            StudytourOrder order = studytourOrderService
                    .lambdaQuery()
                    .eq(StudytourOrder::getId, orderId)
                    .eq(StudytourOrder::getUserId, hanHaiMember.getId())
                    .one();
            if(null == order){
                return Result.error("订单详情查询失败，请检查输入的订单编号：", order);
            }

            return Result.OK("订单详情", order);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("订单详情查询失败");
        }
    }

    //我的订单-创建订单
    @Override
    public Result<?> createOrder(String token, StudytourOrder studytourOrder) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById(token);

        try{
            //0、校验活动信息
            StudytourActivity activity = studytourActivityService.getById(studytourOrder.getActivityId());
            if(null == activity){
                return Result.error("研学活动不存在，请检查活动id" + studytourOrder.getActivityId());
            }

            //1、订单信息
            String payNo = IdWorker.getIdStr();//生成订单号
            studytourOrder.setId(payNo);
            studytourOrder.setUserId(hanHaiMember.getId());

            //1.1 活动相关信息
            studytourOrder.setActivityTitle(activity.getTitle());
            studytourOrder.setActivityBrief(activity.getBrief());
            studytourOrder.setActivityTag(activity.getTagDetails());

            //1.2 出行人信息
            if(StringUtils.isNotEmpty(studytourOrder.getTourisIds())){
                String[] touristIds = studytourOrder.getTourisIds().split(";");
                List<String> ids = Arrays.asList(touristIds);
                List<StudytourPerson> personList = studytourPersonService.listByIds(ids);//出行人信息
                List<StudytourOrderPerson> orderPersonList = new ArrayList<>();//订单出行人信息
                for (StudytourPerson person : personList) {
                    StudytourOrderPerson orderPerson = new StudytourOrderPerson();
                    orderPerson.setOrderId(payNo);//关联订单id
                    orderPerson.setName(person.getName());//出行人姓名
                    orderPerson.setCerNo(person.getCerNo());//出行人身份证号
                    orderPersonList.add(orderPerson);
                }
                studytourOrderPersonService.saveBatch(orderPersonList);
            }else {
                return Result.error("出行人信息为空，至少需要一个出行人");
            }



            //2、创建订单
            studytourOrderService.save(studytourOrder);

            //3、订单支付
            //吊起微信支付
            BigDecimal price = studytourOrder.getPayAmount();//价格
            String productName = activity.getTitle();//服务名称

            String s = price.multiply(new BigDecimal(100)).toString();
            int i1 = Double.valueOf(s).intValue();
            Object appOrder = mpWxPayService.createOrder(
                    "购买"+ productName ,
                    "127.0.0.1",
                    studytourOrder.getId(),
                    i1,
                    studytourOrder.getId(),
                    hanHaiMember.getAppletOpenid(),
                    studytourOrder.toString());
            return Result.OK("支付成功",appOrder);

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("支付失败");
        }
    }

    //我的订单-支付订单
    @Override
    public Result<?> payOrder(String token, String orderId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        try{
            //订单信息
            StudytourOrder studytourOrder = studytourOrderService.getById(orderId);

            //订单支付
            //吊起微信支付
            BigDecimal price = studytourOrder.getPayAmount();//价格
            String productName = studytourOrder.getActivityTitle();//服务名称

            String s = price.multiply(new BigDecimal(100)).toString();
            int i1 = Double.valueOf(s).intValue();
            Object appOrder = mpWxPayService.createOrder(
                    "购买"+ productName ,
                    "127.0.0.1",
                    studytourOrder.getId(),
                    i1,
                    studytourOrder.getId(),
                    hanHaiMember.getAppletOpenid(),
                    studytourOrder.toString());
            return Result.OK("支付成功",appOrder);

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("支付失败");
        }
    }

    //我的订单-查询出行人列表
    @Override
    public Result<?> queryTouristList(String token, StudytourPerson studytourPerson, PageBean pageBean) {
        //权限验证
        //HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        HanHaiMember hanHaiMember = hanHaiMemberService.getById(token);
        //返回信息
        String massege = "";
        //分页信息
        Page<StudytourPerson> page = null;
        //查询信息
        LambdaQueryChainWrapper<StudytourPerson> query = null;
        //返回信息
        Page<StudytourPerson> pageList = null;

        try{
            //分页
            page = new Page<StudytourPerson>(pageBean.getPageNo(), pageBean.getPageSize());
            query = studytourPersonService
                    .lambdaQuery();

            //组装查询条件
            //出行人关联用户
            query.eq(StudytourPerson::getUserId, hanHaiMember.getId());
            //按照创建时间降序排列
            query.orderByDesc(StudytourPerson::getCreateTime);

            //获取订单信息
            pageList = query.page(page);

            return Result.OK("出行人列表", pageList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("出行人列表查询失败");
        }
    }

    //我的订单-查询出行人详情
    @Override
    public Result<?> queryTouristById(String token, String personId) {
        log.info("开始查询出行人信息");
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById(token);
        //返回信息
        String massege = "";

        try{
            //1、查询出行人详情
            StudytourPerson one = studytourPersonService.getById(personId);
            if(null == one){
                log.info("出行人信息不存在，请检查出行人id：{}", personId);
                return Result.error("出行人信息不存在，请检查出行人id："+personId);
            }

            //2、返回出行人信息
            log.info("出行人信息查询结束");
            return Result.OK("出行人信息", one);
        }catch (Exception e){
            log.info("出行人信息查询失败");
            e.printStackTrace();
            return Result.error("出行人查询失败");
        }
    }

    //我的订单-添加出行人
    @Override
    public Result<?> addTourist(String token, StudytourPerson studytourPerson) {
        log.info("添加出行人信息开始");
        //权限验证
        //HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        HanHaiMember hanHaiMember = hanHaiMemberService.getById(token);
        //返回信息
        String massege = "";

        try{
            //1、添加出行人信息
            studytourPerson.setUserId(hanHaiMember.getId());
            boolean result = studytourPersonService.save(studytourPerson);
            //判断是否新增成功
            log.info("添加出行人信息结束");
            if(result){
                return Result.OK("信息添加成功");
            }else {
                return Result.error("信息添加失败");
            }

        }catch (Exception e){
            log.error("添加出行人信息失败");
            e.printStackTrace();
            return Result.error("信息添加失败");
        }
    }

    //我的订单-修改出行人信息
    @Override
    public Result<?> updateTourist(String token, StudytourPerson studytourPerson) {
        log.info("添加出行人信息开始");
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById(token);
        //返回信息
        String massege = "";

        try{
            //1、修改出行人信息
            boolean result = studytourPersonService.updateById(studytourPerson);
            //判断是否修改成功
            log.info("修改出行人信息结束");
            if(result){
                return Result.OK("信息修改成功");
            }else {
                return Result.error("信息修改失败");
            }

        }catch (Exception e){
            log.error("修改出行人信息失败");
            e.printStackTrace();
            return Result.error("信息修改失败");
        }
    }

    //支付回调
    @Override
    public Object payOrderNotify(String requestBody) {
        WxPayOrderNotifyResult notify = mpWxPayService.notify(requestBody);
        String outTradeNo = notify.getOutTradeNo();
        log.info("支付回调订单号码："+outTradeNo);

        try{
            //查询订单信息
            StudytourOrder studytourOrder = studytourOrderService.getById(outTradeNo);
            //如果订单存在则修改订单状态
            if (null != studytourOrder){
                if("0".equals(studytourOrder.getStatus())){

                    studytourOrder.setStatus("1");//订单状态
                    studytourOrder.setPayTime(CommonUtils.getCurrentTime());//订单支付时间
                    studytourOrderService.updateById(studytourOrder);
                }
            }

        }catch (Exception e){
            log.info("支付回调失败，订单号码："+outTradeNo);
            e.printStackTrace();
        }
        return null;
    }


}
