package com.jsowell.web.controller.pile;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.enums.uniapp.BalanceChangesEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.MemberBasicInfo;
import com.jsowell.pile.domain.MemberPlateNumberRelation;
import com.jsowell.pile.dto.CreateMerchantVipDTO;
import com.jsowell.pile.dto.PlatformTesterDTO;
import com.jsowell.pile.dto.QueryMemberInfoDTO;
import com.jsowell.pile.dto.UniAppQueryMemberBalanceDTO;
import com.jsowell.pile.service.MemberBasicInfoService;
import com.jsowell.pile.service.MemberPlateNumberRelationService;
import com.jsowell.pile.service.MemberTransactionRecordService;
import com.jsowell.pile.util.UserUtils;
import com.jsowell.pile.vo.base.MerchantInfoVO;
import com.jsowell.pile.vo.uniapp.customer.MemberVO;
import com.jsowell.pile.vo.uniapp.customer.MemberWalletLogVO;
import com.jsowell.pile.vo.uniapp.customer.MerchantVipVO;
import com.jsowell.pile.vo.web.MemberTransactionVO;
import com.jsowell.pile.vo.web.PlatformTesterVO;
import com.jsowell.pile.vo.web.UpdateMemberBalanceDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 会员基础信息Controller
 *
 * @author jsowell
 * @date 2022-10-12
 */
@RestController
@RequestMapping("/member/info")
public class MemberBasicInfoController extends BaseController {
    @Autowired
    private MemberBasicInfoService memberBasicInfoService;

    @Autowired
    private MemberTransactionRecordService memberTransactionRecordService;

    @Autowired
    private MemberPlateNumberRelationService memberPlateNumberRelationService;

    /**
     * 查询会员基础信息列表
     */
    @PreAuthorize("@ss.hasPermi('member:info:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody QueryMemberInfoDTO dto) {

        // List<MemberVO> list = memberBasicInfoService.selectMemberList(memberBasicInfo.getMobileNumber(), memberBasicInfo.getNickName());
        List<MemberVO> list = memberBasicInfoService.selectMemberList(dto);
        return getDataTable(list);
    }

    /**
     * 查询运营商VIP列表
     */
    @PostMapping("/queryMerchantVipList")
    public TableDataInfo queryMerchantVipList(@RequestBody QueryMemberInfoDTO dto) {
        List<MerchantVipVO> list = memberBasicInfoService.queryMerchantVipList(dto);
        return getDataTable(list);
    }

    /**
     * 新增运营商VIP
     */
    @Log(title = "新增运营商VIP", businessType = BusinessType.UPDATE)
    @PostMapping ("/createMerchantVip")
    public AjaxResult createMerchantVip(@RequestBody CreateMerchantVipDTO dto) {
        AjaxResult ajaxResult;
        try {
            dto.setFromWeb(Constants.ONE);
            memberBasicInfoService.createMerchantVip(dto);
            ajaxResult = AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("新增运营商VIP error", e);
            ajaxResult = AjaxResult.error(e.getMessage() + ", 新增运营商VIP失败");
        } catch (Exception e) {
            logger.error("新增运营商VIP error", e);
            ajaxResult = AjaxResult.error("发生异常, 新增运营商VIP失败");
        }
        return ajaxResult;
    }

    /**
     * 获取当前会员表中存在的运营商列表
     * http://localhost:8080/member/info/getMerchantListByAuth
     * @return
     */
    @GetMapping("/getMerchantListByAuth")
    public RestApiResponse<?> getMerchantListByAuth() {
        RestApiResponse<?> response = null;
        List<MerchantInfoVO> list = UserUtils.getMerchantInfoVOList();
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        response = new RestApiResponse<>(list);
        return response;
    }

    /**
     * 导出会员基础信息列表
     */
	/*@PreAuthorize("@ss.hasPermi('member:info:export')")
	@Log(title = "会员基础信息", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, MemberBasicInfo memberBasicInfo) {
		List<MemberBasicInfo> list = memberBasicInfoService.selectMemberBasicInfoList(memberBasicInfo);
		ExcelUtil<MemberBasicInfo> util = new ExcelUtil<MemberBasicInfo>(MemberBasicInfo.class);
		util.exportExcel(response, list, "会员基础信息数据");
	}*/

    /**
     * 获取会员基础信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('member:info:query')")
    @GetMapping(value = "/{memberId}")
    public AjaxResult getInfo(@PathVariable("memberId") String memberId) {
        return AjaxResult.success(memberBasicInfoService.queryMemberInfoByMemberId(memberId));
    }

    @PreAuthorize("@ss.hasPermi('member:info:query')")
    @GetMapping(value = "/getMemberPersonPileInfo/{memberId}")
    public AjaxResult getMemberPersonPileInfo(@PathVariable("memberId") String memberId) {
        return AjaxResult.success(memberBasicInfoService.getMemberPersonPileInfo(memberId));
    }

    /**
     * 新增会员基础信息
     */
    // @PreAuthorize("@ss.hasPermi('member:info:add')")
    // @Log(title = "会员基础信息", businessType = BusinessType.INSERT)
    // @PostMapping
    // public AjaxResult add(@RequestBody MemberBasicInfo memberBasicInfo) {
    // 	return toAjax(memberBasicInfoService.insertMemberBasicInfo(memberBasicInfo));
    // }

    /**
     * 修改会员基础信息
     */
    @PreAuthorize("@ss.hasPermi('member:info:edit')")
    @Log(title = "会员基础信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MemberBasicInfo memberBasicInfo) {
        return toAjax(memberBasicInfoService.updateMemberBasicInfo(memberBasicInfo));
    }

