package com.ym.mec.student.controller;


import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.OrganizationDao;
import com.ym.mec.biz.dal.dao.SysAreaDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dto.DegreeRegistrationActivityDto;
import com.ym.mec.biz.dal.entity.Organization;
import com.ym.mec.biz.dal.entity.SysArea;
import com.ym.mec.biz.dal.enums.SporadicChargeTypeEnum;
import com.ym.mec.biz.dal.page.SporadicChargeInfoQueryInfo;
import com.ym.mec.biz.service.DegreeRegistrationService;
import com.ym.mec.biz.service.SporadicChargeInfoService;
import com.ym.mec.biz.service.SysConfigService;
import com.ym.mec.biz.service.SysTenantConfigService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.util.idcard.IdcardValidator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("degree")
@Api(tags = "考级报名服务")
@RestController
public class DegreeController extends BaseController {

    @Autowired
    private DegreeRegistrationService degreeRegistrationService;

    @Autowired
    private SporadicChargeInfoService sporadicChargeInfoService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private SysTenantConfigService sysTenantConfigService;

    @Autowired
    private SysConfigDao sysConfigDao;

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private SysAreaDao sysAreaDao;

	@Value("${message.debugMode: false}")
	private boolean debugMode;

    @ApiOperation(value = "考级报名支付")
    @PostMapping("/pay")
    public HttpResponseResult pay(@RequestBody DegreeRegistrationActivityDto degreeRegistration) throws Exception {
        SysUser user = sysUserFeignService.queryUserInfo();
        if(Objects.isNull(user)){
            return failed(HttpStatus.FORBIDDEN,"请登录");
        }
        degreeRegistration.setUserId(user.getId());
        HttpResponseResult result = degreeRegistrationService.check(degreeRegistration);
        if(result.getCode() != 200){
            return result;
        }
        TenantContextHolder.setTenantId(user.getTenantId());
        degreeRegistration.setUserId(user.getId());
        if("IDENTITY".equals(degreeRegistration.getCertificateType())){
	        IdcardValidator idcardValidator = new IdcardValidator();
	        if (!debugMode && !idcardValidator.isValidatedAllIdcard(degreeRegistration.getIdcard())) {
	            throw new BizException("身份证号不正确，请核对");
	        }
        }
        if(user.getOrganId() == null || user.getOrganId() == 43){
            user.setUsername(degreeRegistration.getName());
            user.setIdCardNo(degreeRegistration.getIdcard());
            Organization organization = organizationDao.findByName(degreeRegistration.getCity());
            if(Objects.nonNull(organization)){
                user.setOrganId(organization.getId());
            }
            teacherDao.updateUser(user);
        }
        degreeRegistration.setOrganId(user.getOrganId());
        if(Objects.isNull(degreeRegistration.getOrganId())){
            return failed("该分部暂未开放此活动");
        }
        HttpResponseResult pay = degreeRegistrationService.pay(degreeRegistration);
        TenantContextHolder.clearTenantId();
        return pay;
    }
/*
    @ApiOperation(value = "考级报名支付")
    @PostMapping("/theoryPay")
    public HttpResponseResult theoryPay(@RequestBody DegreeRegistrationActivityDto degreeRegistration) throws Exception {
        SysUser user = sysUserFeignService.queryUserInfo();
        if(Objects.isNull(user)){
            return failed(HttpStatus.FORBIDDEN,"请登录");
        }
        degreeRegistration.setUserId(user.getId());

        if(Objects.nonNull(degreeRegistration.getTheoryLevel())){
            IdcardValidator idcardValidator = new IdcardValidator();
            if (!idcardValidator.isValidatedAllIdcard(degreeRegistration.getIdcard())) {
                throw new BizException("身份证号不正确，请核对");
            }
        }else{
            degreeRegistration.setOrganId(user.getOrganId());
        }

        if(Objects.isNull(degreeRegistration.getOrganId()) || degreeRegistration.getOrganId() == 4){
            return failed("该分部暂未开放此活动");
        }

        return degreeRegistrationService.theoryPay(degreeRegistration);
    }*/

