package cn.com.ctop.kuaishou.modules.ai.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.ai.entity.AiKuaiShouAppInfo;
import cn.com.ctop.kuaishou.modules.ai.mapper.AiKuaiShouAppInfoMapper;
import cn.com.ctop.kuaishou.modules.ai.service.IAiKuaiShouAppInfoService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ai批量上传应用
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-02-02
 */
@Service
@Slf4j
public class AiKuaiShouAppInfoServiceImpl extends ServiceImpl<AiKuaiShouAppInfoMapper, AiKuaiShouAppInfo> implements IAiKuaiShouAppInfoService {
    @Autowired
    private IKuaiShouMaterialUploadService materialUploadService;
    @Autowired
    private AiKuaiShouAppInfoMapper aiKuaiShouAppInfoMapper;
    static ExecutorService executorService = Executors.newFixedThreadPool(10);

    /**
     * 文件导入
     *
     * @param
     * @param accountId
     * @param imageToken
     * @return
     */
    @Override
    public JSONObject importExcel(MultipartFile myFile, Long accountId, String imageToken, Integer platform, String accessToken) {
        JSONObject returnJson = new JSONObject();
        try {
            Workbook workbook = null;
            String fileName = myFile.getOriginalFilename();
            String substring = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
            if (substring.equals("XLS")) {
                workbook = new HSSFWorkbook(myFile.getInputStream());
            } else if (substring.equals("XLSX")) {
                workbook = new XSSFWorkbook(myFile.getInputStream());
            } else {
                throw new Exception("文件不是Excel文件");
            }
            Sheet sheet = workbook.getSheet("Sheet1");
            int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
            if (rows == 0) {
                throw new Exception("请填写数据");
            }
            List<AiKuaiShouAppInfo> appList = new ArrayList<>();
            for (int i = 1; i <= rows + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    AiKuaiShouAppInfo appInfo = new AiKuaiShouAppInfo();
                    appInfo.setStatus(0);
                    appInfo.setRemark("应用待创建");
                    appInfo.setAccountId(accountId);
                    appInfo.setPlatform(platform);
                    appInfo.setImageToken(imageToken);
                    String appName = getCellValue(row.getCell(0));
                    appInfo.setAppName(appName);
                    String packageName = getCellValue(row.getCell(1));
                    appInfo.setPackageName(packageName);
                    String appVersion = getCellValue(row.getCell(2));
                    appInfo.setAppVersion(appVersion);
                    String useSdk = getCellValue(row.getCell(3));
                    if (!Check.isNull(useSdk)) {
                        appInfo.setUseSdk(Integer.valueOf(useSdk));
                    }
                    String appPrivacyUrl = getCellValue(row.getCell(4));
                    if (!Check.isNull(appPrivacyUrl)) {
                        appInfo.setAppPrivacyUrl(appPrivacyUrl);
                    }
                    String url = getCellValue(row.getCell(5));
                    if (!Check.isNull(url)) {
                        appInfo.setUrl(url);
                    }
                    String trackUrl = getCellValue(row.getCell(6));
                    if (!Check.isNull(trackUrl)) {
                        appInfo.setTrackUrl(trackUrl);
                    }
                    appList.add(appInfo);
                }
            }
            this.saveBatch(appList);
            appCreative(accountId, accessToken);
            returnJson.put("code", 0);
            returnJson.put("message", "文件导入成功，异步创建中，请稍后...");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }

