package com.gxwebsoft.shop.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.service.ShopDealerUserService;
import com.gxwebsoft.shop.entity.ShopDealerUser;
import com.gxwebsoft.shop.param.ShopDealerUserParam;
import com.gxwebsoft.shop.param.ShopDealerUserImportParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 分销商用户记录表控制器
 *
 * @author 科技小王子
 * @since 2025-08-11 23:51:41
 */
@Tag(name = "分销商用户记录表管理")
@RestController
@RequestMapping("/api/shop/shop-dealer-user")
public class ShopDealerUserController extends BaseController {
    @Resource
    private ShopDealerUserService shopDealerUserService;

    @Operation(summary = "分页查询分销商用户记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<ShopDealerUser>> page(ShopDealerUserParam param) {
        // 使用关联查询
        return success(shopDealerUserService.pageRel(param));
    }

    @Operation(summary = "查询全部分销商用户记录表")
    @GetMapping()
    public ApiResult<List<ShopDealerUser>> list(ShopDealerUserParam param) {
        // 使用关联查询
        return success(shopDealerUserService.listRel(param));
    }

    @Operation(summary = "根据userId查询分销商用户")
    @GetMapping("/{id}")
    public ApiResult<ShopDealerUser> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(shopDealerUserService.getByIdRel(id));
    }

    @Operation(summary = "添加分销商用户记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ShopDealerUser shopDealerUser) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
         shopDealerUser.setUserId(loginUser.getUserId());
        }
        // 排重
        if (shopDealerUserService.count(new LambdaQueryWrapper<ShopDealerUser>().eq(ShopDealerUser::getMobile, shopDealerUser.getMobile())) > 0) {
            return fail("添加失败，手机号码已存在！");
        }
        if (shopDealerUserService.save(shopDealerUser)) {
            return success("添加成功", shopDealerUser);
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerUser:update')")
    @Operation(summary = "修改分销商用户记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ShopDealerUser shopDealerUser) {
        if (shopDealerUserService.updateById(shopDealerUser)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @Operation(summary = "修改分销商用户记录表")
    @PutMapping("/updateByUserId")
    public ApiResult<?> updateByUserId(@RequestBody ShopDealerUser shopDealerUser) {
      if (shopDealerUserService.updateByUserId(shopDealerUser)) {
        return success("修改成功");
      }
      return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerUser:remove')")
    @OperationLog
    @Operation(summary = "删除分销商用户记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (shopDealerUserService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerUser:save')")
    @OperationLog
    @Operation(summary = "批量添加分销商用户记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<ShopDealerUser> list) {
        if (shopDealerUserService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerUser:update')")
    @OperationLog
    @Operation(summary = "批量修改分销商用户记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ShopDealerUser> batchParam) {
        if (batchParam.update(shopDealerUserService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerUser:remove')")
    @OperationLog
    @Operation(summary = "批量删除分销商用户记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (shopDealerUserService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerUser:save')")
    @Operation(summary = "批量导入分销商用户")
    @Transactional(rollbackFor = {Exception.class})
    @PostMapping("/import")
    public ApiResult<List<String>> importBatch(MultipartFile file) {
        ImportParams importParams = new ImportParams();
        try {
            List<ShopDealerUserImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(), ShopDealerUserImportParam.class, importParams);
            list.forEach(d -> {
                ShopDealerUser item = JSONUtil.parseObject(JSONUtil.toJSONString(d), ShopDealerUser.class);
                assert item != null;
                if (ObjectUtil.isNotEmpty(item)) {
                    // 设置默认值
                    if (item.getIsDelete() == null) {
                        item.setIsDelete(0);
                    }
                    if (item.getSortNumber() == null) {
                        item.setSortNumber(0);
                    }
                    // 记录当前登录用户id（如果没有指定userId）
                    if (item.getUserId() == null) {
                        User loginUser = getLoginUser();
                        if (loginUser != null) {
                            item.setUserId(loginUser.getUserId());
                        }
                    }
                    shopDealerUserService.save(item);
                }
            });
            return success("成功导入" + list.size() + "条", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fail("导入失败", null);
    }

}
