package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeClassBanner;
import shop.alien.entity.store.LifeClassManage;
import shop.alien.mapper.LifeClassBannerMapper;
import shop.alien.mapper.LifeClassManageMapper;
import shop.alien.store.service.LifeClassManageService;
import shop.alien.entity.store.excelVo.util.ExcelExporter;
import shop.alien.util.common.FileUpload;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程管理
 */
@Api(tags = {"一期-课程管理"})
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/classes")
@RequiredArgsConstructor
public class LifeClassManageController {

    private final FileUpload fileUpload;

    private final LifeClassManageService lifeClassManageService;

    private final LifeClassManageMapper lifeClassManageMapper;

    private final LifeClassBannerMapper lifeClassBannerMapper;

    @GetMapping("/getClassesPages")
    public Map<String, Object> getClassesPages(@RequestParam(defaultValue = "1") int page,
                                               @RequestParam(defaultValue = "10") int size,
                                               @RequestParam(required = false) String className,
                                               @RequestParam(required = false) String classTeacher,
                                               @RequestParam(required = false) String classBigType,
                                               @RequestParam(required = false) String classSmallType) {
        log.info("LifeClassManageController.getClassesPages?page={},size={},className={},classTeacher={},classBigType={},classSmallType={}", page, size, className, classTeacher, classBigType, classSmallType);
        IPage<LifeClassManage> stores = lifeClassManageService.getStores(page, size, className, classTeacher, classBigType, classSmallType);
        Map<String, Object> response = new HashMap<>();
        response.put("data", stores.getRecords());
        response.put("total", stores.getRecords().size());
        response.put("current", stores.getCurrent());
        response.put("size", stores.getSize());
        return response;
    }

