package com.ssyf.module.robot.controller.auth;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import com.ssyf.common.core.util.EntityUtil;
import com.ssyf.common.core.util.MapUtil;
import com.ssyf.common.web.aop.RequestSynchronization;
import com.ssyf.common.web.apicode.ApiCodeUser;
import com.ssyf.common.web.result.Result;
import com.ssyf.common.web.valid.ValidA;
import com.ssyf.module.robot.domain.entity.RRobotAccount;
import com.ssyf.module.robot.domain.query.RRobotAccountQuery;
import com.ssyf.module.robot.domain.vo.RRobotAccountVo;
import com.ssyf.module.robot.service.RRobotAccountService;
import com.ssyf.plugs.logger.Log;
import com.ssyf.plugs.mysql.helper.PageEnhanceHelper;
import com.ssyf.plugs.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
* com.ssyf.auth.entity.RRobotAccount模型开放接口
*
* @author: auth
* @date: 2022-12-12
*/
@Api(tags="基础-机器人机器人")
@RestController
@RequestMapping("/auth/RobotAccount")
public class RRobotAccountAuthController {

    @Autowired
    private RRobotAccountService baseService;

    @Log(title = "机器人机器人-新增数据")
    @RequestSynchronization
    @ApiOperation(value = "新增数据", notes = "新增数据")
    @PostMapping(value = "/addOne")
    public Result<RRobotAccountVo> addOne(@Validated({ValidA.class}) @RequestBody RRobotAccountQuery query) {
        if(BeanUtil.isEmpty(query)){
            return Result.fail(ApiCodeUser.PARAMETER_ERROR);
        }
        RRobotAccount menuRRobotAccount = this.baseService.addOne(query);
        return Result.success(BeanUtil.copyProperties(menuRRobotAccount , RRobotAccountVo.class));
    }


    @Log(title = "机器人机器人-批量更新数据")
    @RequestSynchronization
    @ApiOperation(value = "批量更新数据", notes = "根据uids批量更新")
    @PostMapping(value = "/updateByUids")
    public Result updateByUids(@Validated @RequestBody RRobotAccountQuery query) {
        if (BeanUtil.isEmpty(query) || CollectionUtil.isEmpty(query.getUids())) {
            return Result.fail(ApiCodeUser.PARAMETER_ERROR.getCode(), "更新数据不能为空或uids不能为空");
        }
        this.baseService.updateByUids(query.getUids(), query);
        return Result.success();
    }
    @Log(title = "机器人机器人-更新数据")
    @RequestSynchronization
    @ApiOperation(value = "更新数据", notes = "uid更新")
    @PostMapping(value = "/updateByUid/{uid}")
    public Result updateByUid(@PathVariable String uid , @Validated @RequestBody RRobotAccountQuery query){
        if(BeanUtil.isEmpty(query)){
            return Result.fail(ApiCodeUser.PARAMETER_ERROR.getCode() ,"更新数据不能为空");
        }
        this.baseService.updateByUid(uid ,query);
        return Result.success();
    }


    @Log(title = "机器人机器人-校验机器人")
    @RequestSynchronization
    @ApiOperation(value = "校验机器人", notes = "校验机器人")
    @PostMapping(value = "/isValid/{uid}")
    public Result isValid(@PathVariable String uid ){
        this.baseService.isValid(uid);
        return Result.success();
    }

    @Log(title = "机器人机器人-校验机器人")
    @RequestSynchronization
    @ApiOperation(value = "校验机器人", notes = "校验机器人")
    @PostMapping(value = "/isValidNot")
    public Result isValidNot(){
        this.baseService.isValidNot();
        return Result.success();
    }

    @Log(title = "机器人机器人-校验机器人")
    @RequestSynchronization
    @ApiOperation(value = "校验机器人", notes = "校验机器人")
    @PostMapping(value = "/isValidAll")
    public Result isValidAll(){
        this.baseService.isValidAll();
        return Result.success();
    }

    @Log(title = "机器人机器人-删除数据")
    @RequestSynchronization
    @ApiOperation(value = "删除数据", notes = "uid删除")
    @PostMapping(value = "/removeByUid/{uid}")
    public Result removeByUid(@PathVariable String uid){
        this.baseService.removeByUid(uid);
        return Result.success();
    }

    @Log(title = "机器人机器人-批量删除")
    @RequestSynchronization
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @PostMapping(value = "/removeBatchByUid")
    public Result removeBatchByUid(@Validated @RequestBody RRobotAccountQuery query){
        this.baseService.removeBatchByUids(query.getUids());
        return Result.success();
    }


    @ApiOperation(value = "/查询指定数据" ,notes = "uid查询")
    @PostMapping(value = "/getOneByUid/{uid}")
    public Result<PageInfo<RRobotAccountVo>> getOneByUid(@PathVariable String uid) {
        return Result.success(BeanUtil.toBean(this.baseService.getOneByUid(uid) ,RRobotAccountVo.class));
    }

    @ApiOperation(value = "/查询分页数据", notes = "分页查询")
    @PostMapping(value = "/queryPage")
    public Result<PageInfo<RRobotAccountVo>> queryPage(@Validated @RequestBody RRobotAccountQuery query) {
        PageInfo<RRobotAccount> temp = this.baseService.getPage(query);
        return Result.success(PageEnhanceHelper.switchPageInfo(temp ,RRobotAccountVo.class));
    }

