<template>
  <component
    is="a-modal"
    v-model:visible="visible"
    :width="tool.getDevice() === 'mobile' ? '100%' : '600px'"
    :title="title"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="submit"
    :footer="false"
  >
    <!-- 表单信息 start -->
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :auto-label-width="true"
    >
      <a-form-item label="推送游戏" field="gamePackageId">
        <a-select v-model="formData.gamePackageId" placeholder="请选择推送游戏">
          <a-option
            v-for="item in gamePackageOptions"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </a-select>
      </a-form-item>

      <a-form-item label="分包标识" field="remark">
        <a-textarea v-model="formData.remark" placeholder="请输入分包标识" />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="addGamePackage"
            >生成分包标识</a-button
          >
          <a-button type="primary" @click="downloadExcel">下载excel</a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import tool from "@/utils/tool";
import api from "@/api/system/post";
import { request } from "@/utils/request";
import commonApi from "../../api/common";

const emit = defineEmits(["success"]);

// 引用定义
const formRef = ref();
const mode = ref("");
const visible = ref(false);
const loading = ref(false);
const batchData = ref([]);
const gamePackageOptions = ref([]);
const isExport = ref(false);

let title = computed(() => {
  return "广点通分包";
});

// 表单初始值
const initialFormData = {
  id: "",
  gamePackageId: "",
  remark: "",
};

// 表单信息
const formData = reactive({ ...initialFormData });

// 设置批量数据
const setBatchData = async (data) => {
  batchData.value = data;
};

// 验证规则
const rules = {
  game_id: [{ required: true, message: "推送游戏不能为空" }],
};

// 打开弹框
const open = async (type = "ks") => {
  mode.value = type;
  // 重置表单数据
  Object.assign(formData, initialFormData);
  formRef.value.clearValidate();
  formRef.value.resetFields();

  visible.value = true;
  await initPage();
};

// 初始化页面数据
const initPage = async () => {
  await getGamePackageOptions();
};

// 获取母包列表
const getGamePackageOptions = async () => {
  const res = await commonApi.getPackageOptionsApi({ media_id: 2 });
  if (res.code === 200) {
    gamePackageOptions.value = res.data;
  }
};

// 生成分包标识
const addGamePackage = async () => {
  let data = [];
  let gamePackage = gamePackageOptions.value.find(
    (item) => item.id === formData.gamePackageId
  );
  for (let i = 0; i < batchData.value.length; i++) {
    let row = batchData.value[i];
    data.push(
      // 母包名称-广告位ID,游戏ID_渠道ID_广告位ID
      `${gamePackage.name}-${row.site_id},${gamePackage.game_id}_${row.agent_id}_${row.site_id}`
    );
  }
  formData.remark = data.join("\n");
  console.log("生成分包标识", data);
};

// 下载excel
const downloadExcel = async () => {
  if (!formData.remark) {
    Modal.error({
      title: "提示",
      content: "请先生成分包标识",
    });
    return;
  }
  console.log("下载excel");
  // 导出
  Message.info("请求服务器下载文件中...");
  const data = formData.remark.split("\n");
  const download = () =>
    request({
      url: "/v1/advert/AgentSite/exportGamePackageKs",
      data: { title: title.value, data },
      method: "post",
      timeout: 60 * 1000,
      responseType: "blob",
    });
  isExport.value = true;
  download()
    .then((res) => {
      if (res && res.status == 200) {
        tool.download(res);
        Message.success("请求成功，文件开始下载");
      } else {
        Message.error("请前往服务端安装Excel导出库");
      }
    })
    .catch(() => {
      Message.error("请求服务器错误，下载失败");
    })
    .finally(() => {
      isExport.value = false;
    });
};

// 设置数据
const setFormData = async (data) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key];
    }
  }
};

// 数据保存
const submit = async (done) => {
  const validate = await formRef.value?.validate();
  if (!validate) {
    loading.value = true;
    let data = { ...formData };
    let result = {};
    // 生成标识

    if (result.code === 200) {
      Message.success("操作成功");
      emit("success");
      done(true);
    }
    // 防止连续点击提交
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  done(false);
};

// 关闭弹窗
const close = () => (visible.value = false);

defineExpose({ open, setFormData, setBatchData });
</script>
