<template>
  <div class="wrapper">
    <el-row>
      <h3>模型服务商管理</h3>
    </el-row>
    <!--  筛选器-->
      <el-row :gutter="20">
          <el-col :span="4" style="margin-left: 20px">
              <el-form-item label="服务商名称">
                  <el-input v-model="filters.vendorName" style="width: 240px" placeholder="请输入服务商名称" />
              </el-form-item>
          </el-col>
          <el-col :span="5">
              <el-form-item label="服务商编码">
                  <el-input v-model="filters.vendorCode" style="width: 240px" placeholder="请输入服务商编码" />
              </el-form-item>
          </el-col>
          <el-col :span="4">
              <el-form-item label="服务商种类">
                  <el-select v-model="filters.modelKind" placeholder="全部">
                      <el-option
                              v-for="item in modelKindOption"
                              :value="item"
                              :label="item"
                              :key="item"
                      />
                  </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="4">
              <el-form-item label="状态">
                  <el-select v-model="filters.status" placeholder="全部">
                      <el-option
                              v-for="item in modelStateOption"
                              :label="item"
                              :value="item"
                              :key="item"
                      />
                  </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="1" :offset="4" style="padding-left: 30px">
              <el-button type="primary">搜索</el-button>
          </el-col>
          <el-col :span="1" style="padding-left: 30px">
              <el-button @click="resetFilters">重置</el-button>
          </el-col>
      </el-row>
    <el-row :gutter="20">
      <el-col :span="2">
        <el-button type="primary" @click="dialogVisible = true">+新增服务商</el-button>
        <el-dialog v-model="dialogVisible" title="新增服务商" width="40%">

          <el-form>
            <!-- Tab 栏 -->
            <el-tabs  tab-position="top" v-model="activeTab" type="card">
              <el-tab-pane label="基本信息" name="info1">
                <BasicInfo v-model="formData.info1" />
              </el-tab-pane>
              <el-tab-pane label="API配置" name="info2">
                <ApiInfo v-model="formData.info2" />
              </el-tab-pane>
              <el-tab-pane label="附加信息" name="info3">
                <AdditionInfo v-model="formData.info3" />
              </el-tab-pane>
            </el-tabs>
            <!-- 提交按钮 -->
            <div style="display: flex; justify-content: flex-end;">
              <el-form-item>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
              </el-form-item>
            </div>
          </el-form>

        </el-dialog>
      </el-col>
      <el-col :span="1.5">
        <el-button><el-icon><Upload /></el-icon>批量导入</el-button>
      </el-col>
      <el-col :span="1">
        <el-button><el-icon><Download /></el-icon>导出</el-button>
      </el-col>

    </el-row>
    <!--<div class="content">-->
    <!--  -->
    <!--</div>-->
    <div class="table">

      <el-table :data="models" @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <el-table-column label="logoUrl">
          <template #default="slot">
            <el-avatar :src="slot.row.logoUrl" size="small" v-if="slot.row.logoUrl" />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="服务商编码" prop="vendorCode" width="120" />
        <el-table-column label="服务商名称" prop="vendorName" width="120" />
        <el-table-column label="模型种类" prop="modelKind" width="420" />
        <el-table-column label="官方认证" width="120">
          <template #default="slot">
            <el-icon size="15" color="#45D1A6" name="success" v-if="slot.row.isofficial">
              <component is="Check" />
            </el-icon>
            <el-icon size="15" color="#FF4C4E" name="danger" v-else>
              <component is="Close" />
            </el-icon>
          </template>
        </el-table-column>
        <!--<el-table-column label="API接入" width="120">-->
        <!--  <template #default="slot">-->
        <!--    <el-icon size="15" color="#45D1A6" v-if="slot.row.apiAccess">-->
        <!--      <component is="Check" />-->
        <!--    </el-icon>-->
        <!--    <el-icon size="15" color="#FF4C4E" name="danger" v-else>-->
        <!--      <component is="Close" />-->
        <!--    </el-icon>-->
        <!--  </template>-->
        <!--</el-table-column>-->
        <el-table-column label="状态" width="120">
          <template #default="slot">
            <el-tag
                :type="
              slot.row.status === 'active'
                ? 'success'
                : slot.row.status === 'configuring'
                ? 'primary'
                : 'warning'
            "
            >
              {{
                slot.row.status === 1
                    ? '启用'
                    : slot.row.status === ''
                        ? '配置中'
                        : '待配置'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="240" />
        <el-table-column label="操作" width="240">
          <template #default="slot">
            <!-- 查看 -->
            <el-icon size="15" color="#15A9FF" style="margin-right: 10px;"><View /></el-icon>

            <!-- 编辑 -->
            <el-icon size="15" color="#15A9FF" style="margin-right: 10px;"><Edit /></el-icon>

            <!-- 启用/禁用图标 -->
            <el-icon size="15" style="margin-right: 10px;" :color="slot.row.status === 'active' ? '#13ce66' : '#ff4949'">
              <SwitchButton />
            </el-icon>

            <!-- 列表 -->
            <el-icon size="15" color="#15A9FF" style="margin-right: 10px;"><More /></el-icon>


          </template>
        </el-table-column>

      </el-table>
      <div class="batch-actions">
        <span>已选择 {{ selectedIds.length }} 项</span>
        <el-button type="primary" size="small" :disabled="selected.length === 0" @click="batchEnable">批量启用</el-button>
        <el-button type="danger" size="small" :disabled="selected.length === 0" @click="batchDisable">批量禁用</el-button>
        <el-button type="warning" size="small" :disabled="selected.length === 0" @click="batchDelete">批量删除</el-button>
      </div>

      <!-- 右下角的分页 -->
      <div class="pagination">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            @current-change="handlePageChange"
        />
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { TabsInstance, FormInstance } from 'element-plus'
import {Download, More, UploadFilled} from "@element-plus/icons-vue";
import { View, Edit, List, Check, Close } from '@element-plus/icons-vue'
import BasicInfo from "@/views/modleServiceProvide/components/BasicInfo.vue";
import ApiInfo from "@/views/modleServiceProvide/components/ApiInfo.vue";
import AdditionInfo from "@/views/modleServiceProvide/components/AdditionInfo.vue";
import { listModelVendor,addModelVendor, ModelVendorQuery, ModelVendorDto } from '@/api/modleServiceProvide';

import request from "@/utils/request";
// 筛选条件
const filters = ref({
    vendorName: '',
    vendorCode: '',
    modelKind: '',
    status: ''
});

// 筛选后的数据
const filteredData = computed(() => {
    return dataList.value.filter(item => {
        const matchName = item.vendorName.includes(filters.value.vendorName);
        const matchCode = item.vendorCode.includes(filters.value.vendorCode);
        const matchKind = !filters.value.modelKind || item.modelKind === filters.value.modelKind;
        const matchStatus = !filters.value.status || item.status === filters.value.status;
        return matchName && matchCode && matchKind && matchStatus;
    });
});

// 重置筛选条件
const resetFilters = () => {
    filters.value = {
        vendorName: '',
        vendorCode: '',
        modelKind: '',
        status: ''
    };
};
// 分页参数
const queryParams = ref<ModelVendorQuery>({
  pageNum: 1,
  pageSize: 10
});

// 数据绑定
const dataList = ref<ModelVendorDto[]>([]);
const total = ref<number>(0);
const loading = ref<boolean>(false);

// 获取数据方法
const getList = async () => {
  loading.value = true;
  try {
    const res = await listModelVendor(queryParams.value);
    dataList.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 页面加载时请求数据
onMounted(() => {
  getList();
});


const modelKindOption = ref(["大语言模型","多模态","OCR","视觉","向量化","重排序","语音"])
const modelStateOption = ref(["全部","开启","关闭"])
// const models = ref([])
const currentPage = ref(1) // 当前页码
const pageSize = ref(10) // 每页显示条目个数
const selected = ref<number[]>([]) // 存储选中的行ID

const activeTab = 'info1'
const modelState = ref(null)

// 定义表格数据的类型
interface ProviderModel {
  id: number
  logoUrl?: string
  vendorCode: string
  vendorName: string
  modelKind: string
  isofficial: boolean
  apiAccess: boolean
  status: 'active' | 'configuring' | 'pending' // 状态枚举
  createTime: string
}

// 表格数据
const models = ref<ProviderModel[]>([
  {
    id: 1,
    logoUrl: 'https://via.placeholder.com/40',
    vendorCode: 'PROV001',
    vendorName: '阿里云',
    modelKind: '大语言模型',
    isofficial: true,
    apiAccess: true,
    status: 'active',
    createTime: '2025-01-01 10:30',
  },
  {
    id: 2,
    logoUrl: 'https://via.placeholder.com/40',
    vendorCode: 'PROV002',
    vendorName: '腾讯云',
    modelKind: '图像识别',
    isofficial: false,
    apiAccess: true,
    status: 'configuring',
    createTime: '2025-02-15 10:30',
  },
  {
    id: 3,
    logoUrl: 'https://via.placeholder.com/40',
    vendorCode: 'PROV003',
    vendorName: '百度云',
    modelKind: '语音识别',
    isofficial: false,
    apiAccess: false,
    status: 'pending',
    createTime: '2025-03-10 10:30',
  },
])
// 批量启用
const batchEnable = () => {
  // 实现批量启用逻辑
}

// 批量禁用
const batchDisable = () => {
  // 实现批量禁用逻辑
}

// 批量删除
const batchDelete = () => {
  // 实现批量删除逻辑
}

// 分页处理
const handlePageChange = (newPage: number) => {
  currentPage.value = newPage
  // 根据新页面加载数据
}

const selectedIds = ref<number[]>([])

const handleSelectionChange = (selection: ProviderModel[]) => {
  selectedIds.value = selection.map(item => item.id)
}

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()


const formData = ref({
    info1: {
        vendorCode: '',
        vendorName: '',
        modelKind: '',
        logoUrl: '',
        logoFile: null, // 用于保存上传的文件对象
        isOfficial: false,
        status:0,
        sortOrder: 0
    },
    info2: {
        defaultUrl: '',
        extraConfig: ''
    },
    info3: {
        contactInfo: '',
        website: '',
        apiDocUrl: '',
        pricingUrl: '',
        description: '',

    }
})



//表单规则
const rules = {
  vendorName: [
    { required: true, message: '服务商名称不能为空', trigger: 'blur' }
  ],
  vendorCode: [
    { required: true, message: '服务商编码不能为空', trigger: 'blur' }
  ],
  modelKind: [
    { required: true, message: '请选择模型种类', trigger: 'change' }
  ]
}

// const modelKindOption = ref(['大语言模型', '图像识别', '语音识别'])

// logoUrl 上传成功回调
const handlelogoUrlSuccess = (response, file) => {
  form.value.logoUrl = URL.createObjectURL(file.raw)
}

// logoUrl 上传前校验
const beforelogoUrlUpload = (file) => {
  const isValid = ['image/jpeg', 'image/png'].includes(file.type)
  if (!isValid) {
    alert('只能上传 JPG/PNG 文件')
  }
  return isValid
}

const submitForm = () => {
    const data = formData.value;

    const submitData = new FormData();

    // 添加普通字段
    submitData.append('vendorName', data.info1.vendorName);
    submitData.append('vendorCode', data.info1.vendorCode);
    submitData.append('modelKind', data.info1.modelKind);
    submitData.append('isOfficial', data.info1.isOfficial.toString());
    submitData.append('sortOrder', data.info1.sortOrder.toString());

    submitData.append('defaultUrl', data.info2.defaultUrl);
    submitData.append('extraConfig', data.info2.extraConfig);

    submitData.append('apiDocUrl', data.info3.apiDocUrl);
    submitData.append('pricingUrl', data.info3.pricingUrl);
    submitData.append('contactInfo', data.info3.contactInfo);
    submitData.append('website', data.info3.website);

    // 添加文件
    if (data.info1.logoFile) {
        submitData.append('logo', data.info1.logoFile);
    }

   const res =  listModelVendor(submitData);

    // 发送请求
    // axios.post('/api/model/vendor/save', submitData, {
    //     headers: {
    //         'Content-Type': 'multipart/form-data'
    //     }
    // }).then(() => {
    //     ElMessage.success('提交成功');
    //     dialogVisible.value = false;
    // }).catch(() => {
    //     ElMessage.error('提交失败');
    // });

}
</script>

<style scoped lang="scss">
.input-tips{
  font-size: 10px;
  color: #989a9a;

}
.wrapper{
  margin:10px auto;
  width:90%;
}
.model-msg{
  span{
    color:#666666;
  }
}
.section-type{
  span{
    padding-left: 5px;
  }
}
.batch-actions {
  padding: 10px;
  border-top: 1px solid #EBEEF5;
  display: flex;
  align-items: center;
  span {
    margin-right: 10px;
  }
}
.pagination {
  position:absolute;
  right: 0;
  padding: 10px;
  border-top: 1px solid #EBEEF5;
}
.msg-space{
  margin-top:5px;
}
.content{
  padding-left: 10px;
}
.table{
  margin-top: 10px;
}
.el-dialog {
  .el-form {
    padding: 10px;
  }
}
</style>