    @PostMapping("/uploadCoverImage")
    public Integer getClassesPages(
            @RequestParam String classId,
            @RequestParam(required = false) String coverImage) {
        log.info("LifeClassManageController.uploadCoverImage?classId={},coverImage={}", classId, coverImage);
        LambdaUpdateWrapper<LifeClassManage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeClassManage::getId, classId);
        wrapper.set(LifeClassManage::getCoverImage, coverImage);
        lifeClassManageMapper.update(null, wrapper);
        return lifeClassManageMapper.update(null, wrapper);
    }

    @PostMapping("/addPlayCount")
    public R addPlayCount(
            @RequestParam String classId) {
        log.info("LifeClassManageController.addPlayCount?classId={}", classId);
        LifeClassManage lifeClassManage = lifeClassManageMapper.selectById(classId);
        if (ObjectUtils.isEmpty(lifeClassManage.getPlayCount())) {
            LifeClassManage classManage = new LifeClassManage();
            classManage.setId(classId);
            classManage.setPlayCount(1);
            int i = lifeClassManageMapper.updateById(classManage);
            return R.data(i);
        } else {
            LambdaUpdateWrapper<LifeClassManage> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(LifeClassManage::getId, classId);
            wrapper.setSql("play_count = play_count + 1");
            int i = lifeClassManageMapper.update(null, wrapper);
            return R.data(i);
        }
    }

    @ApiOperation("课程列表")
    @GetMapping("/getClasses")
    public R<List<Map<String, Object>>> getClasses(
            @RequestParam(required = false) String className,
            @RequestParam(required = false) String classTeacher,
            @RequestParam(required = false) String classBigType,
            @RequestParam(required = false) String classSmallType) {
        log.info("LifeClassManageController.getClasses?className={},classTeacher={},classBigType={},classSmallType={},page={},size={}", className, classTeacher, classBigType, classSmallType);
        Map<String, Map<String, List<LifeClassManage>>> stores = lifeClassManageService.getAllList(className, classTeacher, classBigType, classSmallType);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Map.Entry<String, Map<String, List<LifeClassManage>>> bigTypeEntry : stores.entrySet()) {
            String bigType = bigTypeEntry.getKey();
            Map<String, List<LifeClassManage>> smallTypeMap = bigTypeEntry.getValue();
            List<Map<String, Object>> smallTypeList = new ArrayList<>();
            for (Map.Entry<String, List<LifeClassManage>> smallTypeEntry : smallTypeMap.entrySet()) {
                String smallType = smallTypeEntry.getKey();
                List<LifeClassManage> records = smallTypeEntry.getValue();
                Map<String, Object> smallTypeRecord = new HashMap<>();
                smallTypeRecord.put("classSmallType", smallType);
                smallTypeRecord.put("records", records);
                smallTypeList.add(smallTypeRecord);
            }
            Map<String, Object> bigTypeRecord = new HashMap<>();
            bigTypeRecord.put("classBigType", bigType);
            bigTypeRecord.put("records", smallTypeList);
            mapList.add(bigTypeRecord);
        }
        return R.data(mapList);
    }

    @GetMapping("/export")
    public ResponseEntity<byte[]> exportToExcelAppeal() throws IOException {
        log.info("LifeClassManageController.exportToExcelAppeal");
        List<LifeClassManage> lifeStoreList = lifeClassManageService.getAllList();
        String[] headers = {"课程名称", "商家ID", "联系人", "联系电话", "经营种类", "申诉时间", "顾客评论", "申诉理由", "状态"};
        byte[] excelData = ExcelExporter.exportToExcel(lifeStoreList, headers, "申诉管理列表");
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("申诉管理列表.xlsx") + "\";charset=utf-8");
        responseHeaders.set("charset", "UTF-8");
        return new ResponseEntity<>(excelData, responseHeaders, HttpStatus.OK);
    }

    @GetMapping("/getClassByType")
    public List<LifeClassManage> getClassByType(@RequestParam("classBigType") String classBigType, @RequestParam("classSmallType") String classSmallType) {
        log.info("LifeClassManageController.getClassByType?classBigType={},classSmallType={}", classBigType, classSmallType);
        return lifeClassManageService.getCLassVideo(classBigType, classSmallType);
    }

    @PostMapping("/setClassState")
    public int setClassState(@RequestParam("id") String id, @RequestParam("classState") String classState) {
        log.info("LifeClassManageController.setClassState?id={},classState={}", id, classState);
        return lifeClassManageService.setStoreState(id, classState);
    }

    @PostMapping("/delete")
    public int delete(@RequestParam("id") String id) {
        log.info("LifeClassManageController.delete?id={}", id);
        return lifeClassManageService.delete(id);
    }

    @PostMapping("addOrUpdateClass")
    public Map<String, Object> addOrUpdateAppeal(LifeClassManage manage,
                                                 @RequestParam("video") MultipartFile video) {
        log.info("LifeClassManageController.addOrUpdateAppeal?manage={}&videoName={}", manage.toString(), video.getOriginalFilename());
        Map<String, Object> response = new HashMap<>();
        final long MAX_FILE_SIZE = 200 * 1024 * 1024;
        try {
            if (video != null && !StringUtils.isEmpty(video.getOriginalFilename())) {
                if (video.getSize() > MAX_FILE_SIZE) {
                    response.put("success", "文件大小超过限制（200MB）");
                    return response;
                }
                manage.setVideoPath(fileUpload.saveImage(video));
//                manage.setClassLength(fileUpload.getVideoDuration(video));
            }
            int cnt = lifeClassManageService.addOrUpdateStore(manage);
            response.put("success", cnt);
        } catch (Exception e) {
            log.error("LifeClassManageController.addOrUpdateAppeal ERROR Msg={}", e.getMessage());
            response.put("success", "上传失败");
            return response;
        }
        return response;
    }

    /**
     * 保存banner轮播图
     * <p>
     * 该方法用于添加或更新班级的轮播图信息如果传入的轮播图ID为空，则视为新增轮播图；
     * 否则，视为更新现有轮播图信息此外，该方法还会检查当前激活的轮播图数量是否已达到上限（4个），
     * 如果达到上限，则不允许添加新的轮播图，直到有一个轮播图被下架
     *
     * @param lifeClassBanner 包含轮播图信息的LifeClassBanner对象
     * @return 返回一个R对象，表示操作结果如果操作成功，返回成功消息；
     * 如果操作失败或达到轮播图数量上限，返回相应的错误消息
     */
    @ApiOperation("保存banner轮播图")
    @PostMapping("/saveClassBanner")
    public R saveClassBanner(@RequestBody LifeClassBanner lifeClassBanner) {
        // 记录方法调用的日志信息
        log.info("LifeClassManageController.saveClassBanner?lifeClassBanner={}", lifeClassBanner);

        try {
            // 判断传入的轮播图ID是否为空，为空则插入新记录，否则更新现有记录
            if (ObjectUtils.isEmpty(lifeClassBanner.getId())) {
                lifeClassBannerMapper.insert(lifeClassBanner);
                return R.success("操作成功");
            } else {
                // 检查当前激活的轮播图数量是否达到上限
                if (ObjectUtils.isNotEmpty(lifeClassBanner.getPlayFlag())) {
                    if (lifeClassBanner.getPlayFlag() == 1) {
                        if (lifeClassBannerMapper.selectCount(new LambdaUpdateWrapper<LifeClassBanner>().eq(LifeClassBanner::getPlayFlag, 1).eq(LifeClassBanner::getDeleteFlag, 0)) >= 4) {
                            return R.fail("轮播图位置已满，请先下架一个后再进行替换");
                        }
                    }
                }
                lifeClassBannerMapper.updateById(lifeClassBanner);
                return R.success("操作成功");
            }
        } catch (Exception e) {
            // 捕获异常并返回操作失败的消息
            return R.fail("操作失败");
        }
    }

    @ApiOperation("分页查询banner轮播图")
    @GetMapping("/getClassBannerPages")
    public R getClassBannerPages(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "10") int size,
                                 @RequestParam(required = false) String bannerTitle,
                                 @RequestParam(required = false) String playFlag) {
        log.info("LifeClassManageController.getClassBannerPages?page={},size={},bannerTitle={},playFlag={}", page, size, bannerTitle, playFlag);
        IPage<LifeClassBanner> bannerPages = lifeClassManageService.getClassBannerPages(page, size, bannerTitle, playFlag);
        return R.data(bannerPages);
    }

    @ApiOperation("更新banner轮播图")
    @PostMapping("/updateSort")
    public R updateSort(@RequestBody List<LifeClassBanner> lifeClassBannerList) {
        log.info("LifeClassManageController.updateSort?lifeClassBannerList={}", lifeClassBannerList);
        for (int i = 0; i < lifeClassBannerList.size(); i++) {
            lifeClassBannerList.get(i).setBannerSort(i + 1);
            lifeClassBannerMapper.updateById(lifeClassBannerList.get(i));
        }
        return R.success("操作成功");
    }

    @ApiOperation("删除banner轮播图")
    @PostMapping("/delClassBanner")
    public R delClassBanner(@RequestParam String id) {
        // 记录方法调用的日志信息
        log.info("LifeClassManageController.delClassBanner?id={}", id);

        try {
            lifeClassBannerMapper.update(null, new LambdaUpdateWrapper<LifeClassBanner>().eq(LifeClassBanner::getId, id).set(LifeClassBanner::getDeleteFlag, 1));
            return R.success("操作成功");
        } catch (Exception e) {
            // 捕获异常并返回操作失败的消息
            return R.fail("操作失败");
        }
    }
}
