package cn.newfeifan.mall.sale.controller.admin.merchant;

import cn.newfeifan.mall.module.system.service.user.AdminUserService;
import cn.newfeifan.mall.module.trade.service.order.TradeOrderQueryService;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantPageReqVO;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantRespVO;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantSaveReqVO;
import cn.newfeifan.mall.sale.dal.dataobject.merchant.MerchantDO;
import cn.newfeifan.mall.sale.service.merchant.MerchantService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.newfeifan.mall.framework.common.pojo.PageParam;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.pojo.CommonResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import static cn.newfeifan.mall.framework.common.pojo.CommonResult.success;

import cn.newfeifan.mall.framework.excel.core.util.ExcelUtils;

import cn.newfeifan.mall.framework.operatelog.core.annotations.OperateLog;

import static cn.newfeifan.mall.framework.operatelog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 商户")
@RestController
@RequestMapping("/sale/merchant")
@Validated
public class MerchantController {

    @Resource
    private AdminUserService adminUserService;
    @Resource
    private MerchantService merchantService;

    @Resource
    private TradeOrderQueryService tradeOrderQueryService;


    @PostMapping("/create")
    @Operation(summary = "创建商户")
    @PreAuthorize("@ss.hasPermission('sale:merchant:create')")
    public CommonResult<HashMap<String, Long>> createMerchant(@Valid @RequestBody MerchantSaveReqVO createReqVO) {
        return success(merchantService.createMerchant(createReqVO, null));
    }

    /*@PostMapping("/createByMobile")
    @Operation(summary = "通过手机号创建一个用户")
    @PreAuthorize("@ss.hasPermission('sale:merchant:create')")
    public CommonResult<String> createByMobile(@RequestBody MerchantSaveReqByMobileVO createReqVO) {
        adminUserService.createUserByMobile(merchant.getId(), createReqVO.getContactNumber(), createReqVO.getContact());
        return success("创建成功");
    }*/


    @PutMapping("/update")
    @Operation(summary = "更新商户")
    @PreAuthorize("@ss.hasPermission('sale:merchant:update')")
    public CommonResult<Boolean> updateMerchant(@Valid @RequestBody MerchantSaveReqVO updateReqVO) {
        /*LoginUser loginUser =  SecurityFrameworkUtils.getLoginUser();
        if (loginUser==null){
            return error(UNAUTHORIZED);
        }
        // 添加校验， 如果是平台用户的话， 就不能修改商户信息
        if (ObjectUtil.notEqual(loginUser.getUserType(), UserTypeEnum.ADMIN.getValue())) {
            return error(FORBIDDEN);
        }*/
        merchantService.updateMerchant(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除商户")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('sale:merchant:delete')")
    public CommonResult<Boolean> deleteMerchant(@RequestParam("id") Long id) {
        merchantService.deleteMerchant(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得商户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<MerchantRespVO> getMerchant(@RequestParam("id") Long id) {
        MerchantDO merchant = merchantService.getMerchant(id);
        MerchantRespVO bean = BeanUtils.toBean(merchant, MerchantRespVO.class);
        if(merchant != null && merchant.getOtherCertificate() != null){
            // Step 1: 去除字符串中的方括号和空格
            String input = merchant.getOtherCertificate().replaceAll("[\\[\\]\\s]", "");

            // Step 2: 按逗号分割字符串
            String[] parts = input.split(",");

            List<String> fileList = new ArrayList<>();

            // Step 3: 去除每个部分可能的空格并添加到列表中
            for (String part : parts) {
                fileList.add(part.trim());
            }

            bean.setOtherCertificate(fileList);
        }
        return success(bean);
    }

    @GetMapping("/getMerchantCount")
    @Operation(summary = "获得商户数量")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<Integer> getMerchantCount(@Valid MerchantPageReqVO pageReqVO) {
        return success(merchantService.getMerchantPage(pageReqVO).getList().size());
    }


    @GetMapping("/page")
    @Operation(summary = "获得商户分页")
    @PreAuthorize("@ss.hasPermission('sale:merchant:query')")
    public CommonResult<PageResult<MerchantRespVO>> getMerchantPage(@Valid MerchantPageReqVO pageReqVO) {
        PageResult<MerchantDO> pageResult = merchantService.getMerchantPage(pageReqVO);
        PageResult<MerchantRespVO> merchantRespVOPageResult = BeanUtils.toBean(pageResult, MerchantRespVO.class);

        Map<Long, MerchantRespVO> map = merchantRespVOPageResult.getList().stream().collect(Collectors.toMap(MerchantRespVO::getId, k -> k));
        List<MerchantRespVO> merchantRespVOS = merchantService.salesVolume(map);
        merchantRespVOPageResult.setList(merchantRespVOS);
        return success(merchantRespVOPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出商户 Excel")
    @PreAuthorize("@ss.hasPermission('sale:merchant:export')")
    @OperateLog(type = EXPORT)
    public void exportMerchantExcel(@Valid MerchantPageReqVO pageReqVO,
                                    HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MerchantDO> list = merchantService.getMerchantPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "商户.xls", "数据", MerchantRespVO.class,
                BeanUtils.toBean(list, MerchantRespVO.class));
    }

}