    @Override
    public void appCreative(Long accountId, String accessToken) {
        List<AiKuaiShouAppInfo> appListByStatus = getAppListByStatus(accountId, 0);
        for (AiKuaiShouAppInfo appInfo : appListByStatus) {
            AiKuaiShouAppInfo updateAppInfo = new AiKuaiShouAppInfo();
            updateAppInfo.setId(appInfo.getId());
            if (Check.isNull(appInfo.getUrl())) {
                updateAppInfo.setStatus(3);
                updateAppInfo.setRemark("下载链接为空");
                this.updateById(updateAppInfo);
                continue;
            }
            String md5 = MD5Util.getMd5(appInfo.getUrl());
            if (Check.isNull(md5)) {
                updateAppInfo.setStatus(3);
                updateAppInfo.setRemark("获取应用MD5失败");
                this.updateById(updateAppInfo);
                continue;
            }
            updateAppInfo.setAppMd5(md5);
            updateAppInfo.setStatus(1);
            updateAppInfo.setRemark("应用创建中");
            this.updateById(updateAppInfo);
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject requestJson = new JSONObject();
                        requestJson.put("advertiser_id", appInfo.getAccountId());
                        requestJson.put("app_version", appInfo.getAppVersion());
                        requestJson.put("app_name", appInfo.getAppName());
                        requestJson.put("image_token", appInfo.getImageToken());
                        requestJson.put("package_name", appInfo.getPackageName());
                        requestJson.put("platform", appInfo.getPlatform());
                        requestJson.put("url", appInfo.getUrl());
                        requestJson.put("use_sdk", appInfo.getUseSdk());
                        requestJson.put("app_privacy_url", appInfo.getAppPrivacyUrl());
                        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.APP_CREATE;
                        Map<String, String> headerMap = new HashMap<>();
                        headerMap.put("Content-Type", "multipart/form-data");
                        headerMap.put("Access-Token", accessToken);
                        String s = materialUploadService.exceptInfoForRestTemplate(url, requestJson, headerMap);
                        JSONObject resultJson = JSONObject.parseObject(s);
                        log.info("上传应用返回信息：{}", resultJson);
                        if (!Check.isNull(resultJson)) {
                            Integer code = resultJson.getInteger("code");
                            if (code == 0) {
                                JSONObject data = resultJson.getJSONObject("data");
                                Long app_id = data.getLong("app_id");
                                updateAppInfo.setStatus(2);
                                updateAppInfo.setRemark("创建应用成功");
                                updateAppInfo.setAppId(app_id);
                            } else {
                                updateAppInfo.setStatus(3);
                                updateAppInfo.setRemark(resultJson.getString("message"));
                            }
                        } else {
                            updateAppInfo.setStatus(3);
                            updateAppInfo.setRemark("上传应用返回结果为空");
                        }

                    } catch (Exception e) {
                        updateAppInfo.setStatus(3);
                        updateAppInfo.setRemark("系统异常");

                    }
                    aiKuaiShouAppInfoMapper.updateById(updateAppInfo);
                }
            });
        }
    }

    @Override
    public AiKuaiShouAppInfo getByParams(Long accountId,Long appId) {
        QueryWrapper<AiKuaiShouAppInfo>queryWrapper = new QueryWrapper<>();
        if(null!=accountId&&accountId!=0){
            queryWrapper.eq("account_id",accountId);
        }
        if(null!=appId&&appId!=0){
            queryWrapper.eq("app_id",appId);
        }
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }


    private List<AiKuaiShouAppInfo> getAppListByStatus(Long accountId, Integer status) {
        QueryWrapper<AiKuaiShouAppInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("status", status);
        return this.list(queryWrapper);
    }


    private String getCellValue(Cell cell) {
        String value = "";
        if (cell != null) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                    value = cell.getNumericCellValue() + "";
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        if (date != null) {
                            value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                        } else {
                            value = "";
                        }
                    } else {
                        value = new DecimalFormat("0").format(cell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING: // 字符串
                    value = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                    value = cell.getBooleanCellValue() + "";
                    break;
                case HSSFCell.CELL_TYPE_FORMULA: // 公式
                    value = cell.getCellFormula() + "";
                    break;
                case HSSFCell.CELL_TYPE_BLANK: // 空值
                    value = "";
                    break;
                case HSSFCell.CELL_TYPE_ERROR: // 故障
                    value = "非法字符";
                    break;
                default:
                    value = "未知类型";
                    break;
            }
        }
        return value.trim();
    }


    @Override
    public JSONObject uploadAppIconImage(String url, Long accountId, String accessToken) {
        JSONObject returnJson = new JSONObject();
        try {
            Map<String, String> headerMap = new HashMap<>();
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            headerMap.put("Access-Token", accessToken);
            headerMap.put("Content-Type", "multipart/form-data");
            requestJson.put("url", url);
            requestJson.put("type", 1);
            requestJson.put("upload_type", "2");
            String requestUrl = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_UPLOAD;
            String result = materialUploadService.exceptInfoForRestTemplate(requestUrl, requestJson, headerMap);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                if (resultJson.getInteger("code") == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        String signature = dataJson.getString("signature");
                        String image_token = dataJson.getString("image_token");
                        returnJson.put("code", 0);
                        returnJson.put("imageToken", image_token);
                        returnJson.put("signature", signature);

                    } else {
                        log.error("快手同步封面素材失败，返回信息：{}，请求参数：{}", resultJson, requestJson);
                        returnJson.put("code", -1);
                        returnJson.put("message", "图片上传失败");
                    }
                } else {
                    log.error("快手同步封面素材失败，返回信息：{}，请求参数：{}", resultJson, requestJson);
                    returnJson.put("code", -1);
                    returnJson.put("message", resultJson.getString("message"));
                }
            }
        } catch (Exception e) {
            returnJson.put("code", -1);
            returnJson.put("message", "系统错误，请重新上传");
        }

        return returnJson;
    }
}
