<template>
  <el-dialog v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="drawerProps.title">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="formData"
      :hide-required-asterisk="drawerProps.isView"
    >
      <!-- <el-form-item label="广告主ID" prop="advertiserId">
        <el-tag v-for="(id, index) in advertiserIdList" :key="index" style="margin-right: 8px; margin-bottom: 8px">
          {{ id }}
        </el-tag>
        <div v-if="advertiserIdList.length === 0" style="color: #909399">未选择广告主</div>
      </el-form-item> -->
      <el-form-item label="日期范围" prop="dt">
        <el-date-picker
          v-model="dt"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="SyncAdvertiserAccountCostDt">
import { ref, reactive, computed } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { syncAdvertiserAccountCostDt } from "@/api/modules/dataManage";

const rules = reactive({
  dt: [{ required: true, message: "请选择日期范围", trigger: "change" }]
});

const dt = ref<string[]>([]);

interface DrawerProps {
  title: string;
  isView: boolean;
  row: {
    advertiserId?: string[] | string;
    [key: string]: any;
  };
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 从 row 中提取广告主ID列表
const advertiserIdList = computed(() => {
  const advertiserId = drawerProps.value.row?.advertiserId;
  if (!advertiserId) return [];
  // 如果是数组，直接返回
  if (Array.isArray(advertiserId)) return advertiserId;
  // 如果是字符串，转换为数组
  if (typeof advertiserId === "string") return [advertiserId];
  return [];
});

// 表单数据
const formData = computed(() => ({
  advertiserId: advertiserIdList.value,
  dt: dt.value
}));

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  // 确保 row 对象存在
  if (!drawerProps.value.row) {
    drawerProps.value.row = {};
  }
  // 重置日期选择
  dt.value = [];
  drawerVisible.value = true;
};

// 提交数据
const ruleFormRef = ref<FormInstance>();
const handleSubmit = async () => {
  // 表单验证
  if (!ruleFormRef.value) return;
  const valid = await ruleFormRef.value.validate().catch(() => false);
  if (!valid) return;

  // 验证日期范围
  if (!dt.value || dt.value.length !== 2) {
    ElMessage.warning("请选择日期范围");
    return;
  }

  // 验证广告主ID
  // if (advertiserIdList.value.length === 0) {
  //   ElMessage.warning("未选择广告主");
  //   return;
  // }

  try {
    // 构建请求参数
    const params = {
      startDate: dt.value[0],
      endDate: dt.value[1],
      advertiserIdList: advertiserIdList.value
    };

    // 调用同步接口
    await syncAdvertiserAccountCostDt(params);
    ElMessage.success("同步素材消耗成功！");

    // 刷新表格数据
    drawerProps.value.getTableList?.();

    // 关闭抽屉
    drawerVisible.value = false;
  } catch (error) {
    console.error("同步失败：", error);
  }
};

defineExpose({
  acceptParams
});
</script>
