import { BasicColumn } from '/@/components/Table';
import { FormSchema } from '/@/components/Table';
import { h } from 'vue';
import { Image, Tag } from 'ant-design-vue';
import { render } from '/@/utils/common/renderUtils';
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';
import { getHeritageProjectOptions } from '/@/api/oroqen/OroqenHeritageProject';

//列表数据
export const columns: BasicColumn[] = [
  {
    title: '头像',
    align: 'center',
    dataIndex: 'avatar',
    width: 80,
    customRender: ({ text, record }) => {
      if (!text) return '-';
      const imageUrl = getFileAccessHttpUrl(text);
      
      return h(Image, {
        src: imageUrl,
        alt: record?.name || '传承人头像',
        width: 50,
        height: 50,
        style: { objectFit: 'cover', borderRadius: '4px' },
        preview: true,
        fallback: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3Ik1RnG4W+FgYxN'
      });
    }
  },
  {
    title: '姓名',
    dataIndex: 'name',
    width: 120,
    align: 'left',
    ellipsis: true,
    fixed: 'left',
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 80,
    align: 'center',
    customRender: ({ text }) => {
      const genderMap = {
        1: { text: '男', color: 'blue' },
        2: { text: '女', color: 'pink' },
      };
      const gender = genderMap[text] || { text: '未知', color: 'default' };
      return render.renderTag(gender.text, gender.color);
    },
  },
  {
    title: '年龄',
    dataIndex: 'age',
    width: 80,
    align: 'center',
  },
  {
    title: '民族',
    dataIndex: 'ethnicity',
    width: 100,
    align: 'center',
  },
  {
    title: '传承项目',
    dataIndex: 'heritageSkills',
    width: 150,
    align: 'left',
    ellipsis: true,
    customRender: ({ text }) => {
      if (!text) return '-';
      // 如果是数组格式的项目ID，需要转换为项目名称显示
      // 这里暂时直接显示，后续可以通过API获取项目名称
      if (Array.isArray(text)) {
        return text.join(', ');
      }
      return text;
    },
  },
  {
    title: '传承级别',
    dataIndex: 'heritageLevel',
    width: 120,
    align: 'center',
    customRender: ({ text }) => {
      const levelMap = {
        'national': { text: '国家级', color: 'red' },
        'provincial': { text: '省级', color: 'orange' },
        'municipal': { text: '市级', color: 'blue' },
        'county': { text: '县级', color: 'green' },
      };
      const level = levelMap[text] || { text: text || '未知', color: 'default' };
      return render.renderTag(level.text, level.color);
    },
  },
  {
    title: '认定年份',
    dataIndex: 'recognitionYear',
    width: 100,
    align: 'center',
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    width: 120,
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    align: 'center',
    customRender: ({ text }) => {
      const statusMap = {
        1: { text: '活跃', color: 'green' },
        0: { text: '停用', color: 'red' },
      };
      const status = statusMap[text] || { text: '未知', color: 'default' };
      return render.renderTag(status.text, status.color);
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 150,
    align: 'center',
    sorter: true,
  },
];

//查询数据
export const searchFormSchema: FormSchema[] = [
  {
    label: '姓名',
    field: 'name',
    component: 'Input',
    componentProps: {
      placeholder: '请输入传承人姓名',
    },
    colProps: { span: 6 },
  },
  {
    label: '性别',
    field: 'gender',
    component: 'Select',
    componentProps: {
      placeholder: '请选择性别',
      options: [
        { label: '男', value: 1 },
        { label: '女', value: 2 },
      ],
    },
    colProps: { span: 6 },
  },
  {
    label: '传承级别',
    field: 'heritageLevel',
    component: 'Select',
    componentProps: {
      placeholder: '请选择传承级别',
      options: [
        { label: '国家级', value: 'national' },
        { label: '省级', value: 'provincial' },
        { label: '市级', value: 'municipal' },
        { label: '县级', value: 'county' },
      ],
    },
    colProps: { span: 6 },
  },
  {
    label: '状态',
    field: 'status',
    component: 'Select',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        { label: '活跃', value: 1 },
        { label: '停用', value: 0 },
      ],
    },
    colProps: { span: 6 },
  },
];

