package org.springblade.modules.api.controller;

import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.enums.AuditStatusEnum;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.api.request.AddChildAccountRequest;
import org.springblade.modules.api.request.AlertChildAccountRequest;
import org.springblade.modules.api.request.TimeRangeReq;
import org.springblade.modules.api.response.MerchantPieRes;
import org.springblade.modules.api.response.TurnoverRes;
import org.springblade.modules.api.utils.TimeRangeReqUtils;
import org.springblade.modules.api.vo.MerchantIncomeVO;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserMerchant;
import org.springblade.modules.system.service.IUserMerchantService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.UserMerchantVO;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * Author pangqijun
 * Date 2024/7/16
 * Description
 */
@RestController
@AllArgsConstructor
@RequestMapping(CommonConstant.API_URL)
@Api(value = "商家端", tags = "商家端用户接口")
public class ApiMerchantUserController {

    private final IUserMerchantService iUserMerchantService;
    private final IUserService iUserService;

    @GetMapping("/merchant/get")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取商家用户信息")
    public R<UserMerchantVO> getMerchantUserInfo() {
        User user = iUserService.getById(AuthUtil.getUserId());
        Assert.notNull(user, "未查询到用户信息");
        UserMerchantVO vo = iUserMerchantService.getByUserId(user.getId());
        vo.setAvatar(user.getAvatar());
        vo.setName(user.getName());
        vo.setRealName(vo.getRealName());
        vo.setPhone(user.getPhone());
        return R.data(vo);
    }

