package com.hzs.activity.people.controller.manage;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.activity.base.param.ActivityParam;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.service.IAcGoalMemberConfigService;
import com.hzs.activity.people.param.AcBaseConfigParam;
import com.hzs.activity.people.vo.AcBaseConfigVO;
import com.hzs.activity.people.vo.AcNewPeopleRuleConfigVO;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.activity.people.service.IAcNewPeopleRuleConfigService;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.activity.base.AcBaseConfig;
import com.hzs.common.domain.activity.base.AcGoalMemberConfig;
import com.hzs.common.domain.activity.base.ext.AcGiftConfigExt;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.system.sys.dto.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 新人礼包规则表 前端控制器
 * </p>
 *
 * @author hzs
 * @since 2023-04-24
 */
@RestController
@RequestMapping("/manage/new-people")
public class AcNewPeopleRuleConfigController extends BaseController {

    @Autowired
    private IAcNewPeopleRuleConfigService iAcNewPeopleRuleConfigService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private IAcBaseConfigService iAcBaseConfigService;
    @Autowired
    private IAcGiftConfigService iAcGiftConfigService;
    @Autowired
    private IAcGoalMemberConfigService goalMemberConfigService;


    /**
     * @description: 查询新人礼包活动列表
     * @author: zhang jing
     * @date: 2023/4/8 14:09
     * @param: [controlVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.NEW_PACK, business = EOperationBusiness.NEW_PACK, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(AcBaseConfigVO abcVO) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        QueryWrapper<AcBaseConfig> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(abcVO.getActName())) {
            queryWrapper.like("ACT_NAME", abcVO.getActName());
        }
        if (abcVO.getActivityStatus() != null) {
            // 状态筛选
            if (abcVO.getActivityStatus() == EActivityStatus.NOT_STARTED.getValue()) {
                // 未开始  当前时间小于开始时间
                queryWrapper.lt("ACT_START_DATE", DateUtils.currentDate());
            } else if (abcVO.getActivityStatus() == EActivityStatus.IN_PROGRESS.getValue()) {
                // 进行中 大于开始 小于结束
                queryWrapper.gt("ACT_START_DATE", DateUtils.currentDate());
                queryWrapper.lt("ACT_END_DATE", DateUtils.currentDate());
            } else if (abcVO.getActivityStatus() == EActivityStatus.EXPIRED.getValue()) {
                // 已失效 当前时间大于结束时间
                queryWrapper.gt("ACT_END_DATE", DateUtils.currentDate());
            }
        }
        // 活动开始时间
        if (abcVO.getStartActStartDate() != null && abcVO.getEndActStartDate() != null) {
            queryWrapper.between("ACT_START_DATE", abcVO.getStartActStartDate(), abcVO.getEndActStartDate());
        }
        // 活动结束时间
        if (abcVO.getStartActEndDate() != null && abcVO.getEndActEndDate() != null) {
            queryWrapper.between("ACT_END_DATE", abcVO.getStartActEndDate(), abcVO.getEndActEndDate());
        }
        // 创建时间
        if (abcVO.getStartCreationTime() != null && abcVO.getEndCreationTime() != null) {
            queryWrapper.between("CREATION_TIME", abcVO.getStartCreationTime(), abcVO.getEndCreationTime());
        }
        queryWrapper.eq("ACT_TYPE", EActType.NEW_GIFT.getValue());
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        List<AcBaseConfigVO> listVO = new ArrayList<>();
        List<AcBaseConfig> list = iAcBaseConfigService.list(queryWrapper);
        for (AcBaseConfig acBaseConfig : list) {
            AcBaseConfigVO baseConfigVo = BeanUtil.copyProperties(acBaseConfig, AcBaseConfigVO.class);
            // 判断活动状态
            // 开始时间
            long startTime = acBaseConfig.getActStartDate().getTime();
            // 结束时间
            long endTime = acBaseConfig.getActEndDate().getTime();
            // 当前时间
            long currentTime = DateUtils.currentDate().getTime();
            if (currentTime > startTime && currentTime < endTime) {
                // 当前时间大于开始 小于结束
                baseConfigVo.setActivityStatusVal(EActivityStatus.IN_PROGRESS.getLabel());
            } else if (currentTime < startTime) {
                // 当前时间小于开始时间
                baseConfigVo.setActivityStatusVal(EActivityStatus.NOT_STARTED.getLabel());
            } else if (currentTime > endTime) {
                // 当前时间大于结束时间
                baseConfigVo.setActivityStatusVal(EActivityStatus.EXPIRED.getLabel());
            }
            listVO.add(baseConfigVo);
        }
        TableDataInfo tableDataInfo = getDataTable(list);
        tableDataInfo.setRows(listVO);
        return tableDataInfo;
    }


    /**
     * @description: 新人礼包查看
     * @author: zhang jing
     * @date: 2023/4/25 14:36
     * @param: [anpVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.NEW_PACK, business = EOperationBusiness.NEW_PACK, method = EOperationMethod.SELECT)
    @PostMapping("/details")
    public AjaxResult details(@RequestBody AcBaseConfigVO anpVO) {
        if (StringUtils.isNull(anpVO.getPkId())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ACTIVITY_NOT_NULL));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        AcBaseConfig acBaseConfig = iAcBaseConfigService.getById(anpVO.getPkId());
        anpVO = BeanUtil.copyProperties(acBaseConfig, AcBaseConfigVO.class);
        AcNewPeopleRuleConfigVO nplVO = new AcNewPeopleRuleConfigVO();
        nplVO.setPkBaseId(anpVO.getPkId());
        nplVO.setPkCountry(pkCountry);
        QueryWrapper<AcGoalMemberConfig> qe = new QueryWrapper<>();
        qe.eq("PK_BASE_ID", anpVO.getPkId());
        List<AcGoalMemberConfig> goalMemberConfigList = goalMemberConfigService.list(qe);
        anpVO.setGoalMemberConfigList(goalMemberConfigList);
        List<AcNewPeopleRuleConfigVO> nplListVO = iAcNewPeopleRuleConfigService.queryNplList(nplVO);
        if (CollectionUtil.isNotEmpty(nplListVO)) {
            nplListVO.forEach(item -> {
                List<AcGiftConfigExt> agList = iAcGiftConfigService.queryListByRuleIdList(item.getPkId(), pkCountry);
                item.setAgcList(agList);
            });
        }
        anpVO.setAnpList(nplListVO);
        return AjaxResult.success(anpVO);
    }


    /**
     * @description: 新增新人活动礼包
     * @author: zhang jing
     * @date: 2023/4/25 9:23
     * @param: [anpVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.AC_NEW_PEOPLE, method = EOperationMethod.INSERT)
    @PostMapping("/save-petition")
    public AjaxResult savePetition(@RequestBody AcBaseConfigParam anpParam) {
        anpParam.setControlType(EControlType.SAVE.getValue());

        // 验证参数
        List<String> errorList = validateParams(anpParam);
        if (!errorList.isEmpty()) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorList);
        }
        // 设置参数
        LoginUser loginUser = userTokenService.getLoginUser();
        anpParam.setLoginUser(loginUser);
        anpParam.setPkCountry(SecurityUtils.getPkCountry());
        ActivityParam activityParam = anpParam.getActivityParam();
        activityParam.setActType(EActType.NEW_GIFT.getValue());
        anpParam.setApprovalType(EApprovalBusiness.NEW_PEOPLE.getValue());
        return AjaxResult.success(iAcNewPeopleRuleConfigService.petition(anpParam));
    }

    /**
     * @description: 修改新人活动礼包
     * @author: zhang jing
     * @date: 2023/4/25 9:23
     * @param: [anpVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.NEW_PACK, business = EOperationBusiness.NEW_PACK, method = EOperationMethod.UPDATE)
    @PostMapping("/up-petition")
    public AjaxResult upPetition(@RequestBody AcBaseConfigParam anpParam) {
        // 验证参数
        anpParam.setControlType(EControlType.MODIFY.getValue());
        List<String> errorList = validateParams(anpParam);
        if (!errorList.isEmpty()) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorList);
        }
        // 设置参数
        LoginUser loginUser = userTokenService.getLoginUser();
        anpParam.setLoginUser(loginUser);
        anpParam.setPkCountry(SecurityUtils.getPkCountry());
        ActivityParam activityParam = anpParam.getActivityParam();
        activityParam.setActType(EActType.NEW_GIFT.getValue());
        anpParam.setApprovalType(EApprovalBusiness.SUPE_RWORK.getValue());
        return AjaxResult.success(iAcNewPeopleRuleConfigService.petition(anpParam));
    }

    /**
     * @description: 删除新人活动礼包
     * @author: zhang jing
     * @date: 2023/4/25 9:24
     * @param: [anpVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.NEW_PACK, business = EOperationBusiness.NEW_PACK, method = EOperationMethod.DELETE)
    @PostMapping("/del-petition")
    public AjaxResult delPetition(@RequestBody AcBaseConfigParam anpParam) {
        // 验证参数
        anpParam.setControlType(EControlType.DELETE.getValue());
        List<String> errorList = validateParams(anpParam);
        if (!errorList.isEmpty()) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorList);
        }
        // 设置参数
        LoginUser loginUser = userTokenService.getLoginUser();
        anpParam.setLoginUser(loginUser);
        anpParam.setPkCountry(SecurityUtils.getPkCountry());
        ActivityParam activityParam = anpParam.getActivityParam();
        activityParam.setActType(EActType.NEW_GIFT.getValue());
        anpParam.setApprovalType(EApprovalBusiness.SUPE_RWORK.getValue());
        return AjaxResult.success(iAcNewPeopleRuleConfigService.petition(anpParam));
    }


    // 验证参数
    private List<String> validateParams(AcBaseConfigParam anpParam) {
        List<String> errorList = new ArrayList<>();
        if (StringUtils.isNull(anpParam)) {
            errorList.add(TransactionUtils.getContent(ConfigMsgConstants.ACTIVITY_NOT_NULL));
        }
        if (StringUtils.isNull(anpParam.getSignType())) {
            errorList.add(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
        }
        return errorList;
    }

}
