package org.dromara.payment.sys.controller;

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

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.payment.sys.domain.bo.SysSydConfigBo;
import org.dromara.payment.sys.domain.vo.SysSydConfigVo;
import org.dromara.payment.sys.service.ISysSydConfigService;
import org.dromara.settlement.api.RemoteConfigService;
import org.dromara.settlement.api.domain.*;
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.common.mybatis.core.page.TableDataInfo;

/**
 * 服务商配置
 * 前端访问路由地址为:/payment/sydConfig
 *
 * @author LionLi
 * @date 2024-03-26
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/sydConfig")
public class SysSydConfigController extends BaseController {

    private final ISysSydConfigService sysSydConfigService;

    @DubboReference
    private RemoteConfigService configService;

    /**
     * 查询服务商配置列表
     */
    @SaCheckPermission("payment:sydConfig:list")
    @GetMapping("/list")
    public TableDataInfo<SysSydConfigVo> list(SysSydConfigBo bo, PageQuery pageQuery) {
        return sysSydConfigService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出服务商配置列表
     */
    @SaCheckPermission("payment:sydConfig:export")
    @Log(title = "服务商配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysSydConfigBo bo, HttpServletResponse response) {
        List<SysSydConfigVo> list = sysSydConfigService.queryList(bo);
        ExcelUtil.exportExcel(list, "服务商配置", SysSydConfigVo.class, response);
    }

    /**
     * 获取服务商配置详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("payment:sydConfig:query")
    @GetMapping("/{id}")
    public R<SysSydConfigVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(sysSydConfigService.queryById(id));
    }

    /**
     * 新增服务商配置
     */
    @SaCheckPermission("payment:sydConfig:add")
    @Log(title = "服务商配置", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysSydConfigBo bo) {
        return toAjax(sysSydConfigService.insertByBo(bo));
    }

    /**
     * 修改服务商配置
     */
    @SaCheckPermission("payment:sydConfig:edit")
    @Log(title = "服务商配置", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysSydConfigBo bo) {
        return toAjax(sysSydConfigService.updateByBo(bo));
    }

    /**
     * 删除服务商配置
     *
     * @param ids 主键串
     */
    @SaCheckPermission("payment:sydConfig:remove")
    @Log(title = "服务商配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(sysSydConfigService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 获取配置大类下面的组信息
     * @param unit_id 服务商id
     * @param class_alias 固定值（settlement.type）
     * @return
     */
    @GetMapping(value = "/getConfGroupByUnit/{unit_id}/{class_alias}")
    public R<List<UnitConfGroup>> getConfGroupByUnit(@PathVariable(value = "unit_id", required = true) Long unit_id,@PathVariable(value = "class_alias", required = true) String class_alias)
    {
        Result<List<UnitConfGroup>> result = configService.getConfGroupByUnit(unit_id,class_alias);
        if(result.getRtnCode()==ResultCodeEnum.SUCCESS.Code()) {
            return R.ok(result.getRtnData());
        }
        return R.fail("获取配置组失败");
    }

    /**
     * 根据配置组查询配置项明细
     * @param unit_id 服务商id
     * @param conf_group 配置组名称
     * @return
     */
    @GetMapping(value = "/getConfDetailByUnit/{unit_id}/{conf_group}")
    public R<List<UnitConfDetail>> getConfDetailByUnit(@PathVariable(value = "unit_id", required = true) Long unit_id,@PathVariable(value = "conf_group", required = true) String conf_group)
    {
        Result<List<UnitConfDetail>>  result = configService.getConfDetailByUnit(unit_id,conf_group);
        if(result.getRtnCode()== ResultCodeEnum.SUCCESS.Code()) {
            return R.ok(result.getRtnData());
        }
        return R.fail("获取配置项明细失败");
    }


    /**
     * 编辑配置项明细
     * @param map
     * @return
     */
    @PostMapping(value = "/editConfDetail")
    public R<Void> editConfDetail(@RequestBody Map map)
    {
        String confs = map.get("confs").toString();
        try {
            List<UnitConfDetail> lendReco = JSONObject.parseArray(confs, UnitConfDetail.class);
            Result<Boolean>  result = configService.editConfDetail(lendReco);
            if(result.getRtnCode()==ResultCodeEnum.SUCCESS.Code()) {
                if(result.getRtnData()) {
                    return  R.ok("保存成功");
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return R.fail("保存失败");
    }
}
