package com.hzs.member.base.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.EnumsPrefixConstants;
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.poi.ExcelUtil;
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.member.ext.CuMemberExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.*;
import com.hzs.member.base.vo.UpdateExpireStopVO;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @description: 特殊配置-修改会员续约
 * @author: zhang jing
 * @date: 2024/6/4 11:10
 * @param:
 * @return:
 **/
@RequestMapping("/manager/updateExpireStop")
@RestController
public class UpdateExpireStopController extends BaseController {

    @Autowired
    private ICuMemberService cuMemberService;

    @Autowired
    public void setCuMemberService(ICuMemberService cuMemberService) {
        this.cuMemberService = cuMemberService;
    }

    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;


    /**
     * @description: 特殊业务-修改会员续约
     * @author: zhang jing
     * @date: 2022/11/17 15:39
     * @param: []
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @AccessPermissions("MemberRenewal")
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_EXPIRE_STOP, method = EOperationMethod.SELECT)
    @GetMapping("/puCodeList")
    public TableDataInfo puCodeList(UpdateExpireStopVO updateExpireStopVO) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        updateExpireStopVO.setPkCountry(pkCountry);
        List<UpdateExpireStopVO> list = cuMemberService.getMemberExpireStopList(updateExpireStopVO);
        list.forEach(itm -> {
            UpdateExpireStopVO ues = JSONObject.parseObject(itm.getNewValue(), UpdateExpireStopVO.class);
            itm.setExpireDateOld(ues.getExpireDateOld());
            itm.setStopDateOld(ues.getStopDateOld());
            itm.setExpireStatusOld(ues.getExpireStatusOld());
            itm.setExpireDateNew(ues.getExpireDateNew());
            itm.setStopDateNew(ues.getStopDateNew());
            itm.setExpireStatusNew(ues.getExpireStatusNew());
            itm.setExpireStatusOldVal(EExpireStatus.getEnumByValue(ues.getExpireStatusOld()).getLabel());
        });
        return getDataTable(list);
    }

    /**
     * @description: 查询特殊业务会员续约
     * @author: zhang jing
     * @date: 2023/7/17 11:52
     * @param: [updateExpireStopVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_EXPIRE_STOP, method = EOperationMethod.SELECT)
    @GetMapping("/specialBusinessQuery")
    public AjaxResult specialBusinessQuery(UpdateExpireStopVO updateExpireStopVO) {
        if (StringUtils.isEmpty(updateExpireStopVO.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_EMPTY));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        updateExpireStopVO.setPkCountry(pkCountry);
        CuMemberExt cme = cuMemberService.getMemberByCode(updateExpireStopVO.getMemberCode());
        updateExpireStopVO = upExpireStopVO(updateExpireStopVO, cme);
        if (null == cme) {
            return AjaxResult.success(cme);
        }
        return AjaxResult.success(updateExpireStopVO);
    }


    /**
     * 导出续约
     *
     * @param response
     * @param updateExpireStopVO
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_EXPIRE_STOP, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UpdateExpireStopVO updateExpireStopVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        updateExpireStopVO.setPkCountry(pkCountry);
        List<UpdateExpireStopVO> list = cuMemberService.getMemberExpireStopList(updateExpireStopVO);
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EApproveStatus.values());
        list.forEach(itm -> {
            UpdateExpireStopVO ues = JSONObject.parseObject(itm.getNewValue(), UpdateExpireStopVO.class);
            itm.setExpireDateOld(ues.getExpireDateOld());
            itm.setStopDateOld(ues.getStopDateOld());
            itm.setExpireStatusOld(ues.getExpireStatusOld());
            itm.setExpireDateNew(ues.getExpireDateNew());
            itm.setStopDateNew(ues.getStopDateNew());
            itm.setExpireStatusNew(ues.getExpireStatusNew());
            itm.setExpireStatusOldVal(EExpireStatus.getEnumByValue(ues.getExpireStatusOld()).getLabel());
            itm.setApproveStatusVal(transactionMap.get(EnumsPrefixConstants.APPROVE_STATUS + itm.getApproveStatus()));
        });
        ExcelUtil<UpdateExpireStopVO> util = new ExcelUtil<>(UpdateExpireStopVO.class);
        util.exportExcel(response, list, "导出会员续约");
    }

    /**
     * 下载模板
     *
     * @param response
     * @param
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_EXPIRE_STOP, method = EOperationMethod.EXPORT)
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        List<UpdateExpireStopImportVO> list = new ArrayList<>();
        ExcelUtil<UpdateExpireStopImportVO> util = new ExcelUtil<>(UpdateExpireStopImportVO.class);
        util.exportExcel(response, list, "修改会员续约");
    }

    /**
     * @description: 导入会员信息
     * @author: zhang jing
     * @date: 2023/1/11 10:27
     * @param: [file, updateSupport]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_EXPIRE_STOP, method = EOperationMethod.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<UpdateExpireStopImportVO> util = new ExcelUtil<>(UpdateExpireStopImportVO.class);
        List<UpdateExpireStopImportVO> list = util.importExcel(file.getInputStream());
        List<UpdateExpireStopVO> newlist = new ArrayList<>();
        List<UpdateExpireStopVO> errorlist = new ArrayList<>();
        Date date = DateUtils.currentDate();
        if (CollectionUtil.isNotEmpty(list)) {
            //过滤重复数据
            Set<String> seenMemberCodes = new HashSet<>();
            List<UpdateExpireStopImportVO> filteredList = list.stream()
                    .filter(vo -> seenMemberCodes.add(vo.getMemberCode()))
                    .collect(Collectors.toList());

            for (UpdateExpireStopImportVO ucv : filteredList) {
                if (StringUtils.isNull(ucv.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
//                if (StringUtils.isNull(ucv.getYears())) {
//                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_EXPIRE_STOP_NOT_NULL));
//                }
                CuMemberExt cuMember = cuMemberService.getMemberByCode(ucv.getMemberCode());
                if (StringUtils.isNull(cuMember)) {
                    UpdateExpireStopVO updateExpireStopVO = BeanUtil.copyProperties(ucv, UpdateExpireStopVO.class);
                    updateExpireStopVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
                    errorlist.add(updateExpireStopVO);
                } else {
                    UpdateExpireStopVO updateExpireStopVO = new UpdateExpireStopVO();
                    updateExpireStopVO = upExpireStopVO(updateExpireStopVO, cuMember);
                    newlist.add(updateExpireStopVO);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
        }
        return AjaxResult.success(newlist);
    }


    /**
     * @description: 选择会员进行修改续约
     * @author: zhang jing
     * @date: 2023/3/27 17:52
     * @param: [updateExpireStopVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_EXPIRE_STOP, method = EOperationMethod.SELECT)
    @PostMapping("/selected")
    public AjaxResult selected(@RequestBody UpdateExpireStopVO updateExpireStopVO) {
        if (StringUtils.isEmpty(updateExpireStopVO.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        List<UpdateExpireStopVO> errorlist = new ArrayList<>();
        CuMemberExt cuMember = cuMemberService.getMemberByCode(updateExpireStopVO.getMemberCode());
        if (StringUtils.isNull(cuMember)) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        updateExpireStopVO = BeanUtil.copyProperties(cuMember, UpdateExpireStopVO.class);
        //当前最大次数
        Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(cuMember.getPkId(),
                EApprovalBusiness.MEMBER_EXPIRE_STOP.getValue(), EApproveStatus.FINISH.getValue());
        updateExpireStopVO.setChangeNumber(approveNumber + 1);
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
        }
        return AjaxResult.success(updateExpireStopVO);
    }

    /**
     * @description: 修改会员续约发起签呈
     * @author: zhang jing
     * @date: 2022/12/30 10:22
     * @param: [postageParams]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_EXPIRE_STOP, method = EOperationMethod.SUBMIT)
    @PostMapping("/upExpireStop")
    public AjaxResult upExpireStop(@RequestBody UpdateExpireStopVO updateExpireStopVO) {
        List<UpdateExpireStopVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(updateExpireStopVO.getUesList())) {
            //只有免签和确认
            if (StringUtils.isNull(updateExpireStopVO.getProcessType())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
            }
            Date date = new Date();
            Integer pkCountry = SecurityUtils.getPkCountry();
            updateExpireStopVO.setPkCountry(pkCountry);
            updateExpireStopVO.setPkCreator(SecurityUtils.getUserId());
            updateExpireStopVO.setModifiedTime(date);
            for (UpdateExpireStopVO uc : updateExpireStopVO.getUesList()) {
                if (StringUtils.isEmpty(uc.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getPkId())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PKID_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getExpireDateNew()) ||
                        StringUtils.isNull(uc.getStopDateNew())) {
                    uc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_EXPIRE_STOP_NOT_NULL));
                    errorlist.add(uc);
                    continue;
                }
                uc.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
                uc.setPkCountry(pkCountry);
                //校验是否存在待审核数据
                List<UpdateExpireStopVO> list = cuMemberService.getMemberExpireStopList(uc);
                if (CollectionUtil.isNotEmpty(list)) {
                    uc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(uc);
                    continue;
                }
                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(uc.getPkId(),
                        EApprovalBusiness.MEMBER_EXPIRE_STOP.getValue(), EApproveStatus.FINISH.getValue());
                uc.setChangeNumber(approveNumber + 1);
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }
            updateExpireStopVO = cuMemberService.upExpireStop(updateExpireStopVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(updateExpireStopVO);
    }


    /**
     * @description: 计算增加年数时间
     * @author: zhang jing
     * @date: 2024/6/4 16:33
     * @param: [expireDate, year]
     * @return: java.util.Date
     **/
    public Date addYear(Date expireDate, Integer year) {
        // 创建Calendar对象，并设置为expireDate的值
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(expireDate);
        // 在calendar上增加year年
        calendar.add(Calendar.YEAR, year);
        // 获取增加1年后的日期
        return calendar.getTime();
    }

