package com.xy.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yitter.idgen.YitIdHelper;
import com.xy.collections.list.JArrayList;
import com.xy.collections.map.JMap;
import com.xy.dto.DeviceAnnualFeeOrdersDto;
import com.xy.entity.DeviceAnnualFee;
import com.xy.entity.DeviceAnnualFeeOrders;
import com.xy.entity.SysDictRedis;
import com.xy.mapper.DeviceAnnualFeeOrdersMapper;
import com.xy.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

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

import static com.xy.utils.PlusBeans.toIPage;
import static com.xy.utils.PlusBeans.toPageBean;


/**
 * <p>
 * 设备年费订单表 服务实现类
 * </p>
 *
 * @author lijin
 * @since 2025-02-28
 */
@Service
@AllArgsConstructor
@Api(tags = "设备年费订单表")
public class DeviceAnnualFeeOrdersServiceImpl extends ServiceImpl<DeviceAnnualFeeOrdersMapper, DeviceAnnualFeeOrders> implements DeviceAnnualFeeOrdersService {

    private DeviceAnnualFeeServiceImpl deviceAnnualFeeService;

    @Override
    @ApiOperation("购买")
    public R pay(List<DeviceAnnualFeeOrdersDto.Pay> pays) {
        LocalDateTime now = LocalDateTime.now();
        List<DeviceAnnualFeeOrders> saves = new ArrayList<>(pays.size());
        for (DeviceAnnualFeeOrdersDto.Pay pay : pays) {
            DeviceAnnualFeeOrders deviceAnnualFeeOrders = Beans.copy(DeviceAnnualFeeOrders.class, pay)
                    .setId(YitIdHelper.nextId())
                    .setOrdersId(pay.getOrderId())
                    .setCreateTime(now)
                    .setUpdateTime(now);
            saves.add(deviceAnnualFeeOrders);
        }
        saveBatch(saves);
        return R.ok();
    }

    @Override
    @ApiOperation("购买回调")
    public R payNotice(DeviceAnnualFeeOrdersDto.PayNotice payNotice) {
        //查询订单
        List<DeviceAnnualFeeOrders> deviceAnnualFeeOrderss = list(new LambdaQueryWrapper<DeviceAnnualFeeOrders>()
                .eq(DeviceAnnualFeeOrders::getOrdersId, payNotice.getOrderId())
        );
        if (!Emptys.check(deviceAnnualFeeOrderss)) {
            return R.ok();
        }
        //查询设备年费表
        List<DeviceAnnualFee> list = deviceAnnualFeeService.list(new LambdaQueryWrapper<DeviceAnnualFee>()
                .eq(DeviceAnnualFee::getMercId, deviceAnnualFeeOrderss.get(0).getMercId())
                .in(DeviceAnnualFee::getDeviceId, new JArrayList<>(deviceAnnualFeeOrderss).getProperty(DeviceAnnualFeeOrders::getDeviceId))
        );
        JMap<Long, DeviceAnnualFee> cover = new JArrayList<>(list).toMap(DeviceAnnualFee::getDeviceId).cover();
        LocalDateTime now = LocalDateTime.now();
        List<DeviceAnnualFee> updateDeviceAnnualFees = new ArrayList<>(list.size());
        List<DeviceAnnualFeeOrders> updateDeviceAnnualFeeOrderss = new ArrayList<>(deviceAnnualFeeOrderss.size());
        for (DeviceAnnualFeeOrders annualFeeOrders : deviceAnnualFeeOrderss) {
            DeviceAnnualFee deviceAnnualFee = cover.get(annualFeeOrders.getDeviceId());
            String timeout = DataTime.getStringAround(annualFeeOrders.getSize(), 0, 0, 0, 0, 0, DataTime.toString(deviceAnnualFee.getTimeout()));
            deviceAnnualFee.setTimeout(DataTime.toLocal(timeout));
            updateDeviceAnnualFees.add(deviceAnnualFee);
            if (!Emptys.check(deviceAnnualFee.getFirstTime())) {
                deviceAnnualFee.setFirstTime(now);
            }
            annualFeeOrders.setStatus(true).setUpdateTime(now);
            updateDeviceAnnualFeeOrderss.add(annualFeeOrders);
        }
        if (Emptys.check(updateDeviceAnnualFees)) {
            deviceAnnualFeeService.updateBatchById(updateDeviceAnnualFees);
        }
        if (Emptys.check(updateDeviceAnnualFeeOrderss)) {
            updateBatchById(updateDeviceAnnualFeeOrderss);
        }
        return R.ok();
    }

    @PostMapping("getAnnualFee")
    @ApiOperation("查询年费标准（无token）")
    public R<Integer> getAnnualFee(@RequestBody @Validated DeviceAnnualFeeOrdersDto.GetAnnualFee getAnnualFee) {
        Map<String, SysDictRedis> stringSysDictRedisMap = SysDictUtils.get("merc_device_annual_fee");
        SysDictRedis sysDictRedis = stringSysDictRedisMap.get(getAnnualFee.getCode());
        if (sysDictRedis == null) {
            return R.fail("配置异常，请联系开发人员");
        }
        SysDictRedis mercSysDictRedis = stringSysDictRedisMap.get(sysDictRedis.getValue());
        JSONObject jsonObject = JSONUtil.parseObj(mercSysDictRedis.getValue());
        return R.ok(jsonObject.getInt("money"));
    }

    @PostMapping("page")
    @ApiOperation("分页查询")
    public R<PageBean<DeviceAnnualFeeOrdersDto.Vo>> page(@RequestBody DeviceAnnualFeeOrdersDto.Page page) {
        LambdaQueryWrapper<DeviceAnnualFeeOrders> lambdaQueryWrapper = new MybatisPlusQuery()
                .eqWrapper(page, DeviceAnnualFeeOrders.class)
                .ge(DeviceAnnualFeeOrders::getCreateTime, page.getBeginTime())
                .le(DeviceAnnualFeeOrders::getCreateTime, page.getEndTime())
                .build();
        IPage<DeviceAnnualFeeOrders> iPage = page(toIPage(page.getPage()), lambdaQueryWrapper);
        PageBean<DeviceAnnualFeeOrdersDto.Vo> pageBean = toPageBean(DeviceAnnualFeeOrdersDto.Vo.class, iPage);
        return R.ok(pageBean);
    }

    @PostMapping("mercPage")
    @ApiOperation("商家分页查询（无token）")
    public R<PageBean<DeviceAnnualFeeOrdersDto.Vo>> mercPage(@RequestBody DeviceAnnualFeeOrdersDto.Page page) {
        return page(page);
    }
}