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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.activity.pick.param.AcPickQueryParam;
import com.hzs.activity.pick.param.AcPickSaveDetailParam;
import com.hzs.activity.pick.param.AcPickSaveParam;
import com.hzs.activity.pick.service.IAcPickService;
import com.hzs.activity.pick.vo.AcPickQueryDetailVO;
import com.hzs.activity.pick.vo.AcPickQueryVO;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.constant.msg.ProductMsgConstants;
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.activity.pick.ext.AcPickExt;
import com.hzs.common.domain.activity.base.ext.AcGiftConfigExt;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.product.IProductServiceApi;
import com.hzs.sale.product.dto.ProductDTO;
import com.hzs.system.sys.dto.LoginUser;
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.*;
import java.util.stream.Collectors;

/**
 * 提货处理控制器
 */
@RequestMapping("/manage/pick")
@RestController
public class AcPickController extends BaseController {

    @Autowired
    private IAcPickService iAcPickService;
    @Autowired
    private IAcGiftConfigService iAcGiftConfigService;
    @Autowired
    private UserTokenService userTokenService;

    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    IProductServiceApi iProductServiceApi;

    /**
     * 查询列表
     *
     * @param param 查询入参
     * @return
     */
    @Log(module = EOperationModule.RECHARGE_PICK, business = EOperationBusiness.RECHARGE_PICK, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(AcPickQueryParam param) {
        param.setCreationTime(DateUtils.handTimeStartAndEnd(param.getCreationTime()));
        param.setModifiedTime(DateUtils.handTimeStartAndEnd(param.getModifiedTime()));
        param.setReceiveTime(DateUtils.handTimeStartAndEnd(param.getReceiveTime()));

        Integer pkCountry = SecurityUtils.getPkCountry();

        // 最终返回数量
        List<AcPickQueryVO> resultList = new ArrayList<>();

        startPage();
        List<AcPickExt> acPickExtList = iAcPickService.queryList(param, pkCountry);

        if (CollectionUtil.isNotEmpty(acPickExtList)) {
            // 活动规则ID列表
            List<Long> ruleIdList = acPickExtList.stream().filter(acPickQueryVO -> EPickType.PICK_PRODUCT.getValue() != acPickQueryVO.getPickType()).map(AcPickExt::getPkDataId).collect(Collectors.toList());

            // 活动规则赠品数据
            Map<Long, List<AcGiftConfigExt>> giftConfigMap = null;
            if (CollectionUtil.isNotEmpty(ruleIdList)) {
                giftConfigMap = iAcGiftConfigService.queryListByRuleIdList(ruleIdList, pkCountry);
            }

            for (AcPickExt acPickExt : acPickExtList) {
                AcPickQueryVO acPickQueryVO = BeanUtil.copyProperties(acPickExt, AcPickQueryVO.class);

                acPickQueryVO.setPickTypeVal(EPickType.getEnumByValue(acPickQueryVO.getPickType()).getLabel());

                if (EPickType.PICK_PRODUCT.getValue() == acPickExt.getPickType()) {
                    // 提货产品
                    acPickQueryVO.setDetailList(Collections.singletonList(AcPickQueryDetailVO.builder()
                            .productName(acPickExt.getProductName())
                            .quantity(acPickExt.getBaseQuantity())
                            .build()));
                } else {
                    // 其它都为活动处理
                    if (null != giftConfigMap) {
                        List<AcGiftConfigExt> acGiftConfigList = giftConfigMap.get(acPickExt.getPkDataId());
                        if (CollectionUtil.isNotEmpty(acGiftConfigList)) {
                            acPickQueryVO.setDetailList(BeanUtil.copyToList(acGiftConfigList, AcPickQueryDetailVO.class));
                            for (AcPickQueryDetailVO acPickQueryDetailVO : acPickQueryVO.getDetailList()) {
                                acPickQueryDetailVO.setProductName(acPickQueryDetailVO.getProductName() + "(" + acPickQueryDetailVO.getSpecsName() + ")");
                            }
                        }
                    }
                }
                resultList.add(acPickQueryVO);
            }
        }

        TableDataInfo tableDataInfo = getDataTable(acPickExtList);
        tableDataInfo.setRows(resultList);
        return tableDataInfo;
    }

    /**
     * 导出
     *
     * @param response
     * @param param    查询入参
     */
    @Log(module = EOperationModule.RECHARGE_PICK, business = EOperationBusiness.RECHARGE_PICK, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AcPickQueryParam param) {
        param.setCreationTime(DateUtils.handTimeStartAndEnd(param.getCreationTime()));
        param.setModifiedTime(DateUtils.handTimeStartAndEnd(param.getModifiedTime()));
        param.setReceiveTime(DateUtils.handTimeStartAndEnd(param.getReceiveTime()));

        Integer pkCountry = SecurityUtils.getPkCountry();

        // 最终返回数量
        List<AcPickQueryVO> resultList = new ArrayList<>();

        List<AcPickExt> acPickExtList = iAcPickService.queryList(param, pkCountry);

        if (CollectionUtil.isNotEmpty(acPickExtList)) {
            // 活动规则ID列表
            List<Long> ruleIdList = acPickExtList.stream().filter(acPickQueryVO -> EPickType.PICK_PRODUCT.getValue() != acPickQueryVO.getPickType()).map(AcPickExt::getPkDataId).collect(Collectors.toList());

            // 活动规则赠品数据
            Map<Long, List<AcGiftConfigExt>> giftConfigMap = null;
            if (CollectionUtil.isNotEmpty(ruleIdList)) {
                giftConfigMap = iAcGiftConfigService.queryListByRuleIdList(ruleIdList, pkCountry);
            }

            for (AcPickExt acPickExt : acPickExtList) {
                AcPickQueryVO acPickQueryVO = BeanUtil.copyProperties(acPickExt, AcPickQueryVO.class);

                acPickQueryVO.setPickTypeVal(EPickType.getEnumByValue(acPickQueryVO.getPickType()).getLabel());

                if (EPickType.PICK_PRODUCT.getValue() == acPickExt.getPickType()) {
                    // 产品处理
                    acPickQueryVO.setDetailList(Collections.singletonList(AcPickQueryDetailVO.builder()
                            .productName(acPickExt.getProductName())
                            .quantity(acPickExt.getBaseQuantity())
                            .build()));
                    acPickQueryVO.setProductData(acPickExt.getProductName() + " * " + acPickExt.getBaseQuantity() + ";");
                } else {
                    // 其它都为活动处理
                    if (null != giftConfigMap) {
                        List<AcGiftConfigExt> giftConfigList = giftConfigMap.get(acPickExt.getPkDataId());
                        if (CollectionUtil.isNotEmpty(giftConfigList)) {
                            StringBuilder productDataSb = new StringBuilder();
                            for (AcGiftConfigExt acGiftConfigExt : giftConfigMap.get(acPickExt.getPkDataId())) {
                                productDataSb.append(acGiftConfigExt.getProductName()).append(" * ").append(acGiftConfigExt.getQuantity()).append("; \n");
                            }
                            acPickQueryVO.setProductData(productDataSb.toString());
                        }
                    }
                }
                resultList.add(acPickQueryVO);
            }
        }

        ExcelUtil<AcPickQueryVO> util = new ExcelUtil<>(AcPickQueryVO.class);
        util.exportExcel(response, resultList, "充值提货卡导出");
    }

    /**
     * 查看详情
     *
     * @param pkId 提货ID
     * @return
     */
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam("pkId") Long pkId) {
        AcPickQueryVO acPickQueryVO = new AcPickQueryVO();

        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();

        AcPickExt acPickExt = iAcPickService.queryDetail(pkId, pkCountry);
        if (null != acPickExt) {
            acPickQueryVO = BeanUtil.copyProperties(acPickExt, AcPickQueryVO.class);
            if (EPickType.PICK_PRODUCT.getValue() == acPickExt.getPickType()) {
                // 产品处理
                acPickQueryVO.setDetailList(Collections.singletonList(AcPickQueryDetailVO.builder()
                        .pkProduct(acPickExt.getPkDataId().intValue())
                        .productName(acPickExt.getProductName())
                        .specsName(acPickExt.getSpecsName())
                        .specsNameId(acPickExt.getSpecsNameId())
                        .quantity(acPickExt.getBaseQuantity())
                        .build()));
            } else {
                // 查询活动规则赠品数据
                Map<Long, List<AcGiftConfigExt>> giftConfigMap = iAcGiftConfigService.queryListByRuleIdList(Collections.singletonList(acPickExt.getPkDataId()), pkCountry);
                if (null != giftConfigMap) {
                    acPickQueryVO.setDetailList(BeanUtil.copyToList(giftConfigMap.get(acPickExt.getPkDataId()), AcPickQueryDetailVO.class));
                    if (CollectionUtil.isNotEmpty(acPickQueryVO.getDetailList())) {
                        for (AcPickQueryDetailVO acPickQueryDetailVO : acPickQueryVO.getDetailList()) {
                            acPickQueryDetailVO.setProductName(acPickQueryDetailVO.getProductName() + "(" + acPickQueryDetailVO.getSpecsName() + ")");
                        }
                    }
                }
            }
        }
        return AjaxResult.success(acPickQueryVO);
    }

