package com.ruoyi.web.controller.school.member;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.xluobo.core.page.RespPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.core.api.APIResponse;
import com.ruoyi.school.course.domain.resp.course.RespCourseTypeSelect;
import com.ruoyi.school.member.domain.ScMemberCard;
import com.ruoyi.school.member.domain.ScMemberCardCharge;
import com.ruoyi.school.member.domain.ScMemberCardCourses;
import com.ruoyi.school.member.domain.ScMemberCardTypes;
import com.ruoyi.school.member.domain.req.ReqAddMemberChargeItem;
import com.ruoyi.school.member.service.IScMemberCardService;
import com.ruoyi.school.member.service.ScMemberCardChargeService;
import com.ruoyi.school.member.service.ScMemberCardCourseService;
import com.ruoyi.school.member.service.ScMemberCardTypesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 会员卡类型信息 Controller
 * </p>
 *
 */
@RestController
@RequestMapping("/api/sc/memberCardTypes")
public class ScMemberCardTypesController {

    @Autowired
    private ScMemberCardTypesService typesService;

    @Autowired
    private ScMemberCardChargeService cardChargeService;
    @Autowired
    private ScMemberCardCourseService cardCoursesService;

    @Autowired
    private IScMemberCardService memberCardService;


    /**
     * 列表
     *
     * @param
     * @return
     */
    @GetMapping("/list/searchList")
    public APIResponse searchList(ScMemberCardTypes types) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("tenant_id", SecurityUtils.getLoginUser().getNowTenantId());
//        qw.eq("delete_flag", "0");
        if (StringUtils.isNotEmpty(types.getCardName())) {
            qw.eq("card_name", types.getCardName());
        }
        if (StringUtils.isNotEmpty(types.getSale())) {
            qw.eq("sale", types.getSale());
        }
        if (StrUtil.isNotEmpty(types.getCardType()) && !types.getCardType().equals("total_fee")){// count 按课时 date_unit 按时间
            qw.isNotNull(types.getCardType());
            qw.ne(types.getCardType(),"");
        }
        qw.last(ObjectUtil.isNotEmpty(types.getCourseTypeId())," and JSON_CONTAINS(course_types, CAST("+types.getCourseTypeId()+" AS JSON)) ");
        RespPage<ScMemberCardTypes> respPage = new RespPage<>(types.getPageNum(),types.getPageSize());
        RespPage<ScMemberCardTypes> listPage =typesService.page(respPage, qw);