//表单数据
export const formSchema: FormSchema[] = [
  {
    label: '',
    field: 'id',
    component: 'Input',
    show: false,
  },
  {
    label: '姓名',
    field: 'name',
    component: 'Input',
    required: true,
    componentProps: {
      placeholder: '请输入传承人姓名',
    },
    colProps: { span: 12 },
  },
  {
    label: '性别',
    field: 'gender',
    component: 'Select',
    required: true,
    componentProps: {
      placeholder: '请选择性别',
      options: [
        { label: '男', value: 1 },
        { label: '女', value: 2 },
      ],
    },
    colProps: { span: 12 },
  },
  {
    label: '年龄',
    field: 'age',
    component: 'InputNumber',
    componentProps: {
      min: 1,
      max: 120,
      placeholder: '请输入年龄',
    },
    colProps: { span: 12 },
  },
  {
    label: '民族',
    field: 'ethnicity',
    component: 'Input',
    componentProps: {
      placeholder: '请输入民族',
    },
    colProps: { span: 12 },
  },
  {
    label: '传承项目',
    field: 'heritageSkills',
    component: 'ApiSelect',
    componentProps: {
      api: getHeritageProjectOptions,
      params: {},
      resultField: '',
      labelField: 'label',
      valueField: 'value',
      placeholder: '请选择传承项目',
      mode: 'multiple',
      showSearch: true,
      filterOption: (input: string, option: any) => {
        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      },
    },
    // 数据转换：数据库存储为逗号分隔的字符串，前端显示为数组
    dynamicRules: ({ model, schema }) => {
      return [];
    },
    // 表单值转换
    valueFormat: (value) => {
      // 从数据库读取时：字符串转数组
      if (typeof value === 'string' && value) {
        return value.split(',').filter(v => v.trim());
      }
      return value || [];
    },
    // 提交时转换
    valueTransform: (value) => {
      // 提交到数据库时：数组转字符串
      if (Array.isArray(value)) {
        return value.join(',');
      }
      return value || '';
    },
    colProps: { span: 12 },
  },
  {
    label: '传承级别',
    field: 'heritageLevel',
    component: 'Select',
    required: true,
    componentProps: {
      placeholder: '请选择传承级别',
      options: [
        { label: '国家级', value: 'national' },
        { label: '省级', value: 'provincial' },
        { label: '市级', value: 'municipal' },
        { label: '县级', value: 'county' },
      ],
    },
    colProps: { span: 12 },
  },
  {
    label: '认定年份',
    field: 'recognitionYear',
    component: 'InputNumber',
    componentProps: {
      min: 1900,
      max: new Date().getFullYear(),
      placeholder: '请输入认定年份',
    },
    colProps: { span: 12 },
  },
  {
    label: '联系电话',
    field: 'phone',
    component: 'Input',
    componentProps: {
      placeholder: '请输入联系电话',
    },
    colProps: { span: 12 },
  },
  // {
  //   label: '身份证号',
  //   field: 'idCard',
  //   component: 'Input',
  //   componentProps: {
  //     placeholder: '请输入身份证号',
  //   },
  //   colProps: { span: 12 },
  // },
  {
    label: '地址',
    field: 'address',
    component: 'Input',
    componentProps: {
      placeholder: '请输入地址',
    },
    colProps: { span: 12 },
  },
  {
    label: '状态',
    field: 'status',
    component: 'Select',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        { label: '活跃', value: 1 },
        { label: '停用', value: 0 },
      ],
    },
    colProps: { span: 12 },
  },
  {
    label: '排序',
    field: 'sortOrder',
    component: 'InputNumber',
    componentProps: {
      min: 0,
      placeholder: '请输入排序值',
    },
    colProps: { span: 12 },
  },
  {
    label: '传承技艺描述',
    field: 'skillDescription',
    component: 'InputTextArea',
    componentProps: {
      rows: 4,
      placeholder: '请输入传承技艺描述',
    },
    colProps: { span: 24 },
  },
  {
    label: '个人简介',
    field: 'biography',
    component: 'InputTextArea',
    componentProps: {
      rows: 4,
      placeholder: '请输入个人简介',
    },
    colProps: { span: 24 },
  },
  {
    label: '传承经历',
    field: 'heritageExperience',
    component: 'InputTextArea',
    componentProps: {
      rows: 4,
      placeholder: '请输入传承经历',
    },
    colProps: { span: 24 },
  },
  {
    label: '获奖情况',
    field: 'awards',
    component: 'InputTextArea',
    componentProps: {
      rows: 3,
      placeholder: '请输入获奖情况',
    },
    colProps: { span: 24 },
  },
  {
    label: '头像',
    field: 'avatar',
    component: 'JUpload',
    componentProps: {
      fileType: 'image',
      maxCount: 1,
      maxSize: 5,
      bizPath: 'inheritor/portrait',
      customRequest: (options) => {
        // 验证文件类型和大小
        const { file } = options;
        const isImage = file.type.startsWith('image/');
        if (!isImage) {
          console.error('只能上传图片文件!');
          return;
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          console.error('图片大小不能超过5MB!');
          return;
        }
        
        // 创建本地预览URL
        const localUrl = URL.createObjectURL(file);
        
        // 直接设置文件的url为本地预览URL
        file.url = localUrl;
        
        // 模拟上传成功响应，返回blob URL作为message
        setTimeout(() => {
          options.onSuccess({
            success: true,
            message: localUrl, // 返回blob URL
          }, file);
        }, 100);
      },
    },
    colProps: { span: 12 },
  },
  {
    label: '作品图片',
    field: 'workImages',
    component: 'JUpload',
    componentProps: {
      fileType: 'image',
      maxCount: 10,
      maxSize: 5,
      bizPath: 'inheritor/works',
      customRequest: (options) => {
        // 验证文件类型和大小
        const { file } = options;
        const isImage = file.type.startsWith('image/');
        if (!isImage) {
          console.error('只能上传图片文件!');
          return;
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          console.error('图片大小不能超过5MB!');
          return;
        }
        
        // 创建本地预览URL
        const localUrl = URL.createObjectURL(file);
        
        // 直接设置文件的url为本地预览URL
        file.url = localUrl;
        
        // 模拟上传成功响应，返回blob URL作为message
        setTimeout(() => {
          options.onSuccess({
            success: true,
            message: localUrl, // 返回blob URL
          }, file);
        }, 100);
      },
    },
    colProps: { span: 12 },
  },
];