    /**
     * 提交签呈
     *
     * @param param 提交签呈入参
     * @return
     */
    @Log(module = EOperationModule.RECHARGE_PICK, business = EOperationBusiness.RECHARGE_PICK, method = EOperationMethod.SUBMIT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody AcPickSaveParam param) {
        if (null == param.getSignType() || CollectionUtil.isEmpty(param.getUserIdList())
                || CollectionUtil.isEmpty(param.getDetailList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        for (AcPickSaveDetailParam detailParam : param.getDetailList()) {
            if (StringUtils.isAnyEmpty(detailParam.getMemberCode(), detailParam.getSpecsName(), detailParam.getSpecsNameId())
                    || null == detailParam.getPkProduct() || null == detailParam.getBaseQuantity() || null == detailParam.getQuantity()
                    || null == detailParam.getIsFreeMail()) {
                // 缺少参数
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
            if (EYesNo.NO.getIntValue() == detailParam.getIsFreeMail() && null == detailParam.getPkPostage()) {
                // 不包邮，则必须传入邮费模板
                // 缺少参数
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }

            // 手动添加提货数据比较少，此处查人和产品先单次查，如果同时操作人过多可以改成批量，或者不进行校验
            CuMember cuMember = iMemberServiceApi.getMember(detailParam.getMemberCode()).getData();
            if (null == cuMember) {
                // 会员不存在，请重新输入会员编号
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
            }

            ProductDTO productDTO = iProductServiceApi.getProduct(detailParam.getPkProduct()).getData();
            if (null == productDTO) {
                // 产品不存在
                return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_NOT_REQUIRED));
            }
        }

        String str = iAcPickService.pickSubmit(param, userTokenService.getLoginUser());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }

    /**
     * @description: 删除充值提货卡
     * @author: zhang jing
     * @date: 2023/10/17 17:35
     * @param: [anpParam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.RECHARGE_PICK, business = EOperationBusiness.RECHARGE_PICK, method = EOperationMethod.DELETE)
    @PostMapping("/del-pick")
    public AjaxResult delPick(@RequestBody AcPickSaveParam anpParam) {
        if (null == anpParam.getSignType() || CollectionUtil.isEmpty(anpParam.getUserIdList())
                || CollectionUtil.isEmpty(anpParam.getDetailList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        // 设置参数
        LoginUser loginUser = userTokenService.getLoginUser();
        anpParam.setLoginUser(loginUser);
        anpParam.setPkCountry(SecurityUtils.getPkCountry());
        anpParam.setApprovalBusiness(EApprovalBusiness.PICK_ADD_DEL.getValue());
        return AjaxResult.success(iAcPickService.delPick(anpParam));
    }

}
