package shop.alien.storeplatform.controller;

import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.StoreUserVo;
import shop.alien.storeplatform.dto.AddAlipayAccountDTO;
import shop.alien.storeplatform.dto.SetPayPasswordDTO;
import shop.alien.storeplatform.service.MerchantUserService;
import shop.alien.storeplatform.util.LoginUserUtil;

import java.util.Map;

/**
 * web端商户用户管理控制器
 *
 * @author ssk
 * @since 2025-01-xx
 */
@Slf4j
@Api(tags = {"web端商户用户管理"})
@ApiSort(5)
@CrossOrigin
@RestController
@RequestMapping("/merchantUser")
@RequiredArgsConstructor
public class MerchantUserController {

    private final MerchantUserService merchantUserService;

    @ApiOperation("根据手机号获取商户用户信息")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/getMerchantByPhone")
    public R<StoreUserVo> getMerchantByPhone(@RequestParam("phone") String phone) {
        log.info("MerchantUserController.getMerchantByPhone?phone={}", phone);
        try {
            StoreUserVo result = merchantUserService.getMerchantByPhone(phone);
            if (result != null && result.getId() != null) {
                return R.data(result);
            }
            return R.fail("手机号不存在");
        } catch (Exception e) {
            log.error("MerchantUserController.getMerchantByPhone ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("修改商户用户信息")
    @ApiOperationSupport(order = 2)
    @PostMapping("/updateMerchantUserInfo")
    public R<Boolean> updateMerchantUserInfo(@RequestBody StoreUser storeUser) {
        log.info("MerchantUserController.updateMerchantUserInfo?storeUser={}", storeUser);
        try {
            boolean success = merchantUserService.updateMerchantUserInfo(storeUser);
            if (success) {
                return R.success("修改成功");
            }
            return R.fail("修改失败");
        } catch (Exception e) {
            log.error("MerchantUserController.updateMerchantUserInfo ERROR: {}", e.getMessage(), e);
            return R.fail("修改失败：" + e.getMessage());
        }
    }

    @ApiOperation("检查是否设置支付密码")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeUserId", value = "用户ID", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "password", value = "支付密码（可选，如果提供则验证密码是否正确）", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/checkPayPassword")
    public R<Map<String, Object>> checkPayPassword(
            @RequestParam("storeUserId") String storeUserId,
            @RequestParam(value = "password", required = false) String password) {
        log.info("MerchantUserController.checkPayPassword?storeUserId={}, hasPassword={}", 
                storeUserId, password != null);
        try {
            Map<String, Object> result = merchantUserService.checkPayPassword(storeUserId, password);
            return R.data(result);
        } catch (Exception e) {
            log.error("MerchantUserController.checkPayPassword ERROR: {}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("设置/修改支付密码")
    @ApiOperationSupport(order = 4)
    @PostMapping("/setPayPassword")
    public R<Boolean> setPayPassword(@RequestBody SetPayPasswordDTO dto) {
        log.info("MerchantUserController.setPayPassword - 设置支付密码");
        try {
            // 从token中获取当前登录用户的ID
            Integer userId = shop.alien.storeplatform.util.LoginUserUtil.getCurrentUserId();
            
            boolean success = merchantUserService.setPayPassword(userId, dto.getPayPassword());
            if (success) {
                return R.success("设置成功");
            }
            return R.fail("设置失败");
        } catch (Exception e) {
            log.error("MerchantUserController.setPayPassword ERROR: {}", e.getMessage(), e);
            return R.fail("设置失败：" + e.getMessage());
        }
    }

    @ApiOperation("添加/修改支付宝账号")
    @ApiOperationSupport(order = 5)
    @PostMapping("/addAlipayAccount")
    public R<Integer> addAlipayAccount(@RequestBody AddAlipayAccountDTO dto) {
        log.info("MerchantUserController.addAlipayAccount - 添加支付宝账号");
        try {
            // 从token中获取当前登录用户的ID
            Integer userId = shop.alien.storeplatform.util.LoginUserUtil.getCurrentUserId();
            
            Integer result = merchantUserService.addAlipayAccount(userId, dto.getAlipayAccount());
            if (result > 0) {
                return R.data(result, "添加成功");
            }
            return R.fail("添加失败");
        } catch (Exception e) {
            log.error("MerchantUserController.addAlipayAccount ERROR: {}", e.getMessage(), e);
            return R.fail("添加失败：" + e.getMessage());
        }
    }

    @ApiOperation("删除支付宝账号")
    @ApiOperationSupport(order = 6)
    @PostMapping("/deleteAlipayAccount")
    public R<Boolean> deleteAlipayAccount() {
        log.info("MerchantUserController.deleteAlipayAccount - 删除支付宝账号");
        try {
            // 从token中获取当前登录用户的ID
            Integer userId = LoginUserUtil.getCurrentUserId();
            
            boolean success = merchantUserService.deleteAlipayAccount(userId);
            if (success) {
                return R.success("删除成功");
            }
            return R.fail("删除失败");
        } catch (Exception e) {
            log.error("MerchantUserController.deleteAlipayAccount ERROR: {}", e.getMessage(), e);
            return R.fail("删除失败：" + e.getMessage());
        }
    }

    @ApiOperation("重置商户到刚注册状态")
    @ApiOperationSupport(order = 7)
    @PostMapping("/resetToInitialStatus")
    public R<Boolean> resetToInitialStatus() {
        log.info("MerchantUserController.resetToInitialStatus - 重置商户状态");
        try {
            boolean success = merchantUserService.resetToInitialStatus();
            if (success) {
                return R.data(true, "重置成功，已退回到刚注册状态");
            }
            return R.fail("重置失败");
        } catch (Exception e) {
            log.error("MerchantUserController.resetToInitialStatus ERROR: {}", e.getMessage(), e);
            return R.fail("重置失败：" + e.getMessage());
        }
    }
}


