package com.hzs.activity.policy.controller.manage;/**
 * @Description:
 * @Author: yuhui
 * @Time: 2023/12/26 10:12
 * @Classname: PolicyConfigController
 * @PackageName: com.hzs.activity.policy.controller
 */

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.IActivityService;
import com.hzs.activity.policy.param.PolicyConfigParam;
import com.hzs.activity.policy.param.PolicyConfigQueryParam;
import com.hzs.activity.policy.service.IAcPolicyConfigService;
import com.hzs.activity.policy.vo.AcBaseConfigExportVo;
import com.hzs.activity.policy.vo.AcPolicyConfigVo;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.enums.EActType;
import com.hzs.common.core.enums.EActivityStatus;
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.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.activity.base.AcBaseConfig;
import com.hzs.common.domain.policy.AcPolicyConfig;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.system.base.ICurrencyServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 *@BelongsProject: hzs_java_cloud_africa
 *@BelongsPackage: com.hzs.activity.policy.controller
 *@Author: yh
 *@CreateTime: 2023-12-26  10:12
 *@Description: TODO
 *@Version: 1.0
 */
@RequestMapping("/manage/policy")
@RestController
public class PolicyConfigController extends BaseController{
    @Autowired
    private IAcBaseConfigService baseConfigService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private IAcPolicyConfigService policyConfigService;
    @DubboReference
    private ICurrencyServiceApi currencyServiceApi;
    /**
     * 查询全部
     * @return
     */
    @GetMapping("list")
    public AjaxResult list(PolicyConfigQueryParam policyConfigQueryParam){
        Integer pkCountry = SecurityUtils.getPkCountry();
//        R<CurrencyDTO> currencyDTO = currencyServiceApi.getCurrency(pkCountry);
//        CurrencyDTO currency = currencyDTO.getData();
        QueryWrapper<AcBaseConfig> queryWrapper = new QueryWrapper<AcBaseConfig>();
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        queryWrapper.eq("ACT_TYPE", EActType.POLICY.getValue());
        if (StringUtils.isNotBlank(policyConfigQueryParam.getActName())){
            queryWrapper.like("ACT_NAME", policyConfigQueryParam.getActName());
        }
        if (policyConfigQueryParam.getStartActStartDate() != null && policyConfigQueryParam.getEndActStartDate() != null){
           queryWrapper.between("ACT_START_DATE", DateUtils.getStartTime(policyConfigQueryParam.getStartActStartDate()),
                    DateUtils.getEndTime(policyConfigQueryParam.getEndActStartDate()));
        }
        if (policyConfigQueryParam.getStartActEndDate() != null && policyConfigQueryParam.getEndActEndDate() != null){
            queryWrapper.between("ACT_END_DATE", DateUtils.getStartTime(policyConfigQueryParam.getStartActEndDate()),
                    DateUtils.getEndTime(policyConfigQueryParam.getEndActEndDate()));
        }
        // 创建时间
        if (policyConfigQueryParam.getStartCreateDate() != null && policyConfigQueryParam.getEndCreateDate() != null){
            queryWrapper.between("CREATION_TIME", DateUtils.getStartTime(policyConfigQueryParam.getStartCreateDate()),
                    DateUtils.getEndTime(policyConfigQueryParam.getEndCreateDate()));
        }
        // 自定义条件
        String condition = "";
        if (policyConfigQueryParam.getStatus() != null){
            // 活动状态
            if (policyConfigQueryParam.getStatus().equals(EActivityStatus.NOT_STARTED.getValue())){
                condition = "  (  (SELECT SYSDATE FROM DUAL) < ACT_START_DATE     )  ";
            }else if (policyConfigQueryParam.getStatus().equals(EActivityStatus.IN_PROGRESS.getValue())){
                condition ="  (   ((SELECT SYSDATE FROM DUAL) > ACT_START_DATE  and (to_date(to_char(SYSDATE, 'yyyy-MM-dd hh:mi:ss'), 'yyyy-MM-dd hh:mi:ss')) <= ACT_END_DATE )    )";
            }else if (policyConfigQueryParam.getStatus().equals(EActivityStatus.EXPIRED.getValue())){
                condition ="  (    (to_date(to_char(SYSDATE, 'yyyy-MM-dd hh:mi:ss'), 'yyyy-MM-dd hh:mi:ss')) > ACT_END_DATE  )";
            }
            // 组装条件
            queryWrapper.apply(condition);
        }
        List<AcBaseConfig> baseConfigList = baseConfigService.list(queryWrapper);
        List<AcPolicyConfigVo> resultList = baseConfigList.stream().map(a -> {
            AcPolicyConfigVo acBaseConfigExt = BeanUtil.copyProperties(a, AcPolicyConfigVo.class);
            // 判断活动状态
            // 开始时间
            long startTime = a.getActStartDate().getTime();
            // 结束时间
            long endTime = a.getActEndDate().getTime();
            // 当前时间
            long currentTime = DateUtils.currentDateTime().getTime();
            if ((currentTime > startTime && currentTime <= endTime) ) {
                // 当前时间大于开始 小于结束
                acBaseConfigExt.setStatus(EActivityStatus.IN_PROGRESS.getLabel());
            } else if (currentTime < startTime) {
                // 当前时间小于开始时间
                acBaseConfigExt.setStatus(EActivityStatus.NOT_STARTED.getLabel());
            } else if (currentTime > endTime) {
                // 当前时间大于结束时间
                acBaseConfigExt.setStatus(EActivityStatus.EXPIRED.getLabel());
            }
            return acBaseConfigExt;
        }).collect(Collectors.toList());


        return AjaxResult.success(resultList);
    }

