package com.jeequan.jeepay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeequan.jeepay.core.model.Capability;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.ProductAppConn;
import com.jeequan.jeepay.db.entity.ProductInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Iterator;
import java.util.List;

@Service
public class MachAppUpdateEXTVService {
    @Autowired
    private MchAppService mchAppService;
    @Autowired
    private ProductInfoService productInfoService;

    public void machAppUpdateEXTV(ProductAppConn productAppConn, int state) {
        //关联时将产品关联的固定功能信息`funcCode`存储到应用信息`extx`中
        //1.取出当前产品的id以及func_code值
        LambdaQueryWrapper<ProductInfo> appInfo = Wrappers.lambdaQuery();
        appInfo.eq(ProductInfo::getProductId, productAppConn.getProductId());
        ProductInfo infoOne = productInfoService.getOne(appInfo);
        String funcCode = infoOne.getFuncCode();
        //2.判断应用库中extv字段是否有相同值，有则进行更新没有则进行新增
        LambdaQueryWrapper<MchAppEntity> mchAppWrapper = Wrappers.lambdaQuery();
        mchAppWrapper.eq(MchAppEntity::getAppId, productAppConn.getAppId());
        MchAppEntity machAppOne = mchAppService.getOne(mchAppWrapper);
        List<Capability> capabilities = machAppOne.getCapabilities();

        if (funcCode == null) {
            return;
        }

        //如果非空则进行遍历匹配，匹配到就删除
        if (!ObjectUtils.isEmpty(capabilities)) {
            Iterator<Capability> iterator = capabilities.iterator();
            while (iterator.hasNext()) {
                Object itemEXTV = iterator.next();
                JSONObject itemEXTVjsonObject = JSON.parseObject(itemEXTV.toString());
                Object machAppExtvKey = itemEXTVjsonObject.get("key");
                //匹配到进行删除
                if (funcCode.equals(machAppExtvKey)) {
                    iterator.remove();
                }
            }
            //判断是否为解除关联，如果是则删除完不用新增
            if (state == 1) {
                //组装新增数据
                Capability capability = Capability.MAP.get(funcCode);
                capabilities.add(capability);
            }
        }

        machAppOne.setCapabilities(capabilities);

        //判断是否为解除关联，如果是则删除完不用新增
        if ("TURNS_PAY".equals(funcCode)) {
            if (state == 0) {
                machAppOne.setPollingBindState(0);
            } else {
                machAppOne.setPollingBindState(1);
            }
        }

        mchAppService.updateById(machAppOne);
    }
}
