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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.PackageInfo;
import com.jeequan.jeepay.db.entity.PackageOrder;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.PackageInfoService;
import com.jeequan.jeepay.service.impl.PackageProductService;
import com.jeequan.jeepay.service.impl.ProductAppService;
import com.jeequan.jeepay.service.impl.ProductInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/packageInfo")
public class PackageInfoController extends CommonCtrl {

    @Autowired private PackageInfoService packageInfoService;

    @Autowired private PackageProductService packageProductService;

    @Autowired private ProductInfoService productInfoService;

    @Autowired private ProductAppService productAppService;


    @GetMapping
    @MethodLog(remark = "查询方案")
    public ApiRes list(){
        IPage<PackageInfo> page=getIPage(true);
        PackageInfo packageInfo = getObject(PackageInfo.class);
        //提供id和名字检索

        LambdaQueryWrapper<PackageInfo> queryWrapper= Wrappers.lambdaQuery();
        IPage<PackageInfo> result = packageInfoService.getList(page, queryWrapper,packageInfo);
        return ApiRes.ok(result);
    }

    @RequestMapping(value = "/getDetailById", method = RequestMethod.GET)
    @MethodLog(remark = "回显方案详情")
    public ApiRes getDetailById() throws BizException {
        //获取查询条件
        PackageInfo packageInfo = getObject(PackageInfo.class);

        PackageInfo info  = packageInfoService.getDetailById(packageInfo.getPackageId());
        return ApiRes.ok(info);
    }

    @MethodLog(remark = "删除方案")
    @PostMapping(value="/deletePackageInfo")
    public ApiRes deletePackageInfo() {
        PackageInfo packageInfo = getObject(PackageInfo.class);
        if (StringUtils.isNotEmpty(packageInfo.getPackageId())){
            packageInfo.setPackageState(2);
            packageInfo.setUpdatedAt(new Date());
            packageInfoService.updateById(packageInfo);
        }else {
            return ApiRes.customFail("所传方案id不能为空！");
        }
        return ApiRes.ok();
    }


    /*新增或修改方案*/
    @PostMapping("/saveOrUpdate")
    @MethodLog(remark = "新增或修改方案")
    public ApiRes saveOrUpdate() {
        PackageInfo packageInfo = getObject(PackageInfo.class);
        String sysUser = getCurrentUser().getSysUser().getRealname();
        packageInfo.setCreatedBy(sysUser);
        //前端组件不稳定，防止出错做一下数据校验
        boolean checkout = packageInfoService.dataCheckout(packageInfo.getProductIds(), packageInfo.getPackageIds(), packageInfo.getPayInterfaceCodes());
        if (!checkout){
            throw new BizException("关联数据格式不正确！");
        }
        //如果收费规则为不收费给默认的免费值
        if(packageInfo.getCharge() != null && packageInfo.getCharge().equals(PackageInfo.PACKAGE_STATE_ON_CHARGE)){
            JSONArray jsonArray =JSONArray.parseArray(PackageInfo.JSON_STR);
            packageInfo.setPackageText(jsonArray);
        }
        //方案表进行新增或者修改
        if (StringUtils.isNotEmpty(packageInfo.getPackageId())){
            //传入id方案表修改
            LambdaUpdateWrapper<PackageInfo> updateWrapper= Wrappers.lambdaUpdate();
            updateWrapper.eq(PackageInfo::getPackageId,packageInfo.getPackageId());
            //如果不需要模板则把之前的清空--前端说不好处理。。
            if(packageInfo.getCertification() != null && packageInfo.getCertification().equals(PackageInfo.PACKAGE_STATE_ON_CHARGE)){
                updateWrapper.set(PackageInfo::getSpecialCertificationText,null);
            }
            boolean update = packageInfoService.update(packageInfo,updateWrapper);
            if (!update) {
                return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
            }
        }else {
            //不传id方案表新增
            packageInfo.setPackageId(DateUtil.format(new Date(), "yyMMdd")+ RandomUtil.randomNumbers(6));
            //根据规则“API_名称拼音大写_FA_PAY”定义
            if (StringUtils.isEmpty(packageInfo.getName())){
                throw new BizException("方案名称不能为空！");
            }
            String pinyinString = PinyinUtil.getPinyin(packageInfo.getName(),""); // 获取拼音字符串，
            String upperCasePinyin = pinyinString.toUpperCase(); // 将拼音转化为大写
            packageInfo.setApiCode(PackageInfo.API_CODE_FIRST+upperCasePinyin+PackageInfo.API_CODE_LAST);
            //code唯一判定
            long count = packageInfoService.count(PackageInfo.gw().eq(PackageInfo::getApiCode, packageInfo.getApiCode()));
            if (count > 0){
                throw new BizException("唯一性code值重复，请尝试更换方案名称！");
            }
            boolean save = packageInfoService.save(packageInfo);
            if (!save) {
                return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
            }
        }
        return ApiRes.ok();
    }


    @RequestMapping(value = "/getPackageCheckList", method = RequestMethod.GET)
    @MethodLog(remark = "方案审核列表")
    public ApiRes getPackageCheckList() throws BizException {
        //获取查询条件
        PackageInfo packageInfo = getObject(PackageInfo.class);
        Page<PackageOrder> page=getIPage(true);
        IPage<PackageInfo> pages = packageInfoService.getPackageCheckList(page,packageInfo.getName(),packageInfo.getPackageState(),packageInfo.getMchName());
        return ApiRes.page(pages);
    }

}
