package com.yida.data.device.telephone.controller;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yida.data.common.core.common.ModuleName;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.enums.OperationLogTypeEnum;
import com.yida.data.common.core.entity.telephone.EduTelephoneCard;
import com.yida.data.common.core.entity.telephone.EduTelephoneFamily;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.device.dto.telephone.UpdateListCardPriceDTO;
import com.yida.data.device.telephone.service.EduTelephoneCardService;
import com.yida.data.device.telephone.service.EduTelephoneFamilyService;
import com.yida.data.device.telephone.util.BalanceUtil;
import com.yida.data.device.vo.OnlineCountVO;
import com.yida.data.device.vo.telephone.IcCardVO;
import com.yida.data.device.vo.telephone.ImportICCardVO;
import com.yida.data.device.vo.telephone.TelephoneCardVO;
import com.yida.data.log.annotation.OperationLog;
import com.yida.data.system.feign.RemoteDeptService;
import com.yida.data.user.feign.RemoteStudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;

/**
 * 亲情电话-ic卡 Controller
 *
 * @author zhanghaijun
 * @date 2021-08-10 16:28:12
 */
@Api("亲情电话-ic卡")
@Slf4j
@Validated
@RestController
@RequestMapping("/telephone/card")
@RequiredArgsConstructor
public class EduTelephoneCardController {

    private final EduTelephoneCardService eduTelephoneCardService;
    private final EduTelephoneFamilyService eduTelephoneFamilyService;
    private final RemoteStudentService remoteStudentService;
    private final RemoteDeptService remoteDeptService;
    private final RedisService redisService;

    @ApiOperation("ic卡列表")
    @GetMapping("/cardList")
    public ResultBean<IPage<IcCardVO>> findCardList(@ApiParam("使用状态，0-正常使用，1-冻结") @RequestParam(required = false) Integer status,
                                                    @ApiParam("icc") @RequestParam(required = false) String icc,
                                                    @ApiParam("学生名字") @RequestParam(required = false) String studentName,
                                                    @RequestParam(required = false) Long schoolId,
                                                    @RequestParam(required = false) Long campusId,
                                                    @RequestParam(required = false) Long sectionId,
                                                    @RequestParam(required = false) Long gradeId,
                                                    @RequestParam(required = false) Long classId,
                                                    @RequestParam(defaultValue = "10") Integer pageSize,
                                                    @RequestParam(defaultValue = "1") Integer pageNum) {
        Page page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);