    /**
     * 删除会员基础信息
     */
    @PreAuthorize("@ss.hasPermi('member:info:remove')")
    @Log(title = "会员基础信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(memberBasicInfoService.deleteMemberBasicInfoByIds(Lists.newArrayList(ids)));
    }

    /**
     * 充值/扣款余额
     */
    @PreAuthorize("@ss.hasAnyPermi('member:balance:update, member:merchantVip:update')")
    @Log(title = "会员充值/扣款余额", businessType = BusinessType.UPDATE)
    @PutMapping("/updateMemberBalance")
    public AjaxResult updateMemberBalance(@RequestBody UpdateMemberBalanceDTO dto) {
    	logger.info("后管充值/扣款余额 param:{}", dto.toString());
        AjaxResult ajaxResult;
        try {
            // 判断入参
            if (dto == null || StringUtils.isBlank(dto.getMemberId()) || StringUtils.isBlank(dto.getTargetMerchantId())
                || dto.getUpdatePrincipalBalance() == null) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            dto.setFromWeb(Constants.ONE);
            int i = memberBasicInfoService.updateMemberBalance(dto);
            if (i > 0) {
                ajaxResult = AjaxResult.success(ReturnCodeEnum.CODE_SUCCESS.getLabel());
            } else {
                ajaxResult = AjaxResult.error();
            }
        } catch (BusinessException e) {
            ajaxResult = AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            ajaxResult = AjaxResult.error();
        }
        return ajaxResult;
    }

    /**
     * 查询会员钱包流水
     * http://localhost:8080/member/info/queryMemberBalanceChanges
     */
    @PostMapping("/queryMemberBalanceChanges")
    public TableDataInfo queryMemberBalanceChanges(@RequestBody UniAppQueryMemberBalanceDTO dto) {
        String type = dto.getType();
        if (!StringUtils.equals("1", type) && !StringUtils.equals("2", type)) {
            type = "";
        }
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MemberWalletLogVO> list = memberBasicInfoService.getMemberBalanceChanges(dto.getMemberId(), type);
        for (MemberWalletLogVO walletLogVO : list) {
            String subType = walletLogVO.getSubType();
            String subTypeValue = BalanceChangesEnum.getValueByCode(subType);
            if (StringUtils.isNotBlank(subTypeValue)) {
                walletLogVO.setSubType(subTypeValue);
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询会员交易流水
     * IMemberTransactionRecordService
     */
    @PostMapping("/selectMemberTransactionRecordList")
    public TableDataInfo selectMemberTransactionRecordList(@RequestBody UniAppQueryMemberBalanceDTO dto) {
        startPage();
        List<MemberTransactionVO> list = memberTransactionRecordService.selectMemberTransactionRecordList(dto.getMemberId());
        return getDataTable(list);
    }

    /**
     * 修改车牌号信息
     *
     * @param relation
     * @return
     */
    @PreAuthorize("@ss.hasPermi('member:info:edit')")
    @Log(title = "修改车牌号信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePlateNumber")
    public AjaxResult updatePlateNumber(@RequestBody MemberPlateNumberRelation relation) {
        int i = memberPlateNumberRelationService.updatePlateNumber(relation);
        logger.info("后管修改用户：{} 的车牌号：{}", relation.getMemberId(), relation.getLicensePlateNumber());
        return toAjax(i);
    }

    /**
     * 删除会员绑定的车牌号信息
     */
    @PreAuthorize("@ss.hasPermi('member:info:remove')")
    @Log(title = "会员绑定的车牌号信息", businessType = BusinessType.DELETE)
    @PostMapping("/deletePlateNumber")
    public AjaxResult deletePlateNumber(@RequestBody MemberPlateNumberRelation relation) {
        int i = memberPlateNumberRelationService.unbindingPlateNumber(relation.getMemberId(), relation.getLicensePlateNumber());
        logger.info("后管解除绑定用户：{} 的车牌号：{}", relation.getMemberId(), relation.getLicensePlateNumber());
        return toAjax(i);
    }

    /**
     * 修改平台测试员状态
     * http://localhost:8080/member/info/updatePlatformTester
     */
    @PostMapping("/updatePlatformTester")
    public AjaxResult updatePlatformTester(@RequestBody PlatformTesterDTO dto) {
        AjaxResult result;
        try {
            if (StringUtils.isBlank(dto.getMemberId()) || StringUtils.isBlank(dto.getStatus())) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            memberBasicInfoService.updatePlatformTester(dto);
            result = AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("修改平台测试员状态error param:{}", JSON.toJSONString(dto), e);
            result = AjaxResult.error(e.getMessage());
        }
        return result;
    }

    /**
     * 查询平台测试员状态
     * http://localhost:8080/member/info/selectPlatformTesterStatus
     */
    @PostMapping("/selectPlatformTesterStatus")
    public AjaxResult selectPlatformTesterStatus(@RequestBody PlatformTesterDTO dto) {
        AjaxResult result;
        try {
            if (StringUtils.isBlank(dto.getMemberId())) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            PlatformTesterVO platformTesterVO = memberBasicInfoService.selectPlatformTesterStatus(dto.getMemberId());
            result = AjaxResult.success(platformTesterVO);
        } catch (BusinessException e) {
            logger.error("查询平台测试员状态error param:{}", JSON.toJSONString(dto), e);
            result = AjaxResult.error(e.getMessage());
        }
        return result;
    }
}
