<template>
  <div class="app-container h-full flex flex-1 flex-col">
    <!-- 搜索 -->
    <page-search
      ref="searchRef"
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    >
      <template #status="scope">
        <Dict v-model="scope.formData[scope.prop]" code="status" v-bind="scope.attrs" />
      </template>
    </page-search>

    <!-- 列表 -->
    <page-content
      ref="contentRef"
      :content-config="contentConfig"
      @add-click="handleAddClick"
      @export-click="handleExportClick"
      @search-click="handleSearchClick"
      @toolbar-click="handleToolbarClick"
      @operate-click="handleOperateClick"
      @filter-change="handleFilterChange"
    >
      <template #status="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="status" />
      </template>
      <template #ecAttach="scope">
        <div v-if="scope.row[scope.prop]">
          <el-image 
            v-if="isImageFile(scope.row[scope.prop])"
            :src="scope.row[scope.prop]"
            :preview-src-list="[scope.row[scope.prop]]"
            preview-teleported
            style="width: 50px; height: 50px; cursor: pointer;"
            fit="cover"
            lazy
          />
          <el-link 
            v-else
            :href="scope.row[scope.prop]" 
            target="_blank"
            type="primary"
            :underline="false"
          >
            {{ getFileName(scope.row[scope.prop]) }}
          </el-link>
        </div>
        <span v-else>无</span>
      </template>
    </page-content>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #status="scope">
        <Dict v-model="scope.formData[scope.prop]" code="status" v-bind="scope.attrs" />
      </template>
      <template #ecAttach="scope">
        <FileUpload 
          v-model="fileList[scope.prop]" 
          :limit="1" 
          @update:model-value="handleFileUploadChange($event, scope.formData, scope.prop)"
        />
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal ref="editModalRef" :modal-config="editModalConfig" @submit-click="handleSubmitClick">
      <template #status="scope">
        <Dict v-model="scope.formData[scope.prop]" code="status" v-bind="scope.attrs" />
      </template>
      <template #ecAttach="scope">
        <FileUpload 
          v-model="fileList[scope.prop]" 
          :limit="1" 
          @update:model-value="handleFileUploadChange($event, scope.formData, scope.prop)"
        />
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: "ThirdPartyInfo" });

import ThirdPartyInfoAPI, { ThirdPartyInfoForm, ThirdPartyInfoPageQuery } from "@/api/operationsManage/third-party-info-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { ref } from "vue";
import type { FileInfo } from "@/api/file-api";

// 组合式 CRUD
const {
  searchRef,
  contentRef,
  addModalRef,
  editModalRef,
  handleQueryClick,
  handleResetClick,
  handleAddClick,
  handleEditClick,
  handleSubmitClick,
  handleExportClick,
  handleSearchClick,
  handleFilterChange,
} = usePage();

// 文件列表
const fileList = ref<Record<string, FileInfo[]>>({});

// 处理文件上传变化
const handleFileUploadChange = (files: any[], formData: any, prop: string) => {
  if (files && files.length > 0) {
    // 取第一个文件的URL作为值
    formData[prop] = files[0].url;
  } else {
    formData[prop] = undefined;
  }
};

// 判断是否为图片文件
const isImageFile = (url: string) => {
  if (!url) return false;
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
  const ext = url.split('.').pop()?.toLowerCase() || '';
  return imageExtensions.includes(ext);
};

