/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.desk.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.app.common.vo.ApprovalVO;
import org.springblade.modules.app.entity.ApplicationInfoDO;
import org.springblade.modules.app.entity.UserDO;
import org.springblade.modules.app.manager.UserManager;
import org.springblade.modules.app.service.IApplicationInfoService;
import org.springblade.modules.desk.excel.PlatformUserExcel;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.desk.entity.PlatformUser;
import org.springblade.modules.desk.vo.PlatformUserVO;
import org.springblade.modules.desk.service.IPlatformUserService;
import org.springblade.core.boot.ctrl.BladeController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Map;

/**
 * 用户信息表 控制器
 *
 * @author BladeX
 * @since 2022-05-25
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-desk/platformuser")
@Api(value = "用户信息表", tags = "用户信息表接口")
public class PlatformUserController extends BladeController {

    private final IPlatformUserService platformUserService;
    private final IApplicationInfoService applicationInfoService;
    private final IUserService userService;

    @Autowired
    private UserManager userManager;

    /**
     * 详情
     */
    @GetMapping("/detail")
    //@ApiOperationSupport(order = 1)
    //@ApiOperation(value = "详情", notes = "传入platformUser")
    public R<PlatformUser> detail(PlatformUser platformUser) {
        PlatformUser detail = platformUserService.getOne(Condition.getQueryWrapper(platformUser));
        return R.data(detail);
    }

    /**
     * 分页 用户信息表
     */
    @GetMapping("/list")
    //@ApiOperationSupport(order = 2)
    //@ApiOperation(value = "分页", notes = "传入platformUser")
    public R<IPage<PlatformUser>> list(PlatformUser platformUser, Query query) {
        platformUser.setCreator("system");
        QueryWrapper<PlatformUser> wrapper = Condition.getQueryWrapper(platformUser);
        wrapper.orderByDesc("created_time");
        IPage<PlatformUser> pages = platformUserService.page(Condition.getPage(query), wrapper);
        return R.data(pages);
    }

    @GetMapping("exportPlatformUser")
    @ApiOperationSupport(order = 13)
    @ApiOperation(value = "导出用户", notes = "传入user")
    public void exportUser(@ApiIgnore @RequestParam Map<String, Object> user, BladeUser bladeUser, HttpServletResponse response) {
        QueryWrapper<PlatformUserVO> queryWrapper = Condition.getQueryWrapper(user, PlatformUserVO.class);
        queryWrapper.lambda().eq(PlatformUserVO::getIsDeleted, BladeConstant.DB_NOT_DELETED);
        List<PlatformUserExcel> list = platformUserService.exportPlatformUser(queryWrapper);
        ExcelUtil.export(response, "用户表数据" + DateUtil.time(), "用户表", list, PlatformUserExcel.class);
    }

    @PostMapping("/approval")
    public R<Boolean> approvalRegisterUser(@RequestBody ApprovalVO approvalVO) {
        return R.status(userManager.approvalRegisterUser(approvalVO));
    }

    /**
     * 自定义分页 用户信息表
     */
    @GetMapping("/page")
    //@ApiOperationSupport(order = 3)
    //@ApiOperation(value = "分页", notes = "传入platformUser")
    public R<IPage<PlatformUserVO>> page(PlatformUserVO platformUser, Query query) {
        IPage<PlatformUserVO> pages = platformUserService.selectPlatformUserPage(Condition.getPage(query), platformUser);
        return R.data(pages);
    }

    /**
     * 新增 用户信息表
     */
    @PostMapping("/save")
    //@ApiOperationSupport(order = 4)
    //@ApiOperation(value = "新增", notes = "传入platformUser")
    public R save(@Valid @RequestBody PlatformUser platformUser) {
        return R.status(platformUserService.save(platformUser));
    }

    /**
     * 修改 用户信息表
     */
    @PostMapping("/update")
    //@ApiOperationSupport(order = 5)
    //@ApiOperation(value = "修改", notes = "传入platformUser")
    public R update(@Valid @RequestBody PlatformUser platformUser) {
        return R.status(platformUserService.updateById(platformUser));
    }

    /**
     * 新增或修改 用户信息表
     */
    @PostMapping("/submit")
    @Transactional
    //@ApiOperationSupport(order = 6)
    //@ApiOperation(value = "新增或修改", notes = "传入platformUser")
    public R submit(@Valid @RequestBody PlatformUser platformUser) {
        List<User> list = userService.list(Wrappers.<User>lambdaQuery().eq(User::getPhone,platformUser.getPhone()));
        if(list.size()>0){
            throw new ServiceException("手机号已存在");
        }
        if (StringUtil.isEmpty(platformUser.getId())) {
            User user = new User();
            user.setUserType(2);
            user.setTenantId("000000");
            user.setPassword("040bd08a4290267535cd247b8ba2eca129d9fe9f");
            user.setName(platformUser.getUserName());
            user.setRealName(platformUser.getUserName());
            user.setPhone(platformUser.getPhone());
            user.setAccount(platformUser.getPhone());
            userService.save(user);
            platformUser.setSysUserId(user.getId().toString());
        }


        platformUser.setUserPassword("670b14728ad9902aecba32e22fa4f6bd");

        platformUserService.saveOrUpdate(platformUser);

        ApplicationInfoDO applicationfo = new ApplicationInfoDO();
        applicationfo.setApplyUserId(platformUser.getId());
        applicationfo.setLinkId(platformUser.getId());
        applicationfo.setApplyUserName(platformUser.getUserName());
        applicationfo.setApplyUserId(platformUser.getId());
        applicationfo.setSubmitPhone(platformUser.getPhone());
        applicationfo.setLinkTable("tb_user");
        applicationfo.setState(0);
        applicationfo.setType(6);
        //applicationfo.setSubmitUserId(user.getId());
        applicationInfoService.save(applicationfo);

        platformUser.setUserPassword("670b14728ad9902aecba32e22fa4f6bd");
        //platformUser.setSysUserId(user.getId().toString());
        return R.success("success");
    }


    /**
     * 删除 用户信息表
     */
    @PostMapping("/remove")
    //@ApiOperationSupport(order = 8)
    //@ApiOperation(value = "删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.status(platformUserService.removeByIds(Func.toLongList(ids)));
    }


}