    @ApiOperation(value = "/查询所有数据")
    @PostMapping(value = "/queryList")
    public Result<PageInfo<RRobotAccountVo>> queryList(@Validated @RequestBody RRobotAccountQuery query) {
        List<RRobotAccount> menuRRobotAccountList = this.baseService.getList(query);
        List<RRobotAccountVo> t = EntityUtil.copyProperties(menuRRobotAccountList, RRobotAccountVo.class);
        return Result.success(t);
    }
    @ApiOperation(value = "/查询总数")
    @PostMapping(value = "/count")
    public Result<Integer> count(@Validated @RequestBody RRobotAccountQuery query) {
        Integer count = this.baseService.countBy(query);
        return Result.success(count);
    }



    //导入接口，读取Excel文件
    @ApiOperation(value = "导入数据", notes = "导入数据")
    @PostMapping(value = "/import")
    public Result<List<RRobotAccountVo>> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String, String> fieldMap = excelTemplate();
        List<RRobotAccountVo> menuRRobotAccountList = ExcelUtil.parseExcel(file.getInputStream(), fieldMap, RRobotAccountVo.class);
        if(CollectionUtil.isEmpty(menuRRobotAccountList)){
            return Result.fail(ApiCodeUser.PARAMETER_ERROR.getCode() ,"导入数据不能为空");
        }
        List<RRobotAccount> RRobotAccountList = new ArrayList<>();
        for(RRobotAccountVo menuRRobotAccount : menuRRobotAccountList){
            RRobotAccount RRobotAccount = BeanUtil.toBean(menuRRobotAccount , RRobotAccount.class);
            RRobotAccountList.add(RRobotAccount);
        }
        //存入数据
        this.baseService.addBatchByImport(RRobotAccountList);
        return Result.success();
    }

    @ApiOperation(value = "批量更新数据", notes = "根据上传的Excel文件批量更新机器人账号信息")
    @PostMapping(value = "/importBatchUpdate")
    public Result<List<RRobotAccountVo>> batchUpdate(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String, String> fieldMap = excelTemplate();
        List<RRobotAccountVo> robotAccountList = ExcelUtil.parseExcel(file.getInputStream(), fieldMap, RRobotAccountVo.class);
        if(CollectionUtil.isEmpty(robotAccountList)){
            return Result.fail(ApiCodeUser.PARAMETER_ERROR.getCode(), "更新数据不能为空");
        }

        List<RRobotAccount> updateList = new ArrayList<>();
        for(RRobotAccountVo robotAccountVo : robotAccountList){
            RRobotAccount robotAccount = BeanUtil.toBean(robotAccountVo, RRobotAccount.class);
            updateList.add(robotAccount);
        }

        // 执行批量更新操作
        this.baseService.batchUpdateByImport(updateList);
        return Result.success();
    }

    @ApiOperation(value = "机器人导入模板文件", notes = "机器人导入模板文件")
    @PostMapping(value = "/dwonloadTemplate", produces = "application/vnd.ms-excel")
    public void export( HttpServletResponse response) throws IOException, IOException {
        Map<String, String> fieldMap = excelTemplate();
        List<RRobotAccount> tempList = new ArrayList<>();
        tempList.add(new RRobotAccount());
        // 创建Workbook对象
        Workbook workbook = ExcelUtil.createWorkbook(tempList, fieldMap);
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=入库主机模板.xlsx");
        // 将Workbook写入响应输出流
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        } finally {
            workbook.close();
        }
    }

    private Map<String ,String> excelTemplate() {
        Map<String, String> fieldMap = MapUtil.builder()
                .put("userNumber", "机器人编码")
                .put("countryMobileCode", "国家电话编码")
                .put("mobile", "电话")
                .put("email", "邮箱")
                .put("password", "密码")
                .put("nickname", "昵称")
                .put("headerIconUrl", "头像url")
                .put("notes", "简介")
                .put("groupName", "分组名称")
                .build();
        return fieldMap;
    }

    @ApiOperation(value = "导出数据", notes = "根据查询条件导出数据为Excel文件")
    @PostMapping(value = "/export", produces = "application/vnd.ms-excel")
    public void export(@Validated @RequestBody RRobotAccountQuery query, HttpServletResponse response) throws IOException, IOException {
        PageInfo<RRobotAccount> RRobotAccountPageInfo= this.baseService.getPage(query);
        List<RRobotAccount> RRobotAccountList = new ArrayList<>();
        if(RRobotAccountPageInfo != null && RRobotAccountPageInfo.getList() != null){
            RRobotAccountList = RRobotAccountPageInfo.getList();
        }
        List<RRobotAccountVo> RRobotAccountVoList = EntityUtil.copyProperties(RRobotAccountList, RRobotAccountVo.class);
        // 字段名和中文名的映射
        Map<String, String> fieldMap = excelTemplate();

        // 创建Workbook对象
        Workbook workbook = ExcelUtil.createWorkbook(RRobotAccountVoList, fieldMap);

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=inbound_records.xlsx");

        // 将Workbook写入响应输出流
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        } finally {
            workbook.close();
        }
    }
}
