package com.ruoyi.web.controller.jarvis;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.erp.request.ExpressCompaniesQueryRequest;
import com.ruoyi.erp.request.IERPAccount;
import com.ruoyi.jarvis.domain.ErpOpenConfig;
import com.ruoyi.jarvis.service.IErpOpenConfigService;
import com.ruoyi.jarvis.service.erp.ErpAccountResolver;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/jarvis/erpOpenConfig")
public class ErpOpenConfigController extends BaseController {

    @Resource
    private IErpOpenConfigService erpOpenConfigService;

    @Resource
    private ErpAccountResolver erpAccountResolver;

    /**
     * 查询闲管家快递公司列表（POST body 固定为 {}，与签名规则一致）
     *
     * @param appKey 与配置中心一致；不传则按 {@link ErpAccountResolver#resolve(String)} 默认账号
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpOpenConfig:list')")
    @GetMapping("/expressCompanies")
    public AjaxResult expressCompanies(@RequestParam(required = false) String appKey) {
        try {
            IERPAccount cred = erpAccountResolver.resolve(appKey);
            ExpressCompaniesQueryRequest req = new ExpressCompaniesQueryRequest(cred);
            String resp = req.getResponseBody();
            JSONObject o = JSONObject.parseObject(resp);
            if (o == null) {
                return AjaxResult.error("开放平台返回空");
            }
            if (o.getIntValue("code") != 0) {
                return AjaxResult.error(o.getString("msg") != null ? o.getString("msg") : resp);
            }
            return AjaxResult.success(o.get("data"));
        } catch (Exception e) {
            return AjaxResult.error("调用快递公司接口失败: " + e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('jarvis:erpOpenConfig:list')")
    @GetMapping("/list")
    public TableDataInfo list(ErpOpenConfig query) {
        startPage();
        List<ErpOpenConfig> list = erpOpenConfigService.selectList(query);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('jarvis:erpOpenConfig:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return AjaxResult.success(erpOpenConfigService.selectById(id));
    }

    @PreAuthorize("@ss.hasPermi('jarvis:erpOpenConfig:add')")
    @Log(title = "闲管家应用配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ErpOpenConfig row) {
        return toAjax(erpOpenConfigService.insert(row));
    }

    @PreAuthorize("@ss.hasPermi('jarvis:erpOpenConfig:edit')")
    @Log(title = "闲管家应用配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ErpOpenConfig row) {
        return toAjax(erpOpenConfigService.update(row));
    }

    @PreAuthorize("@ss.hasPermi('jarvis:erpOpenConfig:remove')")
    @Log(title = "闲管家应用配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        int n = 0;
        if (ids != null) {
            for (Long id : ids) {
                n += erpOpenConfigService.deleteById(id);
            }
        }
        return toAjax(n);
    }
}
