package org.dromara.zhishu.controller;

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

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.zhishu.domain.bo.PrintTemplateBo;
import org.dromara.zhishu.domain.vo.PrintTemplateVo;
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.idempotent.annotation.RepeatSubmit;
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.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.zhishu.domain.vo.PrinterVo;
import org.dromara.zhishu.domain.bo.PrinterBo;
import org.dromara.zhishu.service.IPrinterService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 打印机设置
 *
 * @author yxy
 * @date 2026-03-06
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/printer")
public class PrinterController extends BaseController {

    private final IPrinterService printerService;

    /**
     * 查询打印机设置列表
     */
    @SaCheckPermission("zhishu:printer:list")
    @GetMapping("/list")
    public TableDataInfo<PrinterVo> list(PrinterBo bo, PageQuery pageQuery) {
        return printerService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询全部打印机设置
     * @param bo
     * @return
     */
    @SaCheckPermission("zhishu:printer:list")
    @GetMapping("/listNoPage")
    public List<PrinterVo> listNoPage(PrinterBo bo){
        return printerService.queryList(bo);
    }


    /**
     * 导出打印机设置列表
     */
    @SaCheckPermission("zhishu:printer:export")
    @Log(title = "打印机设置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(PrinterBo bo, HttpServletResponse response) {
        List<PrinterVo> list = printerService.queryList(bo);
        ExcelUtil.exportExcel(list, "打印机设置", PrinterVo.class, response);
    }

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

    /**
     * 新增打印机设置
     */
    @SaCheckPermission("zhishu:printer:add")
    @Log(title = "打印机设置", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody PrinterBo bo) {
        if (bo.getPrintType().equals("2")){
            // 拼多多云打印机
            Map map = new HashMap();
            map.put("printerId",bo.getPrinter());
            map.put("verifyCode",bo.getCaptcha());
            map.put("accessToken",bo.getAccessToken());
            String res = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/pddCloudPrint/pddCloudPrinterBind",map);
            try{
                Map resMap = JsonUtil.transferToObj(res,Map.class);
                Map cloudPrinterBindresponse = (Map) resMap.get("cloud_printer_bind_response");
                Boolean success = (Boolean) cloudPrinterBindresponse.get("success");
                if (success){
                    Map result = (Map) cloudPrinterBindresponse.get("result");
                    bo.setShareCode(result.get("shareCode").toString());
                }else{
                    return R.fail(cloudPrinterBindresponse.get("errorMsg").toString());
                }
            }catch (Exception e){
                return R.fail(res);
            }
        }

        return toAjax(printerService.insertByBo(bo));
    }

    /**
     * 修改打印机设置
     */
    @SaCheckPermission("zhishu:printer:edit")
    @Log(title = "打印机设置", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody PrinterBo bo) {
        return toAjax(printerService.updateByBo(bo));
    }

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


    /**
     * 新增打印机设置
     */
    @GetMapping("/getCaptcha")
    public R<Map> getCaptcha(PrinterBo bo) {


        List<PrinterVo> voList = printerService.queryList(bo);
        if (voList.size() > 0){
            return R.fail("该 "+bo.getPrinter()+" 打印机已被绑定");
        }

        Map map = new HashMap();
        map.put("printerId",bo.getPrinter());
        map.put("accessToken",bo.getAccessToken());
        String res = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/pddCloudPrint/pddCloudPrintVerifyCode",map);
        try{
            Map resMap = JsonUtil.transferToObj(res,Map.class);
            return R.ok(resMap);
        }catch (Exception e){
            return R.fail(res);
        }
    }
}
