package com.jeequan.jeepay.mgr.ctrl.payconfig;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.QualificationDefineEntity;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.QualificationDefineService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/api/qualificationDefine")
@RestController
public class QualificationDefineController extends CommonCtrl {

    @Autowired
    private QualificationDefineService qualificationDefineService;

    @PostMapping("/save")
    public ApiRes save() {
        QualificationDefineEntity entity = getObject(QualificationDefineEntity.class);

        //根据规则“API_名称拼音大写_CP_PAY”定义
        if (StringUtils.isEmpty(entity.getName())){
            throw new BizException("资质名称不能为空！");
        }
        String pinyinString = PinyinUtil.getPinyin(entity.getName(),""); // 获取拼音字符串，
        String upperCasePinyin = pinyinString.toUpperCase(); // 将拼音转化为大写
        entity.setCode(QualificationDefineEntity.API_CODE_FIRST+upperCasePinyin+QualificationDefineEntity.API_CODE_LAST);
        //code唯一判定
        QualificationDefineEntity qualificationDefineServiceById = qualificationDefineService.getById(entity.getCode());
        if (qualificationDefineServiceById != null){
            throw new BizException("唯一性code值重复，请尝试更换资质名称！");
        }else {
            boolean save = qualificationDefineService.save(entity);
            return ApiRes.ok(save);
        }
    }

    @GetMapping("/page")
    public ApiRes page() {
        Page<QualificationDefineEntity> iPage = getIPage(false);
        QualificationDefineEntity condition = getObject(QualificationDefineEntity.class);
        qualificationDefineService.lambdaQuery().setEntity(condition).page(iPage);

        return ApiRes.ok(iPage);
    }

    @GetMapping("/{code}")
    public ApiRes one(@PathVariable String code) {
        QualificationDefineEntity one = qualificationDefineService.lambdaQuery().eq(QualificationDefineEntity::getCode, code).one();
        return ApiRes.ok(one);
    }

    @DeleteMapping("/{code}")
    public ApiRes del(@PathVariable String code) {
        qualificationDefineService.removeById(code);
        return ApiRes.ok();
    }

    /**
     * 编辑
     */
    @PutMapping("/update")
    public ApiRes update() {
        String code = getValStringRequired("code");
        QualificationDefineEntity entity = getObject(QualificationDefineEntity.class);
        boolean update = qualificationDefineService.updateById(entity);
        return ApiRes.ok(update);
    }
}
