package com.ichangzuo.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ichangzuo.common.annotation.Log;
import com.ichangzuo.common.annotation.RepeatSubmit;
import com.ichangzuo.common.base.BasePageQuery;
import com.ichangzuo.common.enums.ContactType;
import com.ichangzuo.common.enums.LogModuleEnum;
import com.ichangzuo.common.result.PageResult;
import com.ichangzuo.common.result.Result;
import com.ichangzuo.common.result.ResultCode;
import com.ichangzuo.common.util.ExcelUtils;
import com.ichangzuo.core.security.util.SecurityUtils;
import com.ichangzuo.system.model.entity.Account;
import com.ichangzuo.system.model.entity.RealNameInfo;
import com.ichangzuo.system.model.entity.User;
import com.ichangzuo.system.model.form.*;
import com.ichangzuo.system.model.query.DrawQuery;
import com.ichangzuo.system.model.query.RealNameInfoPageQuery;
import com.ichangzuo.system.model.vo.TakeOrderPageVO;
import com.ichangzuo.system.model.vo.UserProfileVO;
import com.ichangzuo.system.model.dto.UserImportDTO;
import com.ichangzuo.system.listener.UserImportListener;
import com.ichangzuo.system.model.query.UserPageQuery;
import com.ichangzuo.system.model.dto.UserExportDTO;
import com.ichangzuo.system.model.vo.UserInfoVO;
import com.ichangzuo.system.model.vo.UserPageVO;
import com.ichangzuo.system.service.PayService;
import com.ichangzuo.system.service.UserService;
import com.ichangzuo.system.service.impl.RealNameServiceImpl;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.ichangzuo.common.constant.SystemConstants.REGREX_EMAIL;
import static com.ichangzuo.common.constant.SystemConstants.REGREX_PHONE;
import static com.ichangzuo.common.result.ResultCode.*;

/**
 * 用户控制层
 *
 * @author Ray
 * @since 2022/10/16
 */
