package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.ServiceConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.ModifyBalanceDTO;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.ss.changeBalance.service.IChangeBalanceService;
import com.ruoyi.ss.user.domain.UserVO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ss.user.domain.UserQuery;
import com.ruoyi.ss.user.service.IUserAssembler;
import com.ruoyi.ss.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/user/user")
public class UserController extends BaseController
{
    @Resource
    private IUserService eUserService;

    @Resource
    private IUserAssembler userAssembler;

    @Autowired
    private IChangeBalanceService changeBalanceService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(UserQuery eUser)
    {
        startPage();
        List<UserVO> list = eUserService.selectUserList(eUser);
        /** 店铺数 */
        userAssembler.assemblerStoreNum(list);
        return getDataTable(list);
    }

//    /**
//     * 根据手机号快速搜索用户列表
//     */
//    @GetMapping("/fast/search")
//    public AjaxResult fastSearch(String phonenumber)
//    {
//        List<LabelVo> list = eUserService.fastSearch(phonenumber);
//        return success(list);
//    }


//    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @PostMapping("/importData")
//    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<EUser> util = new ExcelUtil<EUser>(EUser.class);
//        List<EUser> userList = util.importExcel(file.getInputStream());
//        String operName = getUsername();
//        String message = eUserService.importUser(userList, updateSupport, operName);
//        return success(message);
//    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<User> util = new ExcelUtil<>(User.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId,UserQuery query)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            UserVO user = eUserService.selectUserById(userId);
            // 拼接店铺数、房间数、设施数、设备数、总收入、总提现、总消费
            userAssembler.assembleStatisticalData(user, query.getStartDate(), query.getEndDate());
            ajax.put(AjaxResult.DATA_TAG, user);
        }
        return ajax;
    }


    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody User user)
    {
        if (!eUserService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !eUserService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !eUserService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(eUserService.updateUser(user));
    }


//    /**
//     * 绑定系统用户
//     */
//    @Log(title = "绑定系统用户", businessType = BusinessType.UPDATE)
//    @PutMapping("/bandSystemUser")
//    public AjaxResult bandSystemUser(@RequestBody EUser user)
//    {
//        return toAjax(eUserService.bandSystemUser(user));
//    }

//    /**
//     * 删除用户
//     */
//    @Log(title = "用户管理", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{userIds}")
//    public AjaxResult remove(@PathVariable Long[] userIds)
//    {
//        if (ArrayUtils.contains(userIds, getUserId()))
//        {
//            return error("当前用户不能删除");
//        }
//        return toAjax(eUserService.deleteUserByIds(userIds));
//    }

//    /**
//     * 重置密码
//     */
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
//    @PutMapping("/resetPwd")
//    public AjaxResult resetPwd(@RequestBody EUser user)
//    {
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        user.setUpdateBy(getUsername());
//        return toAjax(eUserService.resetPwd(user));
//    }

    /**
     * 状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody User user)
    {
        user.setUpdateBy(getUsername());
        return toAjax(eUserService.updateUserStatus(user));
    }


    /**
     * 修改余额
     *  1. 修改用户余额
     *  2. 增加账变记录
     *      记录操作人 reapply above
     */
    @Log(title = "修改余额", businessType = BusinessType.UPDATE)
    @PutMapping("/modifyBalance")
    public AjaxResult modifyBalance(@Validated @RequestBody ModifyBalanceDTO dto)
    {
        User user = eUserService.selectUserById(dto.getUserId());
        /* 记录账变  */
        int i = changeBalanceService.generateChangeBalance(null, null, dto.getType(),
                ServiceConstants.SYSTEM_MODIFY, dto.getAmount(), dto.getUserId(), user.getUserName(), user.getPhonenumber(),user.getUserType());
        ServiceUtil.assertion(i == 0, "更新记录账变失败");
        return toAjax(i);
    }


}