// 获取文件名
const getFileName = (url: string) => {
  if (!url) return '';
  const fileName = url.split('/').pop() || '';
  return fileName || '下载文件';
};

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "system:third-party-info",
  formItems: [
    {
      type: "input",
      label: "对接商名称",
      prop: "ecName",
      attrs: {
        placeholder: "对接商名称",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "custom",
      slotName: "status",
      label: "状态", //0 正常 1 停用
      prop: "status",
      attrs: {
        placeholder: "状态",
        clearable: true,
        style: { width: "200px" },
      },
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<ThirdPartyInfoPageQuery> = reactive({
  // 权限前缀
  permPrefix: "system:third-party-info",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: ThirdPartyInfoAPI.getPage,
  // 删除接口
  deleteAction: ThirdPartyInfoAPI.deleteByIds,
  // 数据解析函数
  parseData(res: any) {
    return {
      total: res.total,
      list: res.list,
    };
  },
  // 分页配置
  pagination: {
    background: true,
    layout: "total, sizes, prev, pager, next, jumper",
    pageSize: 20,
    pageSizes: [10, 20, 30, 50],
  },
  // 工具栏配置
  toolbar: ["add", "delete"],
  defaultToolbar: ["refresh", "filter"],
  // 表格列配置
  cols: [
    { type: "selection", width: 55, align: "center" },
    { label: "对接商名称", prop: "ecName" },
    { label: "联系人", prop: "contactName" },
    { label: "联系人电话", prop: "contactPhone" },
    {
      label: "协议附件",
      prop: "ecAttach",
      templet: "custom",
      slotName: "ecAttach"
    },
    { label: "对接编号", prop: "appId" },
    { label: "授权码", prop: "authCode" },
    {
      label: "状态", //0 正常 1 停用
      prop: "status",
      templet: "custom",
      slotName: "status"
    },
    { label: "备注", prop: "remark" },
    { label: "创建时间", prop: "createTime" },
    {
      label: "操作",
      prop: "operation",
      width: 220,
      templet: "tool",
      operat: ["edit", "delete"],
    },
  ],
});

// 新增配置
const addModalConfig: IModalConfig<ThirdPartyInfoForm> = reactive({
  // 权限前缀
  permPrefix: "system:third-party-info",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  // 表单项配置
  formItems: [
    {
      type: "input",
      attrs: {
        placeholder: "对接商名称"
      },
      label: "对接商名称",
      prop: "ecName",
    },
    {
      type: "input",
      attrs: {
        placeholder: "联系人"
      },
      label: "联系人",
      prop: "contactName",
    },
    {
      type: "input",
      attrs: {
        placeholder: "联系人电话"
      },
      label: "联系人电话",
      prop: "contactPhone",
    },
    {
      type: "custom",
      label: "协议附件",
      prop: "ecAttach",
      slotName: "ecAttach",
    },
    {
      type: "input",
      attrs: {
        placeholder: "对接编号"
      },
      label: "对接编号",
      prop: "appId",
    },
    {
      type: "input",
      attrs: {
        placeholder: "授权码"
      },
      label: "授权码",
      prop: "authCode",
    },
    {
      type: "custom",
      label: "状态", //0 正常 1 停用
      prop: "status",
      slotName: "status",
      attrs: {
        placeholder: "状态",
        style: { width: "100%" }
      },
    },
    {
      type: "input",
      attrs: {
        placeholder: "备注"
      },
      label: "备注",
      prop: "remark",
    },
  ],
  // 提交函数
  formAction: (data: ThirdPartyInfoForm) => {
    if (data.id) {
      // 编辑
      return ThirdPartyInfoAPI.update(data.id as string, data);
    } else {
      // 新增
      return ThirdPartyInfoAPI.create(data);
    }
  },
});

// 编辑配置
const editModalConfig: IModalConfig<ThirdPartyInfoForm> = reactive({
  permPrefix: "system:third-party-info",
  component: "drawer",
  drawer: {
    title: "编辑",
    size: 500,
  },
  pk: "id",
  formAction(data: any) {
    return ThirdPartyInfoAPI.update(data.id as string, data);
  },
  formItems: addModalConfig.formItems, // 复用新增的表单项
});

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    handleEditClick(data.row, async () => {
      return await ThirdPartyInfoAPI.getFormData(data.row.id);
    });
  }
};

// 处理工具栏按钮点击（删除等）
const handleToolbarClick = (name: string) => {
  console.log(name);
};

</script>
