package com.ytpm.middle.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.agent.model.YtPlatformUserApp;
import com.ytpm.app.enums.AppTypeEnums;
import com.ytpm.app.model.YtAppDefaultConfig;
import com.ytpm.app.param.AppConfigUpdateParam;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.middle.dao.AppMapper;
import com.ytpm.middle.dao.EnterpriseMapper;
import com.ytpm.middle.dao.FinanceMapper;
import com.ytpm.middle.model.YtAppGrantRecord;
import com.ytpm.middle.model.YtMiddleEnterprise;
import com.ytpm.middle.param.AppForm;
import com.ytpm.middle.param.AppListParam;
import com.ytpm.middle.param.GrantAppParam;
import com.ytpm.middle.service.AppService;
import com.ytpm.middle.util.FeignClientInvoker;
import com.ytpm.middle.view.AppListVO;
import com.ytpm.middle.view.DropDownVO;
import com.ytpm.middle.view.FinancePaymentVO;
import com.ytpm.util.IDUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class AppServiceImpl implements AppService {

    @Resource
    private AppMapper appMapper;
    @Resource
    private EnterpriseMapper enterpriseMapper;
    @Autowired
    private FinanceMapper financeMapper;
    @Autowired
    private FeignClientInvoker feignInvoker;

    /**
     *  应用列表
     */
    @Override
    public ResultTable<AppListVO> appList(AppListParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        return ResultTable.resultTableOk(new PageInfo<>(appMapper.getAppList(param)));
    }
    /**
     * 新增上架应用
     */
    @Override
    public Result<String> addApp(AppForm form) {
        // 20251118 反馈IOS应用移除包名唯一校验
        if (form.getAppType() == null || form.getAppType() != 2) {
            YtPlatformUserApp old = appMapper.getByPackName(form.getPackageName());
            if (Objects.nonNull(old)) {
                return Result.resultErr(RepMessage.OBJECT_ALREADY_EXIST);
            }
        }
        YtPlatformUserApp app = new YtPlatformUserApp();
        BeanUtils.copyProperties(form, app);
        app.setCreateTime(new Date());
        app.setCreateUserId(form.getCreateUserId());
        app.setAvailable(1);
        app.setChargeStatus(0);
        appMapper.insertOne(app);
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }

    /**
     * 删除应用
     */
    @Override
    public Result<String> delApp(String appId, String userId) {
        appMapper.delApp(appId,userId);
        return Result.resultOk(RepMessage.DELETE_SUCCESS);
    }

    /**
     * 应用授权企业
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> grantApp(GrantAppParam param) {
        //查询企业是否存在
        YtMiddleEnterprise enterprise = enterpriseMapper.getByCode(param.getCreditCode());
        if(Objects.isNull(enterprise)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        //查询企业用户定金缴费单是否缴费完成
        FinancePaymentVO vo = financeMapper.getPaymentByType(enterprise.getUserId(),1);
        if(Objects.isNull(vo)){
            return Result.resultErr(RepMessage.PAYMENT_NOT_EXIST);
        }
        if(0 == vo.getPaymentStatus()){
            return Result.resultErr(RepMessage.WAITING_PAYMENT);
        }
        //校验微信登录设置
        YtPlatformUserApp appInfo =  appMapper.getByPrimary(param.getAppId());
        if(Objects.isNull(appInfo)|| StrUtil.isBlank(appInfo.getWxAppId())){
            return Result.resultErr(RepMessage.WX_APP_ID_NOT_EMPTY);
        }
        //将当前应用授权给企业
        YtPlatformUserApp app = new YtPlatformUserApp();
        app.setAppId(param.getAppId());
        app.setUpdateParam(param.getUserId());
        app.setUserId(enterprise.getUserId());
        app.setGrantType(param.getGrantType());
        app.setChargeStatus(1);
        appMapper.updateById(app);
        //增加授权记录
        addGrantAppRecord(param, app);
        return Result.resultOk(RepMessage.GRANT_SUCCESS);
    }

    /**
     * 授权应用记录
     */
    private void addGrantAppRecord(GrantAppParam param, YtPlatformUserApp app) {
        YtAppGrantRecord grantRecord = new YtAppGrantRecord();
        grantRecord.setRecordId(IDUtil.generateFlowID("grant"));
        grantRecord.setAppId(app.getAppId());
        grantRecord.setUserId(app.getUserId());
        grantRecord.setGrantType(param.getGrantType());
        grantRecord.setSalePrice(app.getSalePrice());
        grantRecord.setRatio(param.getRatio());
        grantRecord.setDataCharge(param.getDataCharge());
        grantRecord.setGrantTime(new Date());
        grantRecord.setOperateTime(new Date());
        grantRecord.setOperatorId(param.getUserId());
        appMapper.addGrantRecord(grantRecord);
    }

    /**
     * 修改上架应用信息
     */
    @Override
    public Result<String> updateApp(AppForm form) {
        YtPlatformUserApp old = appMapper.getByPrimary(form.getAppId());
        if(Objects.isNull(old)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        YtPlatformUserApp app = new YtPlatformUserApp();
        BeanUtils.copyProperties(form, app);
        appMapper.updateById(app);
        YtAppDefaultConfig config = new YtAppDefaultConfig();
        config.setTakuAppId(app.getTakuAppId());
        config.setTakuKey(app.getTakuKey());
        config.setTakuBannerPid(app.getTakuBannerPid());
        config.setTakuNativePid(app.getTakuNativePid());
        config.setTakuRewardPid(app.getTakuRewardPid());
        config.setTakuInterstitialPid(app.getTakuInterstitialPid());
        // 忽略异常 旧服务兼容性处理
        ExecutorService executor = Executors.newCachedThreadPool();
        try {
            executor.execute(() -> {
                List<String> apps = appMapper.getAppListForSuperior(app.getAppId());
                AppConfigUpdateParam param = new AppConfigUpdateParam();
                param.setDefaultConfig(config);
                param.setApps(apps);
                feignInvoker.invoke(old.getServiceName(), "updateAppsConfig", param);
            });
        } catch (Exception ignored) {
        } finally {
            executor.shutdown();
        }
        return Result.resultOk(RepMessage.GRANT_SUCCESS);
    }

    /**
     * 查询上架应用
     */
    @Override
    public ResultTable<DropDownVO> getIssuedAppList() {
        return ResultTable.resultTableOk(new PageInfo<>(appMapper.getIssuedAppList()));
    }

    /**
     * 根据上级应用获取apk包
     */
    @Override
    public ResultTable<DropDownVO> getApkList(String appId) {
        return ResultTable.resultTableOk(new PageInfo<DropDownVO>(appMapper.getApkList(appId)));
    }
}