    @ApiOperation(value = "考级报名检查")
    @PostMapping("/check")
    public HttpResponseResult check(@RequestBody DegreeRegistrationActivityDto degreeRegistration) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if(Objects.isNull(user)){
            return failed(HttpStatus.FORBIDDEN,"请登录");
        }
        degreeRegistration.setUserId(user.getId());
        return degreeRegistrationService.check(degreeRegistration);
    }

    @ApiOperation(value = "查询收费列表")
    @GetMapping("/queryList")
    public HttpResponseResult queryPage(SporadicChargeInfoQueryInfo queryInfo) {
        queryInfo.setOrganId("42");
        queryInfo.setChargeType(SporadicChargeTypeEnum.LEVEL);
        queryInfo.setRows(99);
        queryInfo.setOpenFlag(0);
        queryInfo.setSort("amount_");
        queryInfo.setOrder("ASC");
        return succeed(sporadicChargeInfoService.queryDetailPage(queryInfo));
    }

    @ApiOperation(value = "获取活动参数")
    @GetMapping("/getParams")
    public HttpResponseResult getParams(){
        SysUser user = sysUserFeignService.queryUserInfo();
        if(Objects.isNull(user)||Objects.isNull(user.getId())){
            return failed(HttpStatus.FORBIDDEN,"请登录");
        }

        SporadicChargeInfoQueryInfo queryInfo = new SporadicChargeInfoQueryInfo();
        queryInfo.setOrganId("42");
        queryInfo.setChargeType(SporadicChargeTypeEnum.LEVEL);
        queryInfo.setRows(99);
        queryInfo.setOpenFlag(0);
        queryInfo.setSort("amount_");
        queryInfo.setOrder("ASC");

        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", user);
        Organization organization = organizationDao.get(user.getOrganId());
        if(!Objects.isNull(organization)){
            SysArea area = sysAreaDao.get(organization.getAreaId());
            if(Objects.nonNull(area)){
                result.put("city", area.getName());
                SysArea parentArea = sysAreaDao.get(area.getParentOrganId());
                if(Objects.nonNull(parentArea)){
                    result.put("province", parentArea.getName());
                }
            }
        }
        result.put("degreeTheoryAmountConfig", sysConfigDao.findConfigValue("degree_theory_amount_config"));

//        Student student = studentDao.get(user.getId());
        //result.put("isNewUser", student.getIsNewUser());

        String configValue = sysTenantConfigService.getTenantConfigValue(SysConfigService.DEGREE_SUPPORT_ORGAN_LIST, user.getTenantId());
        if(StringUtils.isNotEmpty(configValue)){
            List<Integer> userIds = Arrays.stream(configValue.split(",")).mapToInt(Integer::valueOf).boxed().collect(Collectors.toList());
            result.put("organs", organizationDao.findOrgans(userIds));
        }
        result.put("sporadicChargeInfo", sporadicChargeInfoService.queryDetailPage(queryInfo));

//        List<DegreeRegistration> userLevelDegrees = degreeRegistrationDao.getUserLevelDegrees(user.getId(), DegreeRegistrationService.ACTIVITY_TAG,2);
//        long levelNum = userLevelDegrees.stream().filter(d -> Objects.nonNull(d.getSporadicId())&&d.getStatus().equals(2)).count();
//        long theoryLevelNum = userLevelDegrees.stream().filter(d -> StringUtils.isNotBlank(d.getTheoryLevel())&&d.getStatus().equals(2)).count();

//        result.put("levelApplied", levelNum>0?1:0);
//        result.put("theoryLevelApplied", theoryLevelNum>0?1:0);

//        List<StudentPaymentOrderDetail> historyOrderDetails = studentPaymentOrderDetailDao.getWithUserAndOrderType(user.getId(), OrderTypeEnum.DEGREE_REGISTRATION);
//        int historyVipNum = 0, historyPracticeNum = 0, historyHighNum = 0;
//        for (StudentPaymentOrderDetail historyOrderDetail : historyOrderDetails) {
//            if(StringUtils.isBlank(historyOrderDetail.getGoodsIdList())){
//                continue;
//            }
//            Map<String, Integer> courseNumMap = JSON.parseObject(historyOrderDetail.getGoodsIdList(), Map.class);
//            for (Map.Entry<String, Integer> stringIntegerEntry : courseNumMap.entrySet()) {
//                switch (stringIntegerEntry.getKey()){
//                    case "VIP":
//                        historyVipNum = historyVipNum + stringIntegerEntry.getValue();
//                        break;
//                    case "PRACTICE":
//                        historyPracticeNum = historyPracticeNum + stringIntegerEntry.getValue();
//                        break;
//                    case "HIGH":
//                        historyHighNum = historyHighNum + stringIntegerEntry.getValue();
//                        break;
//                }
//            }
//        }
//        Map<String, Integer> historyCourseInfo = new HashMap<>();
//        historyCourseInfo.put(CourseSchedule.CourseScheduleType.VIP.getCode(), historyVipNum);
//        historyCourseInfo.put(CourseSchedule.CourseScheduleType.PRACTICE.getCode(), historyPracticeNum);
//        historyCourseInfo.put(CourseSchedule.CourseScheduleType.HIGH.getCode(), historyHighNum);
//        result.put("historyCourseInfo", historyCourseInfo);

        return succeed(result);
    }
}
