package org.dromara.zhishu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.pdd.pop.sdk.common.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.zhishu.domain.SinglePrint;
import org.dromara.zhishu.domain.bo.PrinterBo;
import org.dromara.zhishu.domain.vo.FastMailVo;
import org.dromara.zhishu.domain.vo.PrinterVo;
import org.dromara.zhishu.domain.vo.TLogisticsVo;
import org.dromara.zhishu.service.IFastMailService;
import org.dromara.zhishu.service.IPrinterService;
import org.dromara.zhishu.service.ITLogisticsService;
import org.dromara.zhishu.util.InterfaceUtils;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.zhishu.domain.bo.SinglePrintBo;
import org.dromara.zhishu.service.ISinglePrintService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 单票打印
 *
 * @author yxy
 * @date 2026-03-27
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/singlePrint")
public class SinglePrintController extends BaseController {

    private final ISinglePrintService singlePrintService;
    private final IFastMailService fastMailService;
    private final ITLogisticsService logisticsService;
    private final IPrinterService printerService;

    /**
     * 查询单票打印列表
     */
    @SaCheckPermission("zhishu:singlePrint:list")
    @GetMapping("/list")
    public TableDataInfo<SinglePrint> list(SinglePrintBo bo, PageQuery pageQuery) {
        return singlePrintService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出单票打印列表
     */
    @SaCheckPermission("zhishu:singlePrint:export")
    @Log(title = "单票打印", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SinglePrintBo bo, HttpServletResponse response) {
        List<SinglePrint> list = singlePrintService.queryList(bo);
        ExcelUtil.exportExcel(list, "单票打印", SinglePrint.class, response);
    }

    /**
     * 获取单票打印详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zhishu:singlePrint:query")
    @GetMapping("/{id}")
    public R<SinglePrint> getInfo(@NotNull(message = "主键不能为空")
                                  @PathVariable Long id) {
        return R.ok(singlePrintService.queryById(id));
    }

    /**
     * 根据快递单号获取单票打印信息
     *
     * @param mailNo 快递单号
     */
    @SaCheckPermission("zhishu:singlePrint:query")
    @GetMapping("/getByMailNo/{mailNo}")
    public R<SinglePrint> getInfoByMailNo(@NotNull(message = "快递单号不能为空")
                                          @PathVariable String mailNo) {
        return R.ok(singlePrintService.queryByMailNo(mailNo));
    }


    @PostMapping("/add")
    public R<Map> add(@RequestBody Map dataMap){
        // 运费模板
        String logisticsId = dataMap.get("logisticsData").toString();
        TLogisticsVo logisticsVo = logisticsService.queryById(Long.parseLong(logisticsId));
        dataMap.put("logisticsVo", JsonUtils.toJsonString(logisticsVo));
        // 快递账号
        String fastMailId = dataMap.get("fastMailId").toString();
        FastMailVo fastMailVo = fastMailService.queryById(Long.parseLong(fastMailId));
        dataMap.put("fastMailVo",JsonUtils.toJsonString(fastMailVo));
        // 根据当前时间戳+5位随机数生成 orderSn
        // 获取当前时间戳（毫秒）
        long timestamp = System.currentTimeMillis();
        // 生成5位随机数（10000-99999）
        int randomNum = new Random().nextInt(90000) + 10000;
        String orderSn =  timestamp + String.valueOf(randomNum);
        dataMap.put("orderSn",orderSn);
        String data = InterfaceUtils.postForm(UrlUtil.getOrderServiceUrl(),"/api/singlePrint/addSinglePrint",dataMap);
        Map mapData = JsonUtil.transferToObj(data,Map.class);
        return R.ok(mapData);
    }

    @GetMapping("/printOne")
    public R<Map> printOne(String id){
        String res = InterfaceUtils.getInterface(UrlUtil.getOrderServiceUrl(),"/api/singlePrint/printOne?id="+id);
        Map resMap = JsonUtil.transferToObj(res,Map.class);
        return R.ok(resMap);
    }

    @PostMapping("/pddCloudPrint")
    public R<Void> pddCloudPrint(@RequestBody Map dataMap){
        if(dataMap.get("fastMailId") != null){
            // 不为空则需要手动查询一下快递账号的token
            FastMailVo fastMailVo = fastMailService.queryById(Long.parseLong(dataMap.get("fastMailId").toString()));
            Map remarkMap = JsonUtil.transferToObj(fastMailVo.getRemark(),Map.class);
            dataMap.put("accessToken",remarkMap.get("token").toString());
        }
        String printerId = dataMap.get("printerId").toString();
        PrinterVo printerVo = printerService.queryById(Long.parseLong(printerId));
        dataMap.put("printer",printerVo);
        Map data = new HashMap();
        data.put("data",JsonUtil.transferToJson(dataMap));
        String str = InterfaceUtils.postForm(UrlUtil.getOrderServiceUrl(),"/api/pddCloudPrint/pddCloudPrint",data);
        return R.ok();
    }

    @GetMapping("/cancelBmOrder")
    public R<Void> cancelBmOrder(String id){
        String res = InterfaceUtils.getInterface(UrlUtil.getOrderServiceUrl(),"/api/singlePrint/cancelBmOrder?id="+id);
        Map resMap = JsonUtil.transferToObj(res,Map.class);
        if (resMap.get("code").equals("200")){
            return R.ok(resMap.get("msg").toString());
        }else{
            return R.fail(resMap.get("msg").toString());
        }
    }


    /**
     * 删除单票打印
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zhishu:singlePrint:remove")
    @Log(title = "单票打印", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(singlePrintService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 根据快递单号删除
     *
     * @param mailNo 快递单号
     */
    @SaCheckPermission("zhishu:singlePrint:remove")
    @Log(title = "单票打印", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteByMailNo/{mailNo}")
    public R<Void> removeByMailNo(@NotNull(message = "快递单号不能为空")
                                  @PathVariable String mailNo) {
        return toAjax(singlePrintService.deleteByMailNo(mailNo));
    }
}