package com.yami.shop.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.Transport2;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.delivery.comment.service.Transport2Service;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/platform/transport2")
public class Transport2Controller {

    @Autowired
    private Transport2Service transportService;

    @GetMapping("/transport2List")
    @ApiOperation("后管端-企业运费列表")
    public R<IPage<Transport2>> transport2List(PageParam<Transport2> page) {
        IPage<Transport2> orderIPage = transportService.transport2List(page);
        return R.SUCCESS(orderIPage);
    }


    @GetMapping("/queryTransport2ByChannelId/{channelId}")
    @ApiOperation(value = "企业ID查询运费模板")
    public R<Transport2> queryTransport2ByChannelId(@PathVariable("channelId") Long channelId) {
        return R.SUCCESS(transportService.queryTransport2ByChannelId(channelId));
    }

    @PostMapping("/addOrEdit")
    @ApiOperation(value = "新增或更新运费模板")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> addOrEdit(@RequestBody List<Transport2> transport2List) {
        if (transport2List != null && !transport2List.isEmpty()) {
            transport2List.forEach(transport -> {
                Long channelId = transport.getChannelId();
                if (channelId != null) {
                    Transport2 transport2 = transportService.queryTransport2ByChannelId(channelId);
                    if (transport2 != null) {
                        transport2.setDistance(transport.getDistance());
                        transport2.setWeight(transport.getWeight());
                        transport2.setFreightFee(transport.getFreightFee());
                        transportService.updateById(transport2);
                    }
                }

                if (transport.getTransportId() != null) {
                    transportService.updateById(transport);
                } else {
                    transportService.save(transport);
                }
            });
        }
        return R.SUCCESS();
    }
}