    /**
     * @description: 更新UpdateExpireStopVO
     * @author: zhang jing
     * @date: 2024/6/5 11:48
     * @param: [updateExpireStopVO, cuMember]
     * @return: com.hzs.member.base.vo.UpdateExpireStopVO
     **/
    public UpdateExpireStopVO upExpireStopVO(UpdateExpireStopVO updateExpireStopVO, CuMemberExt cuMember) {
        Date date = DateUtils.currentDate();
        updateExpireStopVO = BeanUtil.copyProperties(cuMember, UpdateExpireStopVO.class);
        if (cuMember.getExpireDate() != null) {
            updateExpireStopVO.setExpireDateNew(addYear(cuMember.getExpireDate(), updateExpireStopVO.getYears()));
        }
        if (cuMember.getStopDate() != null) {
            updateExpireStopVO.setStopDateNew(addYear(cuMember.getStopDate(), updateExpireStopVO.getYears()));
        }
        updateExpireStopVO.setExpireDateOld(cuMember.getExpireDate());
        updateExpireStopVO.setStopDateOld(cuMember.getStopDate());
        //如果有效状态是休止期则加完时间后修改状态为有效期
        if (cuMember.getExpireStatus() == EExpireStatus.REST.getValue()) {
            if (DateUtils.compareDateBefore(date, updateExpireStopVO.getExpireDateNew())) {
                updateExpireStopVO.setExpireStatusOld(cuMember.getExpireStatus());
                updateExpireStopVO.setExpireStatusNew(EExpireStatus.EXPIRE.getValue());
            }
        } else {
            updateExpireStopVO.setExpireStatusOld(cuMember.getExpireStatus());
            updateExpireStopVO.setExpireStatusNew(cuMember.getExpireStatus());
        }
        //判断状态是否为已终止
        if (updateExpireStopVO.getStopDateNew() != null && DateUtils.compareDateBefore(updateExpireStopVO.getStopDateNew(), date)) {
            updateExpireStopVO.setExpireStatusNew(EExpireStatus.TERMINATED.getValue());
        }
        //当前最大次数
        Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(updateExpireStopVO.getPkId(),
                EApprovalBusiness.CHANGE_MEMBER_CODE.getValue(), EApproveStatus.FINISH.getValue());
        updateExpireStopVO.setChangeNumber(approveNumber + 1);
        return updateExpireStopVO;
    }


}
