package com.gxwebsoft.shop.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.entity.ShopDealerUser;
import com.gxwebsoft.shop.service.ShopDealerApplyService;
import com.gxwebsoft.shop.entity.ShopDealerApply;
import com.gxwebsoft.shop.param.ShopDealerApplyParam;
import com.gxwebsoft.shop.param.ShopDealerApplyImportParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.service.ShopDealerUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 分销商申请记录表控制器
 *
 * @author 科技小王子
 * @since 2025-08-11 23:50:19
 */
@Tag(name = "分销商申请记录表管理")
@RestController
@RequestMapping("/api/shop/shop-dealer-apply")
public class ShopDealerApplyController extends BaseController {
    @Resource
    private ShopDealerApplyService shopDealerApplyService;
    @Resource
    private ShopDealerUserService shopDealerUserService;

    @PreAuthorize("hasAuthority('shop:shopDealerApply:list')")
    @Operation(summary = "分页查询分销商申请记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<ShopDealerApply>> page(ShopDealerApplyParam param) {
        // 使用关联查询
        return success(shopDealerApplyService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:list')")
    @Operation(summary = "查询全部分销商申请记录表")
    @GetMapping()
    public ApiResult<List<ShopDealerApply>> list(ShopDealerApplyParam param) {
        // 使用关联查询
        return success(shopDealerApplyService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:list')")
    @Operation(summary = "根据id查询分销商申请记录表")
    @GetMapping("/{id}")
    public ApiResult<ShopDealerApply> getById(@PathVariable("id") Integer id) {
      // 使用关联查询
      return success(shopDealerApplyService.getById(id));
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:list')")
    @Operation(summary = "根据userId查询分销商申请记录表")
    @GetMapping("/getByUserId/{id}")
    public ApiResult<ShopDealerApply> getByUserId(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(shopDealerApplyService.getByUserIdRel(id));
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:save')")
    @OperationLog
    @Operation(summary = "添加分销商申请记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ShopDealerApply shopDealerApply) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          shopDealerApply.setApplyTime(LocalDateTime.now());
          if(shopDealerApply.getUserId() == null) {
            shopDealerApply.setUserId(loginUser.getUserId());
          }
        }
        if (shopDealerApply.getRefereeId() != null) {
          if(shopDealerUserService.getByIdRel(shopDealerApply.getRefereeId()) == null){
            return fail("推荐人不存在");
          }
        }

        if (shopDealerApplyService.save(shopDealerApply)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:update')")
    @OperationLog
    @Operation(summary = "修改分销商申请记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ShopDealerApply shopDealerApply) {
        shopDealerApply.setAuditTime(null);
        if(shopDealerApply.getRate() != null){
          final ShopDealerUser dealerUser = new ShopDealerUser();
          dealerUser.setRate(shopDealerApply.getRate());
          shopDealerUserService.update(dealerUser, new LambdaQueryWrapper<ShopDealerUser>().eq(ShopDealerUser::getUserId, shopDealerApply.getUserId()));
        }
        if (shopDealerApplyService.updateById(shopDealerApply)) {
            if (shopDealerApply.getApplyStatus().equals(20)) {
              LocalDateTime now = LocalDateTime.now();
              shopDealerApply.setAuditTime(now);
              shopDealerApplyService.updateById(shopDealerApply);
              // 同步添加经销商
              if (shopDealerUserService.count(new LambdaQueryWrapper<ShopDealerUser>().eq(ShopDealerUser::getUserId, shopDealerApply.getUserId())) == 0) {
                final ShopDealerUser dealerUser = new ShopDealerUser();
                dealerUser.setUserId(shopDealerApply.getUserId());
                dealerUser.setRealName(shopDealerApply.getRealName());
                dealerUser.setMobile(shopDealerApply.getMobile());
                dealerUser.setRefereeId(shopDealerApply.getRefereeId());
                shopDealerUserService.save(dealerUser);
              }
            }
            return success("保存成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:remove')")
    @OperationLog
    @Operation(summary = "删除分销商申请记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (shopDealerApplyService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:save')")
    @OperationLog
    @Operation(summary = "批量添加分销商申请记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<ShopDealerApply> list) {
        if (shopDealerApplyService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:update')")
    @OperationLog
    @Operation(summary = "批量修改分销商申请记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ShopDealerApply> batchParam) {
        if (batchParam.update(shopDealerApplyService, "apply_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopDealerApply:remove')")
    @OperationLog
    @Operation(summary = "批量删除分销商申请记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (shopDealerApplyService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    /**
     * excel批量导入分销商申请记录
     * Excel表头格式：类型、用户ID、姓名、分销商名称、分销商编码、手机号、合同金额、详细地址、社区、楼栋号、单元号、房号、推荐人用户ID、申请方式、审核状态、合同时间、驳回原因、商城ID
     */
    @PreAuthorize("hasAuthority('shop:shopDealerApply:save')")
    @Transactional(rollbackFor = {Exception.class})
    @Operation(summary = "批量导入分销商申请记录")
    @PostMapping("/import")
    public ApiResult<List<String>> importBatch(MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 设置标题行，跳过第一行表头
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        List<String> errorMessages = new ArrayList<>();
        int successCount = 0;

        try {
            List<ShopDealerApplyImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(), ShopDealerApplyImportParam.class, importParams);

            // 获取当前登录用户
            User loginUser = getLoginUser();
            Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;

            for (int i = 0; i < list.size(); i++) {
                ShopDealerApplyImportParam param = list.get(i);
                try {
                    // 手动转换对象，避免JSON序列化问题
                    ShopDealerApply item = convertImportParamToEntity(param);

                    // 设置必填字段的默认值
                    if (item.getUserId() == null && currentUserId != null) {
                        item.setUserId(currentUserId);
                    }
                    if (item.getApplyStatus() == null) {
                        item.setApplyStatus(10); // 默认状态为待审核
                    }
                    if (item.getApplyType() == null) {
                        item.setApplyType(10); // 默认需要后台审核
                    }
                    if (item.getType() == null) {
                        item.setType(0); // 默认类型为经销商
                    }

                    // 设置申请时间
                    item.setApplyTime(LocalDateTime.now());

                    // 验证必填字段
                    if (item.getRealName() == null || item.getRealName().trim().isEmpty()) {
                        errorMessages.add("第" + (i + 1) + "行：姓名不能为空");
                        continue;
                    }
                   if (item.getDealerName() == null || item.getDealerName().trim().isEmpty()) {
                      errorMessages.add("第" + (i + 1) + "行：企业名称不能为空");
                      continue;
                    }
                    if (item.getMobile() == null || item.getMobile().trim().isEmpty()) {
                        errorMessages.add("第" + (i + 1) + "行：手机号不能为空");
                        continue;
                    }

                    // 验证推荐人是否存在
                    if (item.getRefereeId() != null) {
                        if (shopDealerUserService.getByIdRel(item.getRefereeId()) == null) {
                            errorMessages.add("第" + (i + 1) + "行：推荐人不存在");
                            continue;
                        }
                    }

                    // 保存数据
                    if (shopDealerApplyService.save(item)) {
                        successCount++;
                    } else {
                        errorMessages.add("第" + (i + 1) + "行：保存失败");
                    }

                } catch (Exception e) {
                    errorMessages.add("第" + (i + 1) + "行：" + e.getMessage());
                    System.err.println("导入第" + (i + 1) + "行数据失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }

            // 返回结果
            if (errorMessages.isEmpty()) {
                return success("成功导入" + successCount + "条数据", null);
            } else {
                return success("导入完成，成功" + successCount + "条，失败" + errorMessages.size() + "条", errorMessages);
            }

        } catch (Exception e) {
            System.err.println("批量导入分销商申请记录失败: " + e.getMessage());
            e.printStackTrace();
            return fail("导入失败：" + e.getMessage(), null);
        }
    }

    /**
     * 下载分销商申请记录导入模板
     */
    @Operation(summary = "下载分销商申请记录导入模板")
    @GetMapping("/import/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 创建空的导入参数列表作为模板
        List<ShopDealerApplyImportParam> templateList = new ArrayList<>();

        // 添加一行示例数据
        ShopDealerApplyImportParam example = new ShopDealerApplyImportParam();
        example.setType(0);
        example.setRealName("宗馥莉");
        example.setDealerName("娃哈哈有限公司");
        example.setDealerCode("WaHaHa");
        example.setMobile("13800138000");
        example.setApplyType(10);
        example.setApplyStatus(10);
        example.setContractTime("2025-09-05 10:00:00");
        example.setCommunity("xx社区");
        example.setBuildingNumber("1");
        example.setUnitNumber("2");
        example.setRoomNumber("302");
        templateList.add(example);

        // 设置导出参数
        ExportParams exportParams = new ExportParams("分销商申请记录导入模板", "分销商申请记录");

        // 生成Excel
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ShopDealerApplyImportParam.class, templateList);

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=shop_dealer_apply_import_template.xlsx");

        // 输出到响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    /**
     * 将ShopDealerApplyImportParam转换为ShopDealerApply实体
     */
    private ShopDealerApply convertImportParamToEntity(ShopDealerApplyImportParam param) {
        ShopDealerApply entity = new ShopDealerApply();

        // 基本字段转换
        entity.setType(param.getType());
        entity.setUserId(param.getUserId());
        entity.setRealName(param.getRealName());
        entity.setDealerName(param.getDealerName());
        entity.setDealerCode(param.getDealerCode());
        entity.setMobile(param.getMobile());
        entity.setMoney(param.getMoney());
        entity.setAddress(param.getAddress());
        entity.setCommunity(param.getCommunity());
        entity.setBuildingNumber(param.getBuildingNumber());
        entity.setUnitNumber(param.getUnitNumber());
        entity.setRoomNumber(param.getRoomNumber());
        entity.setRefereeId(param.getRefereeId());
        entity.setApplyType(param.getApplyType());
        entity.setApplyStatus(param.getApplyStatus());
        entity.setRejectReason(param.getRejectReason());
        entity.setTenantId(param.getTenantId());

        // 处理合同时间
        if (param.getContractTime() != null && !param.getContractTime().trim().isEmpty()) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                entity.setContractTime(LocalDateTime.parse(param.getContractTime(), formatter));
            } catch (Exception e) {
                System.err.println("合同时间格式错误: " + param.getContractTime());
            }
        }

        return entity;
    }

}