        listPage.getRows().forEach(l->{
            //获取课程分类 名
            typesService.memberTypeDetail(l);

        });
        return APIResponse.toAPIResponse(listPage);
    }


    /**
     * 前端select
     *
     * @return
     */
    @GetMapping("/list/select")
    public APIResponse select(ScMemberCardTypes types) {
        QueryWrapper<ScMemberCardTypes> qw = new QueryWrapper();
        qw.eq("tenant_id", SecurityUtils.getLoginUser().getNowTenantId());
        qw.eq("delete_flag", "0");
        qw.eq("sale", "1");
        if (StringUtils.isNotEmpty(types.getCardName())) {
            qw.eq("card_name", types.getCardName());
        }
        return APIResponse.toAPIResponse(typesService.list(qw));
    }

    /**
     * 详情
     *
     * @param
     * @return
     */
    @GetMapping("/info/detailById/{cardId}")
    public APIResponse detailById(@PathVariable("cardId") Long cardId) {
        ScMemberCardTypes types=typesService.getById(cardId);
        //限制课程
        if (types.getRestrictedCourses().equals("2") ){
            List<ScMemberCardCourses> cardCoursesList= cardCoursesService.list(new QueryWrapper<ScMemberCardCourses>()
                    .eq("card_type_id",types.getCardTypeId()));
            List<RespCourseTypeSelect> typeList= cardCoursesList.stream().map(RespCourseTypeSelect::new).collect(Collectors.toList());
            types.setCourseListInType(typeList);
        }

        //付费模式 自定义
        if (types.getChargeType().equals("customize") ){
            List<ScMemberCardCharge> cardChargeList= cardChargeService.list(new QueryWrapper<ScMemberCardCharge>()
                    .eq("card_type_id",types.getCardTypeId()));
            List<ReqAddMemberChargeItem> chargeItems= BeanUtil.copyToList(cardChargeList,ReqAddMemberChargeItem.class);
            types.setFeeModeHourList(chargeItems);
        }
        return APIResponse.toAPIResponse(types);
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    @PostMapping("/add/memberCardTypes")
    @Transactional
    public APIResponse addScCourse(@RequestBody ScMemberCardTypes types) {

        types.checkParam();
        types.setTenantId(SecurityUtils.getLoginUser().getNowTenantId());
        types.setCreateUser(SecurityUtils.getUserId());
        typesService.save(types);
        Long cardTypeId=types.getCardTypeId();

        //限制课程 会员卡项 课程类型 课程id[]
        List<RespCourseTypeSelect> list=types.getCourseListInType();
        if (types.getRestrictedCourses().equals("2") && list.size()>0){
            List<ScMemberCardCourses> cardCoursesList= new ArrayList<>();

            for (RespCourseTypeSelect type : list) {
                Long[] courses= type.getSelectedCourses();
                if (ObjectUtil.isEmpty(courses) || courses.length<1) continue;
                ScMemberCardCourses cardCourse=new ScMemberCardCourses();
                cardCourse.setCardTypeId(cardTypeId);
                cardCourse.setCourseTypeId(type.getId());
                cardCourse.setCourses(courses);
                cardCoursesList.add(cardCourse);
            }
            cardCoursesService.saveBatch(cardCoursesList);
        }

        //付费模式: 会员卡项 课程类型 扣卡次数 扣卡金额
        List<ReqAddMemberChargeItem>  feeList= types.getFeeModeHourList();
        if (types.getChargeType().equals("customize") && feeList.size()>0){
            List<ScMemberCardCharge> cardChargeList= BeanUtil.copyToList(feeList,ScMemberCardCharge.class);
            cardChargeList.forEach(l->{
                l.setCardTypeId(cardTypeId);
            });
            cardChargeService.saveBatch(cardChargeList);
        }

        return APIResponse.toOkResponse();
    }

    /**
     * 修改
     *
     * @param
     * @return
     */
    @PutMapping("/update/updateMemberCardTypes")
    @Transactional
    public APIResponse updateScCourse(@RequestBody ScMemberCardTypes types) {
        types.setLastUpdateUser(SecurityUtils.getUserId());

        typesService.updateById(types);
        cardChargeService.remove(new QueryWrapper<ScMemberCardCharge>()
                .eq("card_type_id",types.getCardTypeId()));

        cardCoursesService.remove(new QueryWrapper<ScMemberCardCourses>()
                .eq("card_type_id",types.getCardTypeId()));

        //限制课程 会员卡项 课程类型 课程id[]
        List<RespCourseTypeSelect> list=types.getCourseListInType();
        if (types.getRestrictedCourses().equals("2") && list.size()>0){
            List<ScMemberCardCourses> cardCoursesList= new ArrayList<>();

            for (RespCourseTypeSelect type : list) {
                Long[] courses= type.getSelectedCourses();
                if (ObjectUtil.isEmpty(courses) || courses.length<1) continue;
                ScMemberCardCourses cardCourse=new ScMemberCardCourses();
                cardCourse.setCardTypeId(types.getCardTypeId());
                cardCourse.setCourseTypeId(type.getId());
                cardCourse.setCourses(courses);
                cardCoursesList.add(cardCourse);
            }
            cardCoursesService.saveBatch(cardCoursesList);
        }

        //付费模式: 会员卡项 课程类型 扣卡次数 扣卡金额
        List<ReqAddMemberChargeItem>  feeList= types.getFeeModeHourList();
        if (types.getChargeType().equals("customize") && feeList.size()>0){
            List<ScMemberCardCharge> cardChargeList= BeanUtil.copyToList(feeList,ScMemberCardCharge.class);
            cardChargeList.forEach(l->{
                l.setCardTypeId(types.getCardTypeId());
            });

            cardChargeService.saveBatch(cardChargeList);
        }

        return APIResponse.toOkResponse();
    }

    @PutMapping("/update/editSale")
    @Transactional
    public APIResponse editSale(@RequestBody ScMemberCardTypes types) {
        types.setLastUpdateUser(SecurityUtils.getUserId());
        typesService.updateById(types);
        return APIResponse.toOkResponse();
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @DeleteMapping("/delete/deleteById/{cardIds}")
    @Transactional
    public APIResponse deleteById(@PathVariable("cardIds") List<Long> cardIds) {
        //判断 卡类下是否有会员
        int count=memberCardService.count(new QueryWrapper<ScMemberCard>().in("card_type_id",cardIds));
        if (count>0){
            return APIResponse.toExceptionResponse("当前卡类已办理会员，无法删除！");
        }
        typesService.removeByIds(cardIds);
        cardChargeService.remove(new QueryWrapper<ScMemberCardCharge>()
                .in("card_type_id",cardIds));

        cardCoursesService.remove(new QueryWrapper<ScMemberCardCourses>()
                .in("card_type_id",cardIds));

        return APIResponse.toOkResponse();
    }



}