        return ResultBean.buildSuccess(eduTelephoneCardService.findCardList(page, status, icc, studentName, schoolId, campusId, sectionId, gradeId, classId));
    }

    @ApiOperation("ic卡详情")
    @GetMapping("/findCard")
    public ResultBean<TelephoneCardVO> findCard(@ApiParam("ic卡id") @RequestParam Long id) {

        return ResultBean.buildSuccess(eduTelephoneCardService.findCard(id));
    }

    @ApiOperation("编辑保存ic卡")
    @PostMapping("/updateCard")
    public ResultBean updateCard(@RequestBody TelephoneCardVO telephoneCardVO) {

        EduTelephoneCard eduTelephoneCard = telephoneCardVO.getEduTelephoneCard();
        eduTelephoneCardService.saveOrUpdate(eduTelephoneCard);
        Long id = eduTelephoneCard.getId();
        List<EduTelephoneFamily> familyList = telephoneCardVO.getFamilyList();
        if (CollectionUtil.isNotEmpty(familyList)) {
            for (EduTelephoneFamily eduTelephoneFamily : familyList) {
                eduTelephoneFamily.setCardId(id);
            }
            eduTelephoneFamilyService.saveOrUpdateBatch(familyList);
        }
        return ResultBean.buildSuccess();
    }

    @ApiOperation("删除ic卡")
    @GetMapping("/delCard")
    public ResultBean delCard(@ApiParam("ic卡Id") @RequestParam List<Long> ids) {
        for (Long id : ids) {
            eduTelephoneCardService.removeById(id);
            eduTelephoneFamilyService.remove(Wrappers.lambdaQuery(new EduTelephoneFamily()).eq(EduTelephoneFamily::getCardId, id));
        }
        return ResultBean.buildSuccess();
    }

    @ApiOperation("批量修改费率")
    @PostMapping("/updateListCard")
    public ResultBean updateListCard(@RequestBody UpdateListCardPriceDTO cardPriceDTO) {
        Collection<EduTelephoneCard> eduTelephoneCards = eduTelephoneCardService.listByIds(cardPriceDTO.getCardId());
        for (EduTelephoneCard eduTelephoneCard : eduTelephoneCards) {
            eduTelephoneCard.setPriceId(cardPriceDTO.getId());
        }
        eduTelephoneCardService.saveOrUpdateBatch(eduTelephoneCards);
        return ResultBean.buildSuccess();
    }


    @ApiOperation("前台ic卡详情")
    @GetMapping("/findStudentCard")
    public ResultBean<EduTelephoneCard> findStudentCard(@ApiParam("学生id") @RequestParam Long studentId) {
        EduTelephoneCard studentCard = eduTelephoneCardService.findStudentCard(studentId);
        EduStudent data = remoteStudentService.getStudentNoPermission(studentId).getData();
        Double decode = BalanceUtil.decode(studentCard.getBalance());
        studentCard.setBalanceValue(decode);
        studentCard.setAvatar(data.getAvatar());
        return ResultBean.buildSuccess(studentCard);
    }


    @ApiOperation("冻结学生ic卡")
    @GetMapping("/updateStudentIcCard")
    public ResultBean listStudentByParent(@ApiParam("卡id") @RequestParam Long cardId,
                                          @ApiParam("使用状态，0-正常使用，1-冻结',") @RequestParam Integer status) {

        EduTelephoneCard telephoneCard = new EduTelephoneCard();
        telephoneCard.setId(cardId);
        telephoneCard.setStatus(status);
        eduTelephoneCardService.updateById(telephoneCard);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("批量上传ic卡")
    @PostMapping("/batchUpIcCard")
    @OperationLog(module = ModuleName.TELEPHONE, methods = "导入学生ic卡", type =
            OperationLogTypeEnum.INSERT)
    public ResultBean batchUpIcCard(@RequestBody MultipartFile file) {
        ImportICCardVO vo = (ImportICCardVO) redisService.hget(CachePrefixConstant.TELEPHONE_IMPORT,
                FebsUtil.getCurrentUser().getUserId().toString());
        Asserts.isTrue(vo == null || vo.getStatus() == 1, "有导入任务正在进行中，请稍后重试");
        eduTelephoneCardService.batchUpIcCard(FileUtil.uploadMultipartFile(file),
                FebsUtil.getCurrentUser().getUserId().toString());
        return ResultBean.buildSuccess();
    }

    @ApiOperation("下载导入模板")
    @GetMapping("/downloadTemplate")
    @OperationLog(module = ModuleName.TELEPHONE, methods = "下载ic卡导入模板")
    public void downloadTemplate(HttpServletResponse response) {
        eduTelephoneCardService.downloadTemplate(response);
    }

    @ApiOperation("查询导入ic卡的进度信息")
    @GetMapping("/getImportPercent")
    @OperationLog(module = ModuleName.TELEPHONE, methods = "导入学生信息", type =
            OperationLogTypeEnum.INSERT)
    public ResultBean getImportPercent() {
        return ResultBean.buildSuccess(redisService.hget(CachePrefixConstant.TELEPHONE_IMPORT, FebsUtil.getCurrentUser().getUserId().toString()));
    }

    @ApiOperation("获取ic状态分布")
    @GetMapping("/getOnlineDistrib")
    public ResultBean<OnlineCountVO> getOnlineDistrib(){
        List<Long> schoolIds = remoteDeptService.getSchoolByArea(null, null).getData().stream().map(Dept::getDeptId).collect(
            Collectors.toList());
        return ResultBean.buildSuccess(eduTelephoneCardService.getOnlineDistrib(schoolIds));
    }
}
