package com.ym.mec.web.controller;

import com.ym.mec.biz.dal.entity.TempBuyFreeLiveTheoryCourse;
import com.ym.mec.biz.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.entity.FinancialExpenditure;
import com.ym.mec.biz.dal.entity.Goods;
import com.ym.mec.biz.dal.entity.StudentPaymentRouteOrder;
import com.ym.mec.biz.dal.enums.TemplateTypeEnum;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.entity.UploadReturnBean;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import com.ym.mec.util.upload.UploadUtil;

@RequestMapping("import")
@Api(tags = "数据导入服务")
@RestController
public class ImportController extends BaseController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private FinancialExpenditureService financialExpenditureService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private StudentPaymentRouteOrderService studentPaymentRouteOrderService;
    @Autowired
    private AppRedemptionCodeService appRedemptionCodeService;
    @Autowired
    private UploadFileService uploadFileService;

    @Autowired
    private MusicGroupService musicGroupService;


    @ApiOperation(value = "导入商品")
    @PostMapping(value = "goods")
    @PreAuthorize("@pcs.hasPermissions('import/goods')")
    public HttpResponseResult<List<Goods>> importGoods(@RequestParam("file") MultipartFile file) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        return succeed(goodsService.importGoods(file, sysUser.getId()));
    }

    @ApiOperation(value = "导入财务支出")
    @PostMapping(value = "financialExpenditure")
    @PreAuthorize("@pcs.hasPermissions('import/financialExpenditure')")
    public HttpResponseResult<List<FinancialExpenditure>> importFinancialExpenditure(@RequestParam("file") MultipartFile file) throws Exception {
        return succeed(financialExpenditureService.importFinancialExpenditure(file));
    }

    @ApiOperation(value = "导入兑换码分配模板")
    @PostMapping(value = "importRedemptionCode")
    @PreAuthorize("@pcs.hasPermissions('import/importRedemptionCode')")
    public HttpResponseResult<String> importRedemptionCode(@RequestParam("file") MultipartFile file) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        String msg = appRedemptionCodeService.importRedemptionCode(file);
        HttpResponseResult response = succeed(null);
        response.setMsg(msg);
        return response;
    }

    @ApiOperation(value = "导入财务管理订单")
    @PostMapping(value = "routeOrder")
    @PreAuthorize("@pcs.hasPermissions('import/routeOrder')")
    public HttpResponseResult<List<StudentPaymentRouteOrder>> importRouteOrder(@RequestParam("file") MultipartFile file) throws Exception {
        return studentPaymentRouteOrderService.importRouteOrder(file);
    }

    @ApiOperation(value = "导入学生至乐团中")
    @PostMapping(value = "studentToMusicGroup")
    @PreAuthorize("@pcs.hasPermissions('import/studentToMusicGroup')")
    public HttpResponseResult<List<StudentPaymentRouteOrder>> importStudentToMusicGroup(String musicGroupId, @RequestParam("file") MultipartFile file) throws Exception {
        Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(new ByteArrayInputStream(file.getBytes()), 2, file.getOriginalFilename());
        boolean result = musicGroupService.importStudentToMusicGroup(musicGroupId, sheetsListMap);

        return result ? succeed() : failed();
    }

    @PostMapping(value = "oaUploadFile")
    public Object uploadFile(@ApiParam(value = "上传的文件", required = true) @RequestParam("file") MultipartFile file, Integer processId) throws Exception {
        if (file != null && StringUtils.isNotBlank(file.getOriginalFilename())) {
            String fileName = UploadUtil.getExtension(file.getOriginalFilename());
            UploadReturnBean bean = uploadFileService.uploadFile(file.getInputStream(), fileName);
            bean.setName(file.getOriginalFilename());
            if (bean.isStatus()) {
                //如果是乐团退费，校验excel
                if (processId != null && (processId.equals(19) || processId.equals(33))) {
                    if (!"xls".equals(fileName) && !"xlsx".equals(fileName)) {
                        throw new BizException("请上传Excel文件");
                    }
                    URL url = new URL(bean.getUrl());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(3 * 1000);
                    File excelFile = File.createTempFile(UUID.randomUUID().toString(), ".xls");
                    try {
                        FileUtils.copyInputStreamToFile(conn.getInputStream(), excelFile);
                        financialExpenditureService.checkOaQuitMusicGroupExcel(FileUtils.readFileToByteArray(excelFile), fileName);
                    } finally {
                        //删除临时文件
                        if (excelFile.exists()) {
                            excelFile.delete();
                        }
                    }
                }
                return succeed(bean);
            } else {
                return failed(bean.getMessage());
            }
        }
        return failed("上传失败");
    }

    @ApiOperation(value = "下载导入模板")
    @GetMapping(value = "downloadTemplate")
    @PreAuthorize("@pcs.hasPermissions('import/downloadTemplate')")
    public void getGoodsTemplate(HttpServletResponse response, TemplateTypeEnum templateType) throws IOException {
        InputStream inputStream = new ClassPathResource("excelTemplate/" + templateType.getMsg() + ".xls").getInputStream();
        OutputStream outputStream = response.getOutputStream();
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + templateType.getMsg() + "-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Autowired
    private TempBuyFreeLiveTheoryCourseService liveTheoryCourseService;

    @ApiOperation(value = "直播临时活动--学员购买导入")
    @PostMapping(value = "importBuyFreeLiveTheoryCourse")
    @PreAuthorize("@pcs.hasPermissions('import/importBuyFreeLiveTheoryCourseList')")
    public HttpResponseResult<List<String>> importBuyFreeLiveTheoryCourse(@RequestParam("file") MultipartFile file) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        List<String> errMsg = liveTheoryCourseService.importBuyFreeLiveTheoryCourse(file, sysUser.getId());
        if (CollectionUtils.isEmpty(errMsg)) {
            return succeed();
        } else {
            return failed(StringUtils.join(errMsg, ","));
        }
    }

    @ApiOperation(value = "直播临时活动--上课老师名片信息")
    @PostMapping(value = "importLiveTeacherCard")
    @PreAuthorize("@pcs.hasPermissions('import/importLiveTeacherCard')")
    public HttpResponseResult<List<String>> importLiveTeacherCard(@RequestParam("file") MultipartFile file) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        List<String> errMsg = liveTheoryCourseService.importLiveTeacherCard(file, sysUser.getId());
        if (CollectionUtils.isEmpty(errMsg)) {
            return succeed();
        } else {
            return failed(StringUtils.join(errMsg, ","));
        }
    }
}
