package com.ruoyi.web.controller.app;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.ValidGroup;
import com.ruoyi.common.core.domain.dto.BasicConfigDTO;
import com.ruoyi.common.core.domain.dto.CollectionCodeDTO;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ss.changeBalance.domain.ChangeBalance;
import com.ruoyi.ss.changeBalance.domain.ChangeBalanceQuery;
import com.ruoyi.ss.store.domain.StoreVO;
import com.ruoyi.ss.store.service.IStoreService;
import com.ruoyi.ss.user.domain.UserQuery;
import com.ruoyi.ss.user.domain.UserVO;
import com.ruoyi.ss.user.service.IUserService;
import com.ruoyi.ss.userWithdraw.domain.UserWithdraw;
import com.ruoyi.ss.userWithdraw.service.IUserWithdrawService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

import static com.ruoyi.common.constant.ServiceConstants.USER_TYPE_CLEANER;
import static com.ruoyi.common.constant.ServiceConstants.USER_TYPE_PARTNER;

/**
 * 用户Controller
 * @author qzz
 * 2024/3/5
 */
@Api(tags = "用户")
@RestController
@RequestMapping("/app/user")
public class AppUserController extends BaseController {

    @Resource
    private IUserService userService;

    @Autowired
    private IStoreService storeService;

    @Autowired
    private IUserWithdrawService userWithdrawService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public AjaxResult list(UserQuery eUser)
    {
//        eUser.setUserType(USER_TYPE_CLEANER);
        List<UserVO> list = userService.selectUserList(eUser);
        assembleStoreName(list);
        return success(list);
    }

    private void assembleStoreName(List<UserVO> list) {
        if(list.isEmpty()){
            return;
        }
        for (UserVO userVO : list) {
            StoreVO storeVO = storeService.selectEStoreByStoreId(userVO.getStoreId());
            if(storeVO != null){
                userVO.setStoreName(storeVO.getName());
            }
        }
    }

    /**
     * 新增保洁员
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addCleaner")
    public AjaxResult add(@Validated(ValidGroup.CreateCleaner.class) @RequestBody User user)
    {
        user.setUserName(user.getPhonenumber());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        StoreVO storeVO = storeService.selectEStoreByStoreId(user.getStoreId());
        ServiceUtil.assertion(storeVO == null, "店铺不存在");
        user.setCreateBy(getUsername());
        user.setUserType(USER_TYPE_CLEANER);
        user.setMerchantId(storeVO.getMerchantId());
        user.setAppMenus(Arrays.asList(3L, 4L, 5L, 20L));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增合伙人
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addPartner")
    public AjaxResult addPartner(@Validated(ValidGroup.CreatePartner.class) @RequestBody User user)
    {
        user.setUserName(user.getPhonenumber());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        StoreVO storeVO = storeService.selectEStoreByStoreId(user.getStoreId());
        ServiceUtil.assertion(storeVO == null, "店铺不存在");
        user.setCreateBy(getUsername());
        user.setUserType(USER_TYPE_PARTNER);
        user.setMerchantId(storeVO.getMerchantId());
        return toAjax(userService.insertUser(user));
    }


    /**
     * 修改保洁员
     */
    @Log(title = "修改保洁员", businessType = BusinessType.UPDATE)
    @PutMapping("/editUser")
    public AjaxResult edit(@RequestBody @Validated(ValidGroup.Update.class) User user)
    {
        logger.info("修改用户：【{}】", JSON.toJSONString(user));
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        logger.info("删除用户：【{}】", JSON.toJSONString(userIds));
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        if (ArrayUtils.contains(userIds, 1L))
        {
            return error("超级管理员不能删除");
        }
        for(Long userId: userIds){
            UserVO userVO = userService.selectUserById(userId);
            if(userVO == null){
                return error(StrUtil.format("用户【{}】不存在",userId));
            }
//            if(!USER_TYPE_CLEANER.equals(userVO.getUserType())){
//                return error(StrUtil.format("用户【{}】非保洁员，不能删除",userId));
//            }
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 保存基础配置
     */
    @Log(title = "保存基础配置", businessType = BusinessType.UPDATE)
    @PostMapping("/basicConfig")
    public AjaxResult basicConfig(@Validated @RequestBody BasicConfigDTO dto)
    {
        logger.info("保存基础配置：【{}】", JSON.toJSONString(dto));
        return toAjax(userService.basicConfig(dto));
    }

    /**
     * 升级多店权限
     */
    @Log(title = "升级多店权限", businessType = BusinessType.UPDATE)
    @PostMapping("/upgrade")
    public AjaxResult upgrade(Long userId)
    {
        logger.info("升级多店权限：【userId={}】", userId);
        UserVO user =new UserVO();
        user.setUserId(userId);
        user.setMultiStore("N");
        return toAjax(userService.updateUser(user));
    }

    /**
     * 账变记录
     */
    @GetMapping(value = {  "/myChangeBalanceList" })
    public AjaxResult myChangeBalanceList(ChangeBalanceQuery query)
    {
        logger.info("【账变记录/myChangeBalanceList】参数：【query={}】", query);
        AjaxResult ajax = AjaxResult.success();
        if(ObjectUtil.isNotNull(query.getType()) && query.getType().equals("0")){
            query.setType(null);
        }
        List<ChangeBalance> changeBalances  = userService.myChangeBalanceList(query,getUserId());
        ajax.put(AjaxResult.DATA_TAG, changeBalances);
        return ajax;
    }


    /**
     * 上传收款码
     */
    @Log(title = "上传收款码", businessType = BusinessType.UPLOADQRCODE)
    @PostMapping("/uploadPaymentCode")
    public AjaxResult uploadPaymentCode(@Validated @RequestBody CollectionCodeDTO dto)
    {
        UserWithdraw userWithdraw = new UserWithdraw();
        userWithdraw.setUserChannelId(dto.getUserWithdrawChannelId());
        userWithdraw.setCollectionCode(dto.getCollectionCode());
        int i = userWithdrawService.updateRlUserWithdraw(userWithdraw);
        return toAjax(i);
    }

}