@Tag(name = "02.用户接口")
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final RealNameServiceImpl realNameService;
    private final PayService payService;

    @Operation(summary = "用户分页列表")
    @GetMapping("/page")
    @Log(value = "用户分页列表", module = LogModuleEnum.USER)
    public PageResult<UserPageVO> listPagedUsers(
            UserPageQuery queryParams
    ) {
        IPage<UserPageVO> result = userService.listPagedUsers(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:user:add')")
    @RepeatSubmit
    public Result<?> saveUser(
            @RequestBody @Valid UserForm userForm
    ) {
        boolean result = userService.saveUser(userForm);
        return Result.judge(result);
    }

    @Operation(summary = "用户表单数据")
    @GetMapping("/{userId}/form")
    public Result<UserForm> getUserForm(
            @Parameter(description = "用户ID") @PathVariable Long userId
    ) {
        UserForm formData = userService.getUserFormData(userId);
        return Result.success(formData);
    }

    @Operation(summary = "修改用户")
    @PutMapping(value = "/{userId}")
    @PreAuthorize("@ss.hasPerm('sys:user:edit')")
    public Result<?> updateUser(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @RequestBody @Validated UserForm userForm) {
        boolean result = userService.updateUser(userId, userForm);
        return Result.judge(result);
    }

    @Operation(summary = "锁定/恢复用户")
    @PatchMapping("/{ids}/{state}")
    @PreAuthorize("@ss.hasPerm('sys:user:edit')")
    public Result<?> patchUsers(
            @Parameter(description = "用户ID，多个以英文逗号(,)分割") @PathVariable String ids,
            @Parameter(description = "状态，0：注销 1：锁定 2：恢复") @PathVariable Integer state
    ) {
        boolean result = userService.setUsersState(ids, state);
        return Result.judge(result);
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:user:delete')")
    public Result<?> deleteUsers(
            @Parameter(description = "用户ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = userService.deleteUsers(ids);
        return Result.judge(result);
    }

    @Operation(summary = "修改用户状态")
    @PatchMapping(value = "/{userId}/status")
    public Result<?> updateUserStatus(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "用户状态(1:启用;0:禁用)") @RequestParam Integer status
    ) {
        boolean result = userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getId, userId)
                .set(User::getStatus, status)
        );
        return Result.judge(result);
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/me")
    public Result<UserInfoVO> getCurrentUserInfo() {
        UserInfoVO userInfoVO = userService.getCurrentUserInfo();
        return Result.success(userInfoVO);
    }

    @Operation(summary = "用户导入模板下载")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "用户导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        String fileClassPath = "templates" + File.separator + "excel" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "导入用户")
    @PostMapping("/import")
    public Result<?> importUsers(MultipartFile file) throws IOException {
        UserImportListener listener = new UserImportListener();
        String msg = ExcelUtils.importExcel(file.getInputStream(), UserImportDTO.class, listener);
        return Result.success(msg);
    }

    @Operation(summary = "导出用户")
    @GetMapping("/export")
    public void exportUsers(UserPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "用户列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<UserExportDTO> exportUserList = userService.listExportUsers(queryParams);
        EasyExcel.write(response.getOutputStream(), UserExportDTO.class).sheet("用户列表")
                .doWrite(exportUserList);
    }

    @Operation(summary = "获取个人中心用户信息")
    @GetMapping("/profile")
    public Result<UserProfileVO> getUserProfile() {
        Long userId = SecurityUtils.getUserId();
        UserProfileVO userProfile = userService.getUserProfile(userId);
        return Result.success(userProfile);
    }

    @Operation(summary = "修改个人中心用户信息")
    @PutMapping("/profile")
    public Result<?> updateUserProfile(@RequestBody UserProfileForm formData) {
        boolean result = userService.updateUserProfile(formData);
        return Result.judge(result);
    }

//    @Operation(summary = "重置用户密码")
//    @PutMapping(value = "/{userId}/password/reset")
//    @PreAuthorize("@ss.hasPerm('sys:user:password:reset')")
//    public Result<?> resetPassword(
//            @Parameter(description = "用户ID") @PathVariable Long userId,
//            @RequestParam String password
//    ) {
//        boolean result = userService.resetPassword(userId, password);
//        return Result.judge(result);
//    }

    @Operation(summary = "修改密码")
    @PutMapping(value = "/password")
    public Result<?> changePassword(
            @RequestBody PasswordChangeForm data
    ) {
        Long currUserId = SecurityUtils.getUserId();
        boolean result = userService.changePassword(currUserId, data);
        return Result.judge(result);
    }

    @Operation(summary = "发送短信/邮箱验证码")
    @PostMapping(value = "/send-verification-code")
    public Result<?> sendVerificationCode(
            @Parameter(description = "联系方式（手机号码或邮箱地址）", required = true) @RequestParam String contact,
            @Parameter(description = "联系方式类型（Mobile或Email）", required = true) @RequestParam ContactType contactType
    ) {
        String subject = contactType==ContactType.EMAIL ? "绑定邮箱" : "绑定手机";
        boolean result = userService.sendVerificationCode(contact, subject, contactType);
        return Result.judge(result);
    }

    @Operation(summary = "发送短信/邮箱验证码")
    @PostMapping(value = "/sendBindCode")
    public Result<?> sendBindCode(
            @Parameter(description = "联系方式（手机号码或邮箱地址）", required = true) @RequestParam String contact
    ) {
        ContactType type;
        if( contact.matches(REGREX_PHONE) ) {
            type = ContactType.MOBILE;
        }
        else if(contact.matches(REGREX_EMAIL)) {
            type = ContactType.EMAIL;
        }
        else
            return Result.failed(PARAM_ERROR);

        String subject = type==ContactType.EMAIL ? "绑定邮箱" : "绑定手机";
        boolean result = userService.sendVerificationCode(contact, subject, type);
        return Result.judge(result);
    }

    @Operation(summary = "绑定个人中心用户手机号")
    @PutMapping(value = "/mobile")
    public Result<?> bindMobile(
            @RequestBody @Validated MobileBindingForm data
    ) {
        boolean result = userService.bindMobile(data);
        return Result.judge(result);
    }


    @Operation(summary = "绑定个人中心用户邮箱")
    @PutMapping(value = "/email")
    public Result<?> bindEmail(
            @RequestBody @Validated EmailChangeForm data
    ) {
        boolean result = userService.bindEmail(data);
        return Result.judge(result);
    }

    @Operation(summary = "获取当前登录账户信息")
    @GetMapping("/account")
    public Result<Account> getCurrentAccount() {
        Account account = userService.getCurrentAccount();
        return Result.success(account);
    }

    @Operation(summary = "获取当前用户实名信息")
    @GetMapping("/realname")
    public Result<RealNameInfo> getCurrentRealName() {
        RealNameInfo info = userService.getCurrentRealNameInfo();
        return Result.success(info);
    }

    @Operation(summary = "获取所有用户实名信息")
    @GetMapping("/realname/page")
    public PageResult<RealNameInfo> getRealNamePage( RealNameInfoPageQuery queryParams) {
        IPage<RealNameInfo> result = realNameService.listPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "修改用户实名信息")
    @PutMapping("/realname")
    public Result<?> submitRealName(@RequestBody RealNameInfo info) {
        boolean result = userService.submitRealName(info);
        return Result.judge(result);
    }

    @Operation(summary = "审核用户实名信息")
    @PostMapping("/{userId}/realname")
    public Result<?> verifyRealName(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "拒绝理由") @RequestParam String reason) {
        boolean result = userService.verifyRealName(userId, reason);
        return Result.judge(result);
    }

    @Operation(summary = "购买VIP会员")
    @PostMapping("/vip")
    public Result<?> beingVIP(
            @Parameter(description = "VIP类型") @RequestParam Integer vipType
    ) {
        int result = userService.beingVIP(vipType);
        return switch (result) {
            case -1 -> Result.failed(USER_LOGIN_ERROR); //登录异常
            case -2 -> Result.failed(USER_ACCOUNT_INVALID); //账户锁定
            case -3 -> Result.failed(PARAM_ERROR); //参数异常
            case -4 -> Result.failed(USER_ACCOUNT_SHORT); //余额不足
            case -5 -> Result.failed(DATABASE_ERROR);
            default -> //数据操作异常
                    Result.success(result);
        };
    }

    @Operation(summary = "购买音符")
    @PostMapping(value = "/buyNotes")
    public Result<?> buyNotes(
            @Parameter(description = "购买方式") @RequestParam String payType,
            @Parameter(description = "金额") @RequestParam String amount
    ) {
        Account account = userService.getCurrentAccount();
        if(account==null)
            return Result.failed(USER_LOGIN_ERROR);  //账户异常
        if(account.getState()==0)
            return Result.failed(USER_ACCOUNT_DELETED);
        if(account.getState()==1)
            return Result.failed(USER_ACCOUNT_LOCKED);

        return payService.getWebOrderInfo(account.getUserId(), payType, amount);

//        String orderNo = (String) result.getData();
//        if(Objects.equals(payType, "alipay")) {
//            result = payService.getAliPayPageInfo(amount, orderNo);
//        }
//        else if(Objects.equals(payType, "ali_h5")) {
//            result = payService.getAliPayWapInfo(amount, orderNo);
//        }
//        else if(Objects.equals(payType, "wxpay")){
//            result = payService.getWxPayPageInfo(amount, orderNo);
//        }
//        else if(Objects.equals(payType, "wx_h5")){
//            result = payService.getWxPayWapInfo(amount, orderNo);
//        }
//        else {
//            return Result.failed("无效的支付方式");
//        }
//
//        if(!Objects.equals(result.getCode(), SUCCESS.getCode()))
//            return result;
//
//        Map<String, String> param = new HashMap<>();
//        param.put("order", orderNo);
//        param.put("resp", (String) result.getData());
//
//        return Result.success(param);
    }

    @Operation(summary = "查询订单")
    @GetMapping("/checkOrder")
    public Result<?> checkOrder(@RequestParam String order) {
        return Result.success(userService.checkOrder(order));
    }

    @Operation(summary = "音符提现")
    @PostMapping(value = "/draw")
    public Result<?> drawNotes(@RequestBody DrawQuery query) {
//        System.out.println(query);
        return userService.drawNotes(query);
    }

    @Operation(summary = "提现分页列表")
    @GetMapping(value = "/draw/page")
    public PageResult<TakeOrderPageVO> drawNotes(BasePageQuery queryParams) {
        IPage<TakeOrderPageVO> result = userService.listPageDraw(queryParams);
        return PageResult.success(result);
    }

    @PutMapping(value = "/draw")
    public Result<?> verifyDraw(
            @Parameter(description = "单号") @RequestParam Integer orderId,
            @Parameter(description = "拒绝理由") @RequestParam String reason
    ) {
        int result = userService.verifyDraw(orderId, reason);
        if( result>0 )
            return Result.success(result);
        else
            return Result.failed(DATABASE_ERROR);
    }

    @Operation(summary = "修改用户昵称")
    @PatchMapping(value = "/{userId}/nickname")
    public Result<?> updateUserNickName(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "用户昵称") @RequestParam String nickname
    ) {
        boolean result = userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getId, userId)
                .set(User::getNickname, nickname)
        );
        return Result.judge(result);
    }
    @Operation(summary = "修改用户手机号")
    @PatchMapping(value = "/{userId}/phone")
    public Result<?> updateUserPhone(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "用户手机号") @RequestParam String phone
    ) {
        boolean result = userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getId, userId)
                .set(User::getMobile, phone)
        );
        return Result.judge(result);
    }

    @Operation(summary = "发送密码重置邮件")
    @PostMapping(value = "/resetPassword")
    public Result<?> resetPassword(
            @RequestBody ResetPasswordForm data
    ) {
        if( data.getUserId()!=null ) {
            if (data.getPassword() != null) {
                if( userService.resetPassword(data.getUserId(), data.getPassword()) ){
                    return Result.success();
                }
                else{
                    return Result.failed(SYSTEM_EXECUTION_ERROR);
                }
            } else if (data.getVerifyCode() != null) {
                int verify = userService.checkVerificationCode(data.getContact(), data.getVerifyCode(), "重置密码");
                if(verify==-1)
                    return Result.failed(ResultCode.VERIFY_CODE_ERROR);
                else if(verify==-2)
                    return Result.failed(ResultCode.VERIFY_CODE_TIMEOUT);
                else if(verify==-3)
                    return Result.failed(ResultCode.PARAM_ERROR);

                return Result.success();
            }
        }
        else if(data.getUsername()!=null && data.getContact()!=null){
            return userService.sendResetPasswordCode(data.getUsername(), data.getContact());
        }

        return Result.failed(PARAM_ERROR);
    }
}
