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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.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.retail.member.CuMemberRetailRegion;
import com.hzs.common.domain.retail.member.ext.CuMemberRetailRegionExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.retail.member.param.RetailMemberRegionParam;
import com.hzs.retail.member.service.ICuMemberRetailRegionService;
import com.hzs.retail.member.vo.UnboundAreaVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @description: 新零售收益区域配置
 * @author: zhang jing
 * @date: 2024/12/25 12:03
 * @param:
 * @return:
 **/
@RestController
@RequestMapping("/manage/cu-member-retail-region")
public class CuMemberRetailRegionController extends BaseController {

    @Autowired
    private ICuMemberRetailRegionService cuMemberRetailRegionService;


    /**
     * @description: 会员收益区域配置
     * @author: zhang jing
     * @date: 2024/12/25 15:02
     * @param: [mrrExt]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.CU_MEMBER_RETAIL_REGION, business = EOperationBusiness.CU_MEMBER_RETAIL_REGION, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(CuMemberRetailRegionExt mrrExt) {
        mrrExt.setPkCountry(SecurityUtils.getPkCountry());
        mrrExt.setSystemType(SecurityUtils.getSystemType());

        startPage();
        List<CuMemberRetailRegionExt> list = cuMemberRetailRegionService.memberretailRegList(mrrExt);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setSourceVal(ENoticeWebsiteType.getNoticeWebsiteType(itm.getSource()).getLabel());
            });
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出会员收益区域配置
     * @author: zhang jing
     * @date: 2024/12/25 14:59
     * @param: [response, mrrExt]
     * @return: void
     **/
    @Log(module = EOperationModule.CU_MEMBER_RETAIL_REGION, business = EOperationBusiness.CU_MEMBER_RETAIL_REGION, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CuMemberRetailRegionExt mrrExt) {
        mrrExt.setPkCountry(SecurityUtils.getPkCountry());
        mrrExt.setSystemType(SecurityUtils.getSystemType());

        List<CuMemberRetailRegionExt> list = cuMemberRetailRegionService.memberretailRegList(mrrExt);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setSourceVal(ENoticeWebsiteType.getNoticeWebsiteType(itm.getSource()).getLabel());
            });
        }
        ExcelUtil<CuMemberRetailRegionExt> util = new ExcelUtil<>(CuMemberRetailRegionExt.class);
        util.exportExcel(response, list, "会员收益区域配置");
    }

    /**
     * @description: 未绑定收益区域
     * @author: zhang jing
     * @date: 2025/1/9 13:54
     * @param: []
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @GetMapping("/regionAreaList")
    public TableDataInfo regionAreaList() {
        startPage();
        List<UnboundAreaVO> areaList = cuMemberRetailRegionService.unboundAreaList(SecurityUtils.getPkCountry(), SecurityUtils.getSystemType());
        return getDataTable(areaList);
    }

    /**
     * @description: 导出未配置收益区域
     * @author: zhang jing
     * @date: 2025/1/15 11:05
     * @param: [response, mrrExt]
     * @return: void
     **/
    @Log(module = EOperationModule.NOT_USED_REGION_AREA, business = EOperationBusiness.NOT_USED_REGION_AREA, method = EOperationMethod.EXPORT)
    @PostMapping("/export-region-area")
    public void exportRegionAreaList(HttpServletResponse response) {
        List<UnboundAreaVO> areaList = cuMemberRetailRegionService.unboundAreaList(SecurityUtils.getPkCountry(), SecurityUtils.getSystemType());
        ExcelUtil<UnboundAreaVO> util = new ExcelUtil<>(UnboundAreaVO.class);
        util.exportExcel(response, areaList, "未配置收益区域");
    }

    /**
     * @description:新增会员收益区域
     * @author: zhang jing
     * @date: 2024/12/25 16:18
     * @param: [mrrExt]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_RETAIL_REGION, business = EOperationBusiness.CU_MEMBER_RETAIL_REGION, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody @Valid RetailMemberRegionParam mrrExt) {
        if (StringUtils.isNull(mrrExt.getPkMember())) {
            return AjaxResult.error(ConfigMsgConstants.MEMBER_NOT_NULL);
        }
        if (StringUtils.isNull(mrrExt.getProvince())) {
            return AjaxResult.error(ConfigMsgConstants.GLO_PROVINCE_NOT_NULL);
        }
        if (StringUtils.isNull(mrrExt.getCity())) {
            return AjaxResult.error(ConfigMsgConstants.GLO_CITY_NOT_NULL);
        }

        Integer pkCountry = SecurityUtils.getPkCountry();
        Integer systemType = SecurityUtils.getSystemType();

        CuMemberRetailRegionExt cuMemberRetailRegionExt = cuMemberRetailRegionService.getRegionByMember(mrrExt.getPkMember(), EGrade.S_VIP.getValue(), systemType);
        if (null == cuMemberRetailRegionExt) {
            return AjaxResult.error("还未达到选择收益区域条件");
        }
        CuMemberRetailRegionExt checkMrrExt = new CuMemberRetailRegionExt();
        checkMrrExt.setPkMember(mrrExt.getPkMember());
        checkMrrExt.setEffective(EDealerYesNo.YES.getValue());
        checkMrrExt.setPkCountry(pkCountry);
        checkMrrExt.setSystemType(systemType);
        List<CuMemberRetailRegionExt> list = cuMemberRetailRegionService.memberretailRegList(checkMrrExt);
        if (CollectionUtil.isNotEmpty(list)) {
            return AjaxResult.error(ConfigMsgConstants.MEMBER_RETAIL_REGION_REPEAT);
        }
        // 校验区域是否被占用
        if(ObjectUtil.isEmpty(mrrExt.getCounty())){
            mrrExt.setCounty(-1);
        }
        int cuMemberRetailRegion = cuMemberRetailRegionService.count(Wrappers.<CuMemberRetailRegion>lambdaQuery()
                .eq(CuMemberRetailRegion::getProvince, mrrExt.getProvince())
                .eq(CuMemberRetailRegion::getCity, mrrExt.getCity())
                .eq(CuMemberRetailRegion::getCounty, mrrExt.getCounty())
                .eq(CuMemberRetailRegion::getEffective, EYesNo.YES.getIntValue())
                .eq(CuMemberRetailRegion::getSystemType, systemType)
        );
        if (cuMemberRetailRegion > 0) {
            return AjaxResult.error("当前区域已经被占用");
        }
        mrrExt.setSource(ENoticeWebsiteType.ADMIN.getValue());
        mrrExt.setPkCountry(pkCountry);
        mrrExt.setSystemType(systemType);
        String msg = cuMemberRetailRegionService.setRegion(mrrExt);
        if (msg == null) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error(msg);
        }
    }


    /**
     * @description: 修改会员收益区域
     * @author: zhang jing
     * @date: 2024/12/25 16:18
     * @param: [mrrExt]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_RETAIL_REGION, business = EOperationBusiness.CU_MEMBER_RETAIL_REGION, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody CuMemberRetailRegionExt mrrExt) {
        if (StringUtils.isNull(mrrExt.getPkMember())) {
            return AjaxResult.error(ConfigMsgConstants.MEMBER_NOT_NULL);
        }
        if (StringUtils.isNull(mrrExt.getProvince())) {
            return AjaxResult.error(ConfigMsgConstants.GLO_PROVINCE_NOT_NULL);
        }
        if (StringUtils.isNull(mrrExt.getCity())) {
            return AjaxResult.error(ConfigMsgConstants.GLO_CITY_NOT_NULL);
        }

        // 校验区域是否被占用
        int cuMemberRetailRegion = cuMemberRetailRegionService.count(Wrappers.<CuMemberRetailRegion>lambdaQuery()
                .eq(CuMemberRetailRegion::getProvince, mrrExt.getProvince())
                .eq(CuMemberRetailRegion::getCity, mrrExt.getCity())
                .eq(CuMemberRetailRegion::getCounty, mrrExt.getCounty())
                .eq(CuMemberRetailRegion::getEffective, EYesNo.YES.getIntValue())
                .eq(CuMemberRetailRegion::getSystemType, SecurityUtils.getSystemType())
                .ne(CuMemberRetailRegion::getPkId, mrrExt.getPkId())
        );
        if (cuMemberRetailRegion > 0) {
            return AjaxResult.error("当前区域已经被占用");
        }
        mrrExt.setPkModified(SecurityUtils.getUserId());
        mrrExt.setModifiedTime(new Date());
        return toAjax(cuMemberRetailRegionService.updateById(mrrExt));
    }


    /**
     * @description: 查询会员收益区域
     * @author: zhang jing
     * @date: 2024/12/25 16:18
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_RETAIL_REGION, business = EOperationBusiness.CU_MEMBER_RETAIL_REGION, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Integer pkId) {
        CuMemberRetailRegion withdrawalProcess = cuMemberRetailRegionService.getById(pkId);
        return AjaxResult.success(withdrawalProcess);
    }


    /**
     * @description: 删除会员收益区域
     * @author: zhang jing
     * @date: 2024/12/25 16:18
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.CU_MEMBER_RETAIL_REGION, business = EOperationBusiness.CU_MEMBER_RETAIL_REGION, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        LambdaUpdateWrapper<CuMemberRetailRegion> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CuMemberRetailRegion::getPkId, pkId);
        updateWrapper.set(CuMemberRetailRegion::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(CuMemberRetailRegion::getPkModified, SecurityUtils.getUserId());
        updateWrapper.set(CuMemberRetailRegion::getModifiedTime, new Date());
        return toAjax(cuMemberRetailRegionService.update(updateWrapper));
    }

}