    @PostMapping("/merchant/update")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "更新用户信息")
    public R<Void> updateUserInfo(@RequestBody UserMerchantVO userMerchantVO) {
        User user = iUserService.getById(AuthUtil.getUserId());
        Assert.notNull(user, "未查询到用户信息");
//        UserMerchantVO vo = iUserMerchantService.getByUserId(AuthUtil.getUserId());
//        Assert.notNull(user, "未查询到商户信息");
        user.setAvatar(userMerchantVO.getAvatar());
        return R.status(iUserService.updateById(user));
    }

    @PostMapping("/addChildAccount")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "添加子账号", notes = "传入userMerchant")
    public R<Void> addChildAccount(@Valid @RequestBody AddChildAccountRequest request) {
        if (!request.getPassword().equals(request.getRePassword())) {
            return R.fail("密码不一致");
        }
        User query1 = iUserService.getOne(Wrappers.<User>query().lambda().eq(User::getAccount, request.getPhone()));
        if (query1 != null) {
            return R.fail("手机号已注册！");
        }
        String tenantId = WebUtil.getRequest().getHeader(TokenUtil.TENANT_HEADER_KEY);
        User user = new User();
        user.setAccount(request.getPhone());
        user.setPhone(request.getPhone());
        user.setAvatar(request.getCover());
        user.setTenantId(tenantId);
        user.setUserType(UserEnum.MERCHANT.getCategory());
        user.setPassword(DigestUtil.encrypt(request.getPassword()));
        user.setName(request.getNickname() == null ? DesensitizedUtil.mobilePhone(request.getPhone()) : request.getNickname());
        user.setRealName(request.getRealName());
        iUserService.save(user);

        UserMerchant userMerchant = new UserMerchant();
        userMerchant.setUserId(user.getId());
        userMerchant.setParentId(AuthUtil.getUserId());
        userMerchant.setAuditStatus(AuditStatusEnum.PASS.getValue());
        userMerchant.setAuthShop(request.getAuthShopIds());
        iUserMerchantService.save(userMerchant);

        return R.success("添加成功");
    }

    @Transactional
    @PostMapping("/updateChildAccount")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "修改子账号", notes = "alertChildAccountRequest")
    public R<Void> deleteChildAccount(@Valid @RequestBody AlertChildAccountRequest request) {
        UserMerchantVO userMerchant = iUserMerchantService.getByUserId(request.getId());
        userMerchant.setParentId(AuthUtil.getUserId());
        userMerchant.setAuditStatus(AuditStatusEnum.PASS.getValue());
        userMerchant.setAuthShop(request.getAuthShopIds());
        iUserMerchantService.updateById(userMerchant);
        return R.success("修改成功");
    }

    @Transactional
    @PostMapping("/deleteChildAccount")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "删除子账号", notes = "传入ids")
    public R<Void> deleteChildAccount(@ApiParam(value = "主键集合", required = true) @RequestParam Long childAccountId) {
        UserMerchant child = iUserMerchantService.getById(childAccountId);
        Assert.notNull(child, "未查询到子账号信息");
        iUserMerchantService.removeById(childAccountId);
        return R.status(iUserService.removeById(childAccountId));
    }

    /**
     * 自定义分页 商家用户表
     */
    @GetMapping("/childAccount/list")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "子账号列表", notes = "传入userMerchant")
    public R<IPage<UserMerchantVO>> page(UserMerchantVO userMerchant, Query query) {
        userMerchant.setParentId(AuthUtil.getUserId());
        IPage<UserMerchantVO> pages = iUserMerchantService.selectUserMerchantPage(Condition.getPage(query), userMerchant);
        return R.data(pages);
    }

    /**
     * 可提现金额
     */
    @GetMapping("/getCash")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "可提现金额", notes = "可提现金额")
    public R cash() {
      return R.data( iUserMerchantService.getCash());
    }

    /**
     * 我的钱包收益记录
     */
    @GetMapping("/pageIncome")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "我的钱包收益记录-分页", notes = "我的钱包收益记录-分页")
    public R<IPage<MerchantIncomeVO>> pageIncome(Query query) {
        IPage<MerchantIncomeVO> pages = iUserMerchantService.pageIncome(Condition.getPage(query), AuthUtil.getUserId());
        return R.data(pages);
    }

    /**
     * 商家端-首页
     */
    @PostMapping("/pie")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "商家端-首页-饼图", notes = "商家端-首页-饼图")
    public R<List<MerchantPieRes>> pie(@Valid @RequestBody TimeRangeReq timeRangeReq) {

        TimeRangeReqUtils.setTimeRangeReq(timeRangeReq);

        /*
        * 数据格式
        [
        { value: 0, name: '展现', itemStyle: { color: '#1890ff' } },
        { value: 0, name: '点击', itemStyle: { color: '#91cb74' } },
        { value: 0, name: '订单', itemStyle: { color: '#fac858' } },
        { value: 0, name: '付款', itemStyle: { color: '#ee6666' } },
        ]
        * */

        List<MerchantPieRes> result = new ArrayList<>();

        MerchantPieRes reveal = new MerchantPieRes();//展现
        reveal.setValue("200");
        reveal.setName("展现");
        Map<String, String> revealColorMap = new HashMap<>();
        revealColorMap.put("color", "#1890ff");
        reveal.setItemStyle(revealColorMap);
        result.add(reveal);

        MerchantPieRes order = new MerchantPieRes();//订单
        order.setValue("300");
        order.setName("点击");
        Map<String, String> orderColorMap = new HashMap<>();
        orderColorMap.put("color", "#91cb74");
        order.setItemStyle(orderColorMap);
        result.add(order);

        MerchantPieRes click = new MerchantPieRes();//订单
        click.setValue("100");
        click.setName("订单");
        Map<String, String> clickColorMap = new HashMap<>();
        clickColorMap.put("color", "#fac858");
        click.setItemStyle(clickColorMap);
        result.add(click);

        MerchantPieRes pay = new MerchantPieRes();//付款
        pay.setValue("100");
        pay.setName("订单");
        Map<String, String> payColorMap = new HashMap<>();
        payColorMap.put("color", "#ee6666");
        pay.setItemStyle(payColorMap);
        result.add(pay);

        return R.data(result);
    }

    /**
     * 商家端-首页-设备状态
     */
    @GetMapping("/survey")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "商家端-首页-设备状态", notes = "商家端-首页-设备状态")
    public R<Map<String, String>> survey() {
        //key为名称，value为数量
        Map<String, String> result = new HashMap<>();
        result.put("设备数量", "60");
        result.put("门店数量", "6");
        result.put("故障设备", "10");
        result.put("在线设备", "40");
        result.put("子账号", "6");
        result.put("订单量", "600");
        return R.data(result);
    }

    /**
     * 商家端-首页-营业额和结算额
     */
    @PostMapping("/turnover")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "商家端-首页-营业额和结算额", notes = "商家端-首页-营业额和结算额")
    public R<TurnoverRes> turnover(@Valid @RequestBody TimeRangeReq timeRangeReq) {
        TimeRangeReqUtils.setTimeRangeReq(timeRangeReq);
        //key为名称，value为数量
        TurnoverRes result = new TurnoverRes();
        result.setTurnover("6000.00");
        result.setClearing("5873.16");
        return R.data(result);
    }

}
