package com.ruoyi.school.student.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.page.RespPage;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.core.api.APIResponse;
import com.ruoyi.core.api.ApiResEnums;
import com.ruoyi.school.member.domain.ScMemberCard;
import com.ruoyi.school.member.domain.ScStudent;
import com.ruoyi.school.member.domain.req.ReqSearchScStudent;
import com.ruoyi.school.member.domain.req.ReqStudentSelect;
import com.ruoyi.school.member.domain.resp.RespSearchStudent;
import com.ruoyi.school.member.mapper.ScStudentMapper;
import com.ruoyi.school.member.service.IScMemberCardService;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.system.service.YjAppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author ：zhangbaoyu
 * @date ：Created in 2020-01-14 17:24
 */
@Service
@Transactional
public class BusinessScStudentService {

    @Autowired
    private IScStudentService scStudentService;


    @Autowired
    private ScStudentMapper studentMapper;
    @Autowired
    private IScStudentAccountService accountService;

    @Autowired
    private YjAppUserService appUserService;
    /**
     * 查询
     *
     * @param reqSearchScStudent
     * @return
     */
    public APIResponse searchList(ReqSearchScStudent reqSearchScStudent) {
        RespPage<RespSearchStudent> page = new RespPage(reqSearchScStudent.getPageNum(), reqSearchScStudent.getPageSize());
        List<RespSearchStudent> respSearchStudents = studentMapper.selectForSearchTable(reqSearchScStudent, page);
        page.setRows(respSearchStudents);
        return APIResponse.toAPIResponse(page);
    }

    /**
     * 前端select
     *
     * @return
     */
    public APIResponse select(ReqStudentSelect studentSelect) {
        RespPage<RespSearchStudent> page = new RespPage(studentSelect.getPageNum(), studentSelect.getPageSize());
        List<RespSearchStudent> list = scStudentService.selectStudentSelect(studentSelect, page);
        return APIResponse.toAPIResponse(list);
    }

    /**
     * 详情
     *
     * @param studentId
     * @return
     */
    public APIResponse detailById(Long studentId) {
        if (null == studentId) {
            return APIResponse.toAPIResponse(null);
        }
        ScStudent detailInfo = scStudentService.getById(studentId);

        return APIResponse.toAPIResponse(detailInfo);
    }

    /**
     * 添加
     *
     * @param scStudent
     * @return
     */
    public APIResponse addScStudent(ScStudent scStudent) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 保存会员信息

        insertAppUser(scStudent);

        int i=scStudentService.count(new QueryWrapper<ScStudent>().eq("app_user_id",scStudent.getAppUserId())
                .eq("delete_flag","0")
                .eq("tenant_id",SecurityUtils.getLoginUser().getNowTenantId())
        );

        if(i>0){
            throw new RuntimeException("使用该手机号注册的会员已经存在，请勿重复添加！");
        }

        scStudent.setTenantId(SecurityUtils.getLoginUser().getNowTenantId());
        scStudent.setCreateUser(loginUser.getUserId());
        scStudentService.save(scStudent);


        return APIResponse.toAPIResponse(scStudent.getStudentId().toString());
    }
    //关联appUser账号
    public void insertAppUser(ScStudent scStudent){
        AppUser appUser=appUserService.getOne(new QueryWrapper<AppUser>().eq("phone_number",scStudent.getPhone()));

        if (ObjectUtil.isEmpty(appUser)){
            appUser=new AppUser();
            appUser.setNickName(scStudent.getStudentName());
            appUser.setPhoneNumber(scStudent.getPhone());
            appUser.setPassword(SecurityUtils.encryptPassword(scStudent.getPhone()));
            appUser.setVisitStore(SecurityUtils.getLoginUser().getDeptId());
            appUser.setStatus(1);
            appUserService.save(appUser);
        }
        scStudent.setAppUserId(appUser.getId());
    }

    /**
     * 更新
     *
     * @param scStudent
     * @return
     */
    public APIResponse updateScStudent(ScStudent scStudent) {
        if (null == scStudent.getStudentId()) {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ScStudent dbStr=scStudentService.getById(scStudent.getStudentId());

        if (!dbStr.getPhone().equals(scStudent.getPhone())){
            int i=scStudentService.count(new QueryWrapper<ScStudent>()
                    .eq("phone",scStudent.getPhone())
                    .eq("delete_flag","0")
                    .eq("tenant_id",SecurityUtils.getLoginUser().getNowTenantId())
            );

            if(i>0){
                throw new RuntimeException("使用该手机号注册的会员已经存在，请勿重复添加！");
            }
        }


        // 更新会员信息
        scStudent.setLastUpdateUser(loginUser.getUserId());
        scStudent.setLastUpdateTime(new Date());
        boolean updateScStudent = scStudentService.updateById(scStudent);

        return APIResponse.toOkResponse();
    }

    @Autowired
    private IScMemberCardService memberCardService;
    /**
     * 删除
     *
     * @param studentIds
     * @return
     */
    public APIResponse deleteById(Long[] studentIds) {
        if (null == studentIds || studentIds.length == 0) {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }

        // 如果已报读 不允许删除
        int studentCourseCount = memberCardService.count(new QueryWrapper<ScMemberCard>()
                .in("member_id",  Arrays.asList(studentIds)));
        if (studentCourseCount != 0) {
            return APIResponse.toExceptionResponse("会员已办理会员卡,无法删除");
        }

        boolean deleteScStudent = scStudentService.removeByIds(Arrays.asList(studentIds));
        if (deleteScStudent) {
            return APIResponse.toOkResponse();
        } else {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }
    }
}
