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


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.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.PackageOrder;
import com.jeequan.jeepay.db.entity.ProductInfo;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchAppService;
import com.jeequan.jeepay.service.impl.PackageInfoService;
import com.jeequan.jeepay.service.impl.PackageOrderService;
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;

/**
 * 产品列表
 *
 * @author huay
 * @date 2023-11-08 14:50
 */
@RestController
@RequestMapping("/api/product")
public class ProductController extends CommonCtrl {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private PackageOrderService packageOrderService;

    @Autowired
    private MchAppService mchAppService;

    @Autowired
    private PackageInfoService packageInfoService;

    /**
     * 产品列表
     **/
    @RequestMapping(value = "/getProductList", method = RequestMethod.GET)
    @MethodLog(remark = "产品列表")
    public ApiRes getProductList() throws BizException {
        //获取查询条件
        ProductInfo productInfo = getObject(ProductInfo.class);

        Date[] searchDateRange = productInfo.buildQueryDateRange();
        productInfo.setFirstDate(searchDateRange[0]);
        productInfo.setLastDate(searchDateRange[1]);

        Page<ProductInfo> resut = productInfoService.getMgrProductList(getIPage(true),productInfo);
        return ApiRes.page(resut);
    }

    @MethodLog(remark = "新增产品")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ApiRes add() {
        //获取查询条件
        ProductInfo productInfo = getObject(ProductInfo.class);
        //前端组件不稳定，防止出错做一下数据校验
        boolean checkout = packageInfoService.dataCheckout(productInfo.getProductIds(), productInfo.getPackageIds(), productInfo.getPayInterfaceCodes());
        if (!checkout){
            throw new BizException("关联数据格式不正确！");
        }
        //根据规则“API_名称拼音大写_CP_PAY”定义
        if (StringUtils.isEmpty(productInfo.getProductName())){
            throw new BizException("产品名称不能为空！");
        }
        String pinyinString = PinyinUtil.getPinyin(productInfo.getProductName(),""); // 获取拼音字符串，
        String upperCasePinyin = pinyinString.toUpperCase(); // 将拼音转化为大写
        productInfo.setApiCode(ProductInfo.API_CODE_FIRST+upperCasePinyin+ProductInfo.API_CODE_LAST);
        //code唯一判定
        long count = productInfoService.count(ProductInfo.gw().eq(ProductInfo::getApiCode, productInfo.getApiCode()));
        if (count > 0){
            throw new BizException("唯一性code值重复，请尝试更换产品名称！");
        }
        // 当前登录用户信息
        SysUser sysUser = getCurrentUser().getSysUser();
        productInfo.setProductId(DateUtil.format(new Date(), "yyMMdd") + RandomUtil.randomNumbers(6));
        productInfo.setCreatedBy(String.valueOf(sysUser.getSysUserId()));
        //如果收费规则为不收费给默认的免费值
        if(productInfo.getCharge() != null && productInfo.getCharge().equals(ProductInfo.PRODUCT_STATE_ON_CHARGE)){
            JSONArray jsonArray =JSONArray.parseArray(ProductInfo.JSON_STR);
            productInfo.setProductText(jsonArray);
        }
        productInfoService.save(productInfo);

        return ApiRes.ok();
    }

    @MethodLog(remark = "删除产品")
    @RequestMapping(value = "/{productId}", method = RequestMethod.DELETE)
    public ApiRes delete(@PathVariable("productId") String productId) {
        productInfoService.deleteProduct(productId);
        return ApiRes.ok();
    }

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

        ProductInfo info = productInfoService.getDetailById(productInfo.getProductId());
        return ApiRes.ok(info);
    }

    @MethodLog(remark = "更新产品信息")
    @RequestMapping(value = "/{productId}", method = RequestMethod.PUT)
    public ApiRes update(@PathVariable("productId") String productId) {
        //获取查询条件
        ProductInfo productInfo = getObject(ProductInfo.class);
        LambdaUpdateWrapper<ProductInfo> updateWrapper= Wrappers.lambdaUpdate();
        updateWrapper.eq(ProductInfo::getProductId,productInfo.getProductId());
        //前端组件不稳定，防止出错做一下数据校验
        boolean checkout = packageInfoService.dataCheckout(productInfo.getProductIds(), productInfo.getPackageIds(), productInfo.getPayInterfaceCodes());
        if (!checkout){
            throw new BizException("关联数据格式不正确！");
        }
        productInfo.setProductId(productId);//设置主键
        productInfo.setUpdatedAt(new Date());
        //如果收费规则为不收费给默认的免费值
        if(productInfo.getCharge() != null && productInfo.getCharge().equals(ProductInfo.PRODUCT_STATE_ON_CHARGE)){
            JSONArray jsonArray =JSONArray.parseArray(ProductInfo.JSON_STR);
            productInfo.setProductText(jsonArray);
        }
        //如果不需要模板则把之前的清空--前端说不好处理。。
        if(productInfo.getCertification() != null && productInfo.getCertification().equals(ProductInfo.PRODUCT_STATE_ON_CHARGE)){
            updateWrapper.set(ProductInfo::getSpecialCertificationText,null);
        }
        productInfoService.update(productInfo,updateWrapper);
        return ApiRes.ok();
    }

    /**
     * 审核列表
     **/
    @GetMapping("/getProductCheckList")
    @MethodLog(remark = "审核列表")
    public ApiRes getProductCheckList() throws BizException {
        //获取查询条件
        Page<PackageOrder> page=getIPage(true);
        PackageOrder packageOrder = getObject(PackageOrder.class);
        // 时间搜索
        Date[] searchDateRange = packageOrder.buildQueryDateRange();
        packageOrder.setFirstDate(searchDateRange[0]);
        packageOrder.setLastDate(searchDateRange[1]);
        Page<PackageOrder> result = packageOrderService.getList(page, packageOrder);
        return ApiRes.page(result);
    }

    @PostMapping(value = "/checkProduct")
    @MethodLog(remark = "产品审核")
    public ApiRes checkProduct() throws BizException {
        //获取查询条件
        PackageOrder app = getObject(PackageOrder.class);
        app.setUpdatedAt(new Date());
        productInfoService.checkProduct(app);
        return ApiRes.ok();
    }

    @RequestMapping(value = "/getPackageOderById", method = RequestMethod.GET)
    @MethodLog(remark = "审核内容详情")
    public ApiRes getPackageOderById() throws BizException {
        //获取查询条件
        PackageOrder packageOrder = getObject(PackageOrder.class);
        PackageOrder serviceById = packageOrderService.getDetail(packageOrder.getId());
        return ApiRes.ok(serviceById);
    }

    public void selectParams(ProductInfo productInfo, LambdaQueryWrapper<ProductInfo> wrapper) {
        wrapper.like(StringUtils.isNotEmpty(productInfo.getProductName()), ProductInfo::getProductName, productInfo.getProductName());
        wrapper.eq(productInfo.getProductState() != null, ProductInfo::getProductState, productInfo.getProductState());
    }
}
