package com.ruoyi.demo.service.impl;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.demo.entity.*;
import com.ruoyi.demo.entity.bo.OrderAddBo;
import com.ruoyi.demo.entity.bo.PlanBo;
import com.ruoyi.demo.entity.vo.OrderVo;
import com.ruoyi.demo.mapper.*;
import com.ruoyi.demo.service.OrderService;
import com.ruoyi.demo.utils.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AppMapper appMapper;
    @Autowired
    StatisticsMapper statisticsMapper;
    @Autowired
    PlanMapper planMapper;
    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    DlUserMapper dlUserMapper;

    // 获取sign——用于测试
    @Override
    public String getSign(OrderAddBo bo) {
        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("appkey",bo.getAppkey());
        appQueryWrapper.eq("state",1);
        appQueryWrapper.eq("deleted","0");
        App app = appMapper.selectOne(appQueryWrapper);
        if (app == null)
            return "error";
        Map<String,Object> params = Dict.create()
            .set("appkey",bo.getAppkey())
            .set("createTime",bo.getTime())
            .set("dealCount",bo.getDealCount())
            .set("equipmentCode",bo.getEquipmentCode())
            .set("goodsId",bo.getGoodsId())
            .set("goodsName",bo.getGoodsName())
            .set("goodsPrice",bo.getGoodsPrice())
            .set("orderId",bo.getOrderId())
            .set("userId",bo.getUserId())
            .set("userName",bo.getUserName())
            .set("userTelephone",bo.getUserTelephone())
            .set("vendorId",bo.getVendorId())
            .set("vendorName",bo.getVendorName())
            .set("sign",null)
            .set("specs",bo.getSpecs())
            .set("state",bo.getState());
        return SignUtil.sign(params,app.getAppSecret());
    }

    // 添加订单
    @Override
    public int addOrder(OrderAddBo bo) {
        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("appkey",bo.getAppkey());
        appQueryWrapper.eq("state",1);
        appQueryWrapper.eq("deleted","0");
        App app = appMapper.selectOne(appQueryWrapper);
        if (app == null)
            return -1;
        Map<String,Object> params = Dict.create()
            .set("appkey",bo.getAppkey())
            .set("createTime",bo.getTime())
            .set("dealCount",bo.getDealCount())
            .set("equipmentCode",bo.getEquipmentCode())
            .set("goodsId",bo.getGoodsId())
            .set("goodsName",bo.getGoodsName())
            .set("goodsPrice",bo.getGoodsPrice())
            .set("orderId",bo.getOrderId())
            .set("userId",bo.getUserId())
            .set("userName",bo.getUserName())
            .set("userTelephone",bo.getUserTelephone())
            .set("vendorId",bo.getVendorId())
            .set("vendorName",bo.getVendorName())
            .set("sign",bo.getSign())
            .set("specs",bo.getSpecs())
            .set("state",bo.getState());
        if (!SignUtil.verify(params,app.getAppSecret()))
            return -3;
        // 验证通过后，如果用户不存在，则添加用户；否则更新用户信息
        QueryWrapper<Equipment> equipmentQueryWrapper = new QueryWrapper<>();
        equipmentQueryWrapper.eq("equipment_code",bo.getEquipmentCode());
        Equipment equipment = equipmentMapper.selectOne(equipmentQueryWrapper);

        QueryWrapper<DlUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id",bo.getUserId());
        DlUser user = dlUserMapper.selectOne(userQueryWrapper);

        if (user == null)
            dlUserMapper.insert(new DlUser(bo,equipment));
        else{
            user.setEndEquipmentId(equipment.getEquipmentId());
            user.setEndEquipmentName(equipment.getEquipmentName());
            user.setEndEquipmentCode(equipment.getEquipmentCode());
            user.setEndTime(bo.getTime());
            user.setTotalPrice(user.getTotalPrice() + bo.getGoodsPrice() * bo.getDealCount());
            dlUserMapper.update(user,userQueryWrapper);
        }
        // 添加交易行为记录
        statisticsMapper.insert(new Statistics(bo,equipment));
        // 添加订单
        return orderMapper.insert(new Order(bo,app));
    }

    // 查询订单列表
    @Override
    public PageInfo<List<OrderVo>> getOrderList(PlanBo bo) {
        PageHelper.startPage(bo.getPageNum(),bo.getPageSize(),true);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (bo.getText() != null)
            queryWrapper.and(orderQueryWrapper -> {
                orderQueryWrapper.like("order_id",bo.getText())
                    .or()
                    .like("goods_name",bo.getText())
                    .or()
                    .like("user_name",bo.getText())
                    .or()
                    .like("vendor_name",bo.getText());
            });
        if (bo.getStartTime() != null)
            queryWrapper.apply("create_time >= STR_TO_DATE({0},'%Y-%m-%d %H:%i:%s')",bo.getStartTime());
        if (bo.getEndTime() != null)
            queryWrapper.apply("create_time <= STR_TO_DATE({0},'%Y-%m-%d %H:%i:%s')",bo.getEndTime());
        List<Order> orders = orderMapper.selectList(queryWrapper);
        List<OrderVo> vos = new ArrayList<>();
        for (Order order : orders)
            vos.add(new OrderVo(order));
        return new PageInfo(vos);
    }
}
