package com.github.wxiaoqi.security.admin.rest.admin;

import com.github.wxiaoqi.security.admin.AdminBootstrap;
import com.github.wxiaoqi.security.admin.biz.BaseUserMemberExportBiz;
import com.github.wxiaoqi.security.admin.dto.BaseUserMemberExportDataFindDTO;
import com.github.wxiaoqi.security.admin.dto.UserMemberSaveDTO;
import com.github.wxiaoqi.security.admin.vo.BaseUserMemberExportVo;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.excel.ExcelImport;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/7/11 9:58
 */
@RestController
@RequestMapping("/admin/member")
@Api("后台*会员管理")
public class UserMemberAdminController {

    @Autowired
    private BaseUserMemberExportBiz baseUserMemberExportBiz;

    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @ApiOperation("批量导入会员")
    @PostMapping("/user/export")
    public ObjectRestResponse importUserMember(@RequestPart("file") MultipartFile userMemberExcel, HttpServletRequest request) {
        try {
            IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request));

            List<String[]> userMemberData = ExcelImport.getExcelData(userMemberExcel);
            if (userMemberData.size() < 1) {
                return ObjectRestResponse.createFailedResult(1001, "导入不能没数据！！！");
            }
            for (String[] userMemberDatum : userMemberData) {
                if (userMemberDatum.length!=4){
                    return ObjectRestResponse.createFailedResult(1002, "数据不完整！！！");
                }
            }
            userMemberData.remove(0);
            try {
                int effectSize = baseUserMemberExportBiz.importUserMember(userMemberData,Integer.valueOf(infoFromToken.getId()),infoFromToken.getUniqueName());
                return  ObjectRestResponse.succ(effectSize);
            }catch (BaseException ex){
                return  ObjectRestResponse.createDefaultFail();
            }
        } catch (Exception e) {
            throw new BaseException(e);
        }
    }


    @ApiOperation("会员excel模板下载")
    @GetMapping("/app/unauth/user/excel_model/dowload")
    public ResponseEntity<byte[]> dowloadUserMemberExcelModel(HttpServletResponse response){
        // 重置response
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.addHeader("Content-Disposition", "attachment;filename=usermember.xlsx");
        InputStream inputStream = AdminBootstrap.class.getClassLoader().getResourceAsStream("file/usermember.xlsx");
        try {
            byte[] bytes = IOUtils.toByteArray(inputStream);
            return ResponseEntity.ok(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
    }

    @ApiOperation("会员新增")
    @PostMapping("/save")
    public ObjectRestResponse<Void> saveUserMember(@RequestBody UserMemberSaveDTO userMemberSaveDTO,HttpServletRequest request) {
        try {
            IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request));
            baseUserMemberExportBiz.saveUserMember(userMemberSaveDTO,Integer.valueOf(infoFromToken.getId()),infoFromToken.getName());
            return ObjectRestResponse.succ();
        } catch (Exception e) {
            throw new BaseException(e);
        }

    }

    @ApiOperation("分页查询")
    @GetMapping("/page")
    public ObjectRestResponse<PageDataVO<BaseUserMemberExportVo>> findUserMemberExprotDataPage(BaseUserMemberExportDataFindDTO baseUserMemberExportDataFindDTO){
        PageDataVO<BaseUserMemberExportVo> userMemberExportDataPage = baseUserMemberExportBiz.findUserMemberExportDataPage(baseUserMemberExportDataFindDTO);
        return ObjectRestResponse.succ(userMemberExportDataPage);
    }

    @ApiOperation("根据id删除")
    @DeleteMapping("/{id}")
    public ObjectRestResponse<Void> deleteExportDataById(@PathVariable(value = "id") Integer id){
        baseUserMemberExportBiz.updateUserMemberExportDataStatus(id);
        return ObjectRestResponse.succ();
    }
}
