<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center">
          <el-button link @click="handleBack">
            <el-icon><ArrowLeft /></el-icon>
            <span class="ml-1">返回</span>
          </el-button>
          <el-divider direction="vertical" />
          <span class="text-lg font-medium">发布方案</span>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <!-- 推文标题 -->
          <el-col :span="8">
            <el-form-item label="推文标题" prop="tweetsTitle">
              <el-input
                v-model="form.tweetsTitle"
                type="textarea"
                :rows="3"
                placeholder="请输入推文标题"
              />
            </el-form-item>
          </el-col>
          <!-- 副标题 -->
          <el-col :span="8">
            <el-form-item label="副标题" prop="subtitle">
              <el-input
                v-model="form.subtitle"
                type="textarea"
                :rows="3"
                placeholder="请输入副标题"
              />
            </el-form-item>
          </el-col>
          <!-- 推文类别 -->
          <el-col :span="8">
            <el-form-item label="推文类别" prop="tweetsCategory">
              <el-select v-model="form.tweetsCategory" placeholder="选择分类" clearable style="width: 100%">
                <el-option
                  v-for="item in purchaseCategoryOptions"
                  :key="item.id"
                  :label="item.categoryName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 适配场景 -->
          <el-col :span="8">
            <el-form-item label="适配场景" prop="adaptNo">
              <el-select v-model="form.adaptNo" placeholder="选择分类" clearable style="width: 100%">
                <el-option
                  v-for="item in sceneOptions"
                  :key="item.id"
                  :label="item.sceneName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 适配行业 -->
          <el-col :span="8">
            <el-form-item label="适配行业" prop="adaptIndustry">
              <el-select v-model="form.adaptIndustry" placeholder="请选择" clearable style="width: 100%">
                <el-option
                  v-for="item in industryOptions"
                  :key="item.id"
                  :label="item.industryCategoryName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 价格区间 -->
          <el-col :span="8">
            <el-form-item label="价格区间" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 标签 -->
          <el-col :span="8">
            <el-form-item label="标签" prop="lable">
              <el-select v-model="form.lable" placeholder="选择分类" clearable style="width: 100%">
                <el-option
                  v-for="item in tagOptions"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 失效时间 -->
          <el-col :span="8">
            <el-form-item label="失效时间" prop="invalidTime">
              <el-date-picker
                v-model="form.invalidTime"
                type="date"
                placeholder="请选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <!-- 显示设置 -->
          <el-col :span="8">
            <el-form-item label="显示设置" prop="isShow">
              <el-switch
                v-model="form.isShow"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 封面图 -->
          <el-col :span="24">
            <el-form-item label="封面图" prop="coverImage">
              <div class="flex items-center gap-2">
                <el-button @click="openCoverUpload">
                  <el-icon><Upload /></el-icon>
                  <span class="ml-1">选择上传文件</span>
                </el-button>
                <el-button @click="openCoverSelector">
                  <el-icon><Picture /></el-icon>
                  <span class="ml-1">从图片库选择</span>
                </el-button>
                <div v-if="form.coverImage" class="ml-4 flex items-center">
                  <el-image
                    :src="coverImageUrl"
                    style="width: 60px; height: 60px"
                    fit="cover"
                    :preview-src-list="[coverImageUrl]"
                  />
                  <el-button link type="danger" class="ml-2" @click="clearCoverImage">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 上传方案 -->
          <el-col :span="24">
            <el-form-item label="上传方案" prop="uploadScheme">
              <div class="flex items-center gap-2">
                <el-button @click="openSchemeSelector">
                  <el-icon><Upload /></el-icon>
                  <span class="ml-1">选择文件</span>
                </el-button>
                <span v-if="form.filename" class="ml-4 text-gray-600">{{ form.filename }}</span>
                <el-button v-if="form.uploadScheme" link type="danger" class="ml-2" @click="clearScheme">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 描述 -->
          <el-col :span="24">
            <el-form-item label="描述" prop="programDescribe">
              <el-input
                v-model="form.programDescribe"
                type="textarea"
                :rows="5"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" :loading="submitLoading" @click="handleSubmit">提 交</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 封面图上传对话框 -->
    <el-dialog v-model="coverUploadVisible" title="上传封面图" width="500px" append-to-body>
      <el-upload
        ref="coverUploadRef"
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :limit="1"
        accept="image/*"
        :on-change="handleCoverUploadChange"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">只能上传图片文件</div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="coverUploadVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCoverUpload">确定</el-button>
      </template>
    </el-dialog>

    <!-- 封面图选择器 -->
    <FileSelector
      v-model="coverSelectorVisible"
      title="选择封面图"
      :allowed-types="[1]"
      :multiple="false"
      :allow-upload="true"
      @confirm="handleCoverSelected"
    />

    <!-- 方案文件选择器 -->
    <FileSelector
      v-model="schemeSelectorVisible"
      title="选择方案文件"
      :allowed-types="[4]"
      :multiple="false"
      :allow-upload="true"
      @confirm="handleSchemeSelected"
    />
  </div>
</template>

<script setup lang="ts" name="ProgramForm">
import { ArrowLeft, Upload, Picture, Delete, UploadFilled } from '@element-plus/icons-vue';
import { getProgram, addProgram, updateProgram } from '@/api/product/program/index';
import { listPurchaseCategory } from '@/api/globalSetting/purchaseCategory';
import { listScene } from '@/api/globalSetting/scene';
import { listIndustryCategory } from '@/api/customer/industryCategory';
import { listCustomerTag } from '@/api/customer/customerTag';
import { ProgramForm } from '@/api/product/program/types';
import FileSelector from '@/components/FileSelector/index.vue';
import { img } from '@/utils/common';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();

