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.*;
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.nio.charset.Charset;
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, "导入不能没数据！！！");
            }
            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(value = "/app/unauth/user/excel_model/dowload")
    public ResponseEntity<byte[]> dowloadUserMemberExcelModel(){

        HttpHeaders  headers = new HttpHeaders();
//        headers.add("Content-Disposition","attachment;filename=usermember.xlsx");
//        headers.add("Content-Type","application/vnd.ms-excel");
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setContentDisposition(ContentDisposition.builder("attachment").filename("usermember.xlsx", Charset.forName("UTF-8")).build());
        InputStream inputStream = AdminBootstrap.class.getClassLoader().getResourceAsStream("file/usermember.xlsx");
        try {
            headers.setContentLength(Long.valueOf(inputStream.available()));
            byte[] bytes = IOUtils.toByteArray(inputStream);
            inputStream.close();
            return new ResponseEntity<>(bytes,headers,HttpStatus.OK);
        } 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.getUniqueName());
            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();
    }
}