    /**
     * 批量新增/修改
     * @param policyConfigParam
     * @return
     */
    @PostMapping("save-or-update")
    public AjaxResult save(@RequestBody PolicyConfigParam policyConfigParam){
         Integer pkCountry = SecurityUtils.getPkCountry();

        //ActivityParam activityParam = policyConfigParam.getActivityParam();

        policyConfigService.saveAll(policyConfigParam,pkCountry);
        return AjaxResult.success();
    }
    @GetMapping("detail")
    public AjaxResult detail(Long pkBaseId){
        //
        AcBaseConfig baseConfig = baseConfigService.getById(pkBaseId);
        ActivityParam activityParam = BeanUtil.copyProperties(baseConfig, ActivityParam.class);

        QueryWrapper<AcPolicyConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_BASE_ID",pkBaseId);
        List<AcPolicyConfig> policyConfigList = policyConfigService.list(queryWrapper);
        PolicyConfigParam policyConfigParam = new PolicyConfigParam();
        policyConfigParam.setActivityParam(activityParam);
        policyConfigParam.setPolicyConfigList(policyConfigList);
        return AjaxResult.success(policyConfigParam);
    }

    /**
     * 签呈
     */
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody PolicyConfigParam param) {
        if (null == param.getSignType() || CollectionUtil.isEmpty(param.getUserIdList())
             ) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        return AjaxResult.success(policyConfigService.policyConfigSubmit(param,userTokenService.getLoginUser()));
    }

    /**
     * 导出
     * @param policyConfigQueryParam
     */
    @PostMapping("export")
    public void export(PolicyConfigQueryParam policyConfigQueryParam, HttpServletResponse response){
        Integer pkCountry = SecurityUtils.getPkCountry();
        QueryWrapper<AcBaseConfig> queryWrapper = new QueryWrapper<AcBaseConfig>();
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        queryWrapper.eq("ACT_TYPE", EActType.POLICY.getValue());
        if (StringUtils.isNotBlank(policyConfigQueryParam.getActName())){
            queryWrapper.like("ACT_NAME", policyConfigQueryParam.getActName());
        }
        if (policyConfigQueryParam.getStartActStartDate() != null && policyConfigQueryParam.getEndActStartDate() != null){
            queryWrapper.between("ACT_START_DATE", DateUtils.getStartTime(policyConfigQueryParam.getStartActStartDate()),
                    DateUtils.getEndTime(policyConfigQueryParam.getEndActStartDate()));
        }
        if (policyConfigQueryParam.getStartActEndDate() != null && policyConfigQueryParam.getEndActEndDate() != null){
            queryWrapper.between("ACT_END_DATE", DateUtils.getStartTime(policyConfigQueryParam.getStartActEndDate()),
                    DateUtils.getEndTime(policyConfigQueryParam.getEndActEndDate()));
        }
        // 创建时间
        if (policyConfigQueryParam.getStartCreateDate() != null && policyConfigQueryParam.getEndCreateDate() != null){
            queryWrapper.between("CREATION_TIME", DateUtils.getStartTime(policyConfigQueryParam.getStartCreateDate()),
                    DateUtils.getEndTime(policyConfigQueryParam.getEndCreateDate()));
        }
        List<AcBaseConfig> baseConfigList = baseConfigService.list(queryWrapper);
        List<AcBaseConfigExportVo> resultList = baseConfigList.stream().map(a -> {

            AcBaseConfigExportVo acBaseConfigExt = BeanUtil.copyProperties(a, AcBaseConfigExportVo.class);
            // 判断活动状态
            // 开始时间
            long startTime = a.getActStartDate().getTime();
            // 结束时间
            long endTime = a.getActEndDate().getTime();
            // 当前时间
            long currentTime = DateUtils.currentDate().getTime();
            if ((currentTime > startTime && currentTime < endTime) || currentTime == startTime || currentTime == endTime) {
                // 当前时间大于开始 小于结束
                acBaseConfigExt.setStatus(EActivityStatus.IN_PROGRESS.getLabel());
            } else if (currentTime < startTime) {
                // 当前时间小于开始时间
                acBaseConfigExt.setStatus(EActivityStatus.NOT_STARTED.getLabel());
            } else if (currentTime > endTime) {
                // 当前时间大于结束时间
                acBaseConfigExt.setStatus(EActivityStatus.EXPIRED.getLabel());
            }
            return acBaseConfigExt;
        }).collect(Collectors.toList());
        ExcelUtil<AcBaseConfigExportVo> util = new ExcelUtil<>(AcBaseConfigExportVo.class);
        util.exportExcel(response, resultList, "政策币赠送导出");
    }
}