// 表单引用
const formRef = ref<ElFormInstance>();
const coverUploadRef = ref();

// 加载状态
const submitLoading = ref(false);

// 下拉选项数据
const purchaseCategoryOptions = ref<any[]>([]);
const sceneOptions = ref<any[]>([]);
const industryOptions = ref<any[]>([]);
const tagOptions = ref<any[]>([]);

// 对话框状态
const coverUploadVisible = ref(false);
const coverSelectorVisible = ref(false);
const schemeSelectorVisible = ref(false);

// 临时上传文件
const tempCoverFile = ref<any>(null);

// 表单数据
const initFormData: ProgramForm = {
  id: undefined,
  programNo: undefined,
  tweetsTitle: undefined,
  subtitle: undefined,
  programDescribe: undefined,
  tweetsCategory: undefined,
  isShow: 1,
  coverImage: undefined,
  imageList: undefined,
  clicks: undefined,
  collects: undefined,
  price: undefined,
  adaptNo: undefined,
  lable: undefined,
  uploadScheme: undefined,
  adaptIndustry: undefined,
  invalidTime: undefined,
  filename: undefined,
  status: undefined,
  remark: undefined
};

const form = ref<ProgramForm>({ ...initFormData });

// 表单验证规则
const rules = reactive({
  tweetsTitle: [{ required: true, message: '推文标题不能为空', trigger: 'blur' }],
  programDescribe: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
});

// 封面图URL计算
const coverImageUrl = computed(() => {
  if (form.value.coverImage) {
    return img(form.value.coverImage);
  }
  return '';
});

/** 获取采购分类列表 */
const getPurchaseCategoryList = async () => {
  const res = await listPurchaseCategory({ isShow: 1 });
  purchaseCategoryOptions.value = res.rows || [];
};

/** 获取适配场景列表 */
const getSceneList = async () => {
  const res = await listScene({ isShow: 1 });
  sceneOptions.value = res.rows || [];
};

/** 获取行业列表 */
const getIndustryList = async () => {
  const res = await listIndustryCategory({ isShow: 1 });
  industryOptions.value = res.rows || [];
};

/** 获取标签列表 */
const getTagList = async () => {
  const res = await listCustomerTag({ isShow: 1 });
  tagOptions.value = res.rows || [];
};

/** 获取详情数据 */
const getDetail = async (id: string | number) => {
  const res = await getProgram(id);
  Object.assign(form.value, res.data);
};

/** 返回列表 */
const handleBack = () => {
  router.back();
};

/** 打开封面图上传对话框 */
const openCoverUpload = () => {
  tempCoverFile.value = null;
  coverUploadVisible.value = true;
};

/** 打开封面图选择器 */
const openCoverSelector = () => {
  coverSelectorVisible.value = true;
};

/** 打开方案文件选择器 */
const openSchemeSelector = () => {
  schemeSelectorVisible.value = true;
};

/** 处理封面图上传文件变化 */
const handleCoverUploadChange = (file: any) => {
  tempCoverFile.value = file;
};

/** 确认上传封面图 */
const confirmCoverUpload = () => {
  if (tempCoverFile.value) {
    // 这里需要上传文件到服务器，获取URL
    // 暂时使用本地预览
    const reader = new FileReader();
    reader.onload = (e) => {
      form.value.coverImage = e.target?.result as string;
    };
    reader.readAsDataURL(tempCoverFile.value.raw);
    coverUploadVisible.value = false;
  }
};

/** 处理封面图选择 */
const handleCoverSelected = (files: any[]) => {
  if (files && files.length > 0) {
    form.value.coverImage = files[0].path || files[0].url;
  }
};

/** 清除封面图 */
const clearCoverImage = () => {
  form.value.coverImage = undefined;
};

/** 处理方案文件选择 */
const handleSchemeSelected = (files: any[]) => {
  if (files && files.length > 0) {
    form.value.uploadScheme = files[0].path || files[0].url;
    form.value.filename = files[0].name || files[0].originalName;
  }
};

/** 清除方案文件 */
const clearScheme = () => {
  form.value.uploadScheme = undefined;
  form.value.filename = undefined;
};

/** 提交表单 */
const handleSubmit = async () => {
  await formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true;
      try {
        if (form.value.id) {
          await updateProgram(form.value);
        } else {
          await addProgram(form.value);
        }
        proxy?.$modal.msgSuccess('操作成功');
        router.back();
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

/** 初始化 */
onMounted(async () => {
  // 加载下拉选项
  await Promise.all([
    getPurchaseCategoryList(),
    getSceneList(),
    getIndustryList(),
    getTagList()
  ]);

  // 如果有id参数，加载详情
  const id = route.query.id;
  if (id) {
    await getDetail(id as string);
  }
});
</script>

<style scoped>
.flex {
  display: flex;
}
.items-center {
  align-items: center;
}
.gap-2 {
  gap: 8px;
}
.ml-1 {
  margin-left: 4px;
}
.ml-2 {
  margin-left: 8px;
}
.ml-4 {
  margin-left: 16px;
}
.text-lg {
  font-size: 18px;
}
.font-medium {
  font-weight: 500;
}
.text-gray-600 {
  color: #666;
}
</style>
