
package com.yami.shop.platform.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.Channel;
import com.yami.shop.bean.param.OrderRefundStaisticsParam;
import com.yami.shop.bean.vo.ChannelVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.ChannelService;
import com.yami.shop.service.UserService;
import com.yami.shop.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 渠道管理控制器
 *
 * @author lgh on 2024/01/01.
 */
@RestController
@RequestMapping("/platform/channel")
@Api(tags = "渠道管理接口")
@AllArgsConstructor
public class ChannelController {
    private final ChannelService channelService;
    private final UserService userService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 查询全部
     */
    @GetMapping("/listAll")
    @ApiOperation(value = "查询全部")
    public R<List<Channel>> listAll() {
        List<Channel> channels = channelService.list();
        return R.SUCCESS(channels);
    }
    /**
     * 根据规则类型查询全部
     */
    @GetMapping("/listAllSplitRule")
    @ApiOperation(value = "根据规则类型查询全部")
    public R<List<Channel>> listAllSplitRule(@RequestParam(value = "splitRule") Integer splitRule) {
        List<Channel> channels = channelService.list(new LambdaQueryWrapper<Channel>().eq(Channel::getSplitRule, splitRule));
        return R.SUCCESS(channels);
    }

    /**
     * 根据渠道ID获取商品列表
     */
    @GetMapping("/listProd/{id}")
    @ApiOperation(value = "根据渠道ID获取商品列表")
    public R<Channel> listProd(@PathVariable String id) {
        Channel channel = channelService.getById(id);
        return R.SUCCESS(channel);
    }

    /**
     * 分页获取政企列表统计
     */
    @GetMapping("/statisticsPage")
    @ApiOperation(value = "分页获取政企列表统计")
    public R<IPage<ChannelVO>> statisticsPage(PageParam pageParam, Channel channel ) {
        getChannel(channel);
        IPage<ChannelVO> page = channelService.statisticsPage(pageParam,channel);
        return R.SUCCESS(page);
    }

    /**
     * 添加
     */
    @PostMapping
    @ApiOperation(value = "添加")
    public R add(@RequestBody Channel channel) {
        channel.setCreateTime(new Date());
        //获取最后一条数据编号
        channelService.save(channel);
        return R.SUCCESS();
    }
    /**
     * 修改
     */
    @PutMapping
    @ApiOperation(value = "修改")
    public R update(@RequestBody Channel channel) {
        channelService.updateById(channel);
        return R.SUCCESS();
    }

    /**
     * 批量修改
     */
    @PutMapping("/batch")
    @ApiOperation(value = "批量修改")
    public R batchUpdate(@RequestParam(value = "splitRule") Integer splitRule, @RequestBody List<Channel> channels) {
        if (splitRule == null){
            R.FAIL( "请传入拆单规则 splitRule" );
        }
        channelService.updateSplitRule(splitRule);
        channelService.updateBatchById(channels);
        return R.SUCCESS();
    }


    @GetMapping("/list")
    @ApiOperation(value = "查询全部")
    public R<List<Channel>> listByUserId() {
        Long userId = null;
        try {
            userId = SecurityUtils.getSysUser().getUserId();
        } catch (Exception e) {
            throw new GlobalException("获取当前登录用户失败");
        }
        List<Channel> channels = null;
        if(userId == Constant.SUPER_ADMIN_ID){
            channels = channelService.list();
        }else {
            channels = sysUserService.findByUserId(userId);
        }
        Channel channel = new Channel();
        channel.setId(0L);
        channel.setChannelName("全部");
        if (channels==null){
            channels =new ArrayList<Channel>();
        }
        channels.add(0,channel);
        return R.SUCCESS(channels);
    }

    private void getChannel(Channel channel){
        if (channel.getChannelIdList()==null||channel.getChannelIdList().isEmpty()){
            throw new GlobalException("请求参数-所属企业不允许为空");
        }
        if (ObjectUtil.isEmpty(channel.getUserAttrType())){
            channel.setUserAttrType("1");//默认查询正常人员属性
        }
        if (channel.getChannelIdList().contains(0L)){
            Long userId = null;
            try {
                userId = SecurityUtils.getSysUser().getUserId();
            } catch (Exception e) {
                throw new GlobalException("获取当前登录用户失败");
            }
            List<Long> channelIdList =  sysUserService.findByUserIdListId(userId);
            channel.setChannelIdList(channelIdList);
            if (userId != Constant.SUPER_ADMIN_ID&&(channel.getChannelIdList()==null||channel.getChannelIdList().isEmpty())){
                List<Long> longs = new ArrayList<>();
                longs.add(0L);
                channel.setChannelIdList(longs);
            }
        }
    }
}
