<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, ref, nextTick } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'
import { ElButton, ElInput, ElPopconfirm, ElTable, ElTableColumn, ElTag } from 'element-plus'
import { BaseButton } from '@/components/Button'
import AddSeleltOption from './AddSeleltOption.vue'
const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const formSchema = ref<FormSchema[]>([
  {
    field: 'type',
    label: '菜单类型',
    component: 'RadioButton',
    value: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '文本框',
          value: 'Input'
        },
        {
          label: '单选框',
          value: 'RadioGroup'
        },
        {
          label: '文件上传',
          value: 'Upload'
        },
        {
          label: '多选框',
          value: 'CheckboxGroup'
        },
        {
          label: '下拉框',
          value: 'Select'
        },
        {
          label: '日期选择框',
          value: 'DatePicker'
        },
        {
          label: '时间选择框',
          value: 'TimePicker'
        }
      ],
      on: {
        change: async (val: string) => {
          changeType(val)
        }
      }
    }
  },

  {
    field: 'info',
    label: '配置名称',
    value: '',
    component: 'Input',
    componentProps: {
      placeholder: '请输入配置名称'
    }
  },
  {
    field: 'menu_name',
    label: '字段变量',
    value: '',
    component: 'Input',
    componentProps: {
      placeholder: '请输入变量名称'
    }
  },
  {
    field: 'is_store',
    label: '系统',
    component: 'RadioGroup',
    value: 0,
    componentProps: {
      options: [
        {
          label: '总后台',
          value: 0
        },
        {
          label: '门店',
          value: 1
        }
      ]
    }
  },
  {
    field: 'value',
    label: '默认值',
    component: 'Input',
    value: ''
  },

  {
    field: 'upload_type',
    label: '上传类型',
    hidden: true,
    colProps: {
      span: 24
    },
    value: 1,
    component: 'RadioGroup',
    componentProps: {
      placeholder: '请输入配置名称',
      options: [
        {
          label: '单图',
          value: 1
        },
        {
          label: '多图',
          value: 2
        },
        {
          label: '文件',
          value: 3
        }
      ]
    }
  },
  {
    field: 'input_type',
    label: '类型',
    colProps: {
      span: 24
    },
    value: 'text',
    component: 'RadioGroup',
    componentProps: {
      placeholder: '请输入配置名称',
      options: [
        {
          label: '文本框',
          value: 'text'
        },
        {
          label: '数字',
          value: 'number'
        },
        {
          label: '多行文本框',
          value: 'textarea'
        }
      ]
    }
  },
  {
    field: 'required',
    label: '验证规则',
    component: 'CheckboxGroup',
    value: [],
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '必填',
          value: 'required'
        },
        {
          label: '手机号',
          value: 'phone'
        },
        {
          label: '不能有空格',
          value: 'notSpace'
        },
        {
          label: '不能有特殊字符',
          value: 'notSpecialCharacters'
        },
        {
          label: '邮箱',
          value: 'email'
        },
        {
          label: '长度范围',
          value: 'lengthRange'
        }
      ],
      on: {
        change: async (val: string) => {
          changeResult(val)
        }
      }
    }
  },
  {
    field: 'maxlength',
    label: '最长',
    hidden: true,
    value: '',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户输入内容最长字符',
      type: 'number'
    }
  },
  {
    field: 'minlength',
    label: '最短',
    hidden: true,
    value: '',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户输入内容最短字符',
      type: 'number'
    }
  },

  {
    field: 'permissionList',
    label: '默认选项',
    hidden: true,
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => (
          <>
            <BaseButton
              class="m-t-5px"
              type="primary"
              size="small"
              onClick={() => (showDrawer.value = true)}
            >
              添加选项
            </BaseButton>
            <ElTable data={data?.permissionList}>
              <ElTableColumn type="index" prop="id" />
              <ElTableColumn
                prop="label"
                label="名称"
                v-slots={{
                  default: ({ row }: any) =>
                    permissionEditingRow.value && permissionEditingRow.value.id === row.id ? (
                      <ElInput v-model={permissionEditingRow.value.label} size="small" />
                    ) : (
                      <ElTag class="mr-1" key={row.value}>
                        {row.label}
                      </ElTag>
                    )
                }}
              />
              <ElTableColumn
                prop="value"
                label="参数值"
                v-slots={{
                  default: ({ row }: any) =>
                    permissionEditingRow.value && permissionEditingRow.value.id === row.id ? (
                      <ElInput v-model={permissionEditingRow.value.value} size="small" />
                    ) : (
                      <span>{row.value}</span>
                    )
                }}
              />
              <ElTableColumn
                label="操作"
                width="180"
                v-slots={{
                  default: ({ row }: any) =>
                    permissionEditingRow.value && permissionEditingRow.value.id === row.id ? (
                      <ElButton size="small" type="primary" onClick={handleSave}>
                        确定
                      </ElButton>
                    ) : (
                      <>
                        <ElButton size="small" type="primary" onClick={() => handleEdit(row)}>
                          编辑
                        </ElButton>
                        <ElPopconfirm
                          title="Are you sure to delete this?"
                          onConfirm={() => handleClose(row)}
                        >
                          {{
                            reference: () => (
                              <ElButton size="small" type="danger">
                                删除
                              </ElButton>
                            )
                          }}
                        </ElPopconfirm>
                      </>
                    )
                }}
              />
            </ElTable>
          </>
        )
      }
    }
  },
  {
    field: 'sort',
    label: '排序',
    value: '',
    component: 'Input',
    componentProps: {
      placeholder: '请输入排序',
      type: 'number'
    }
  },
  {
    field: 'status',
    label: '状态',
    component: 'Switch',
    value: true
  },
  {
    field: 'desc',
    label: '描述',
    colProps: {
      span: 24
    },
    value: '',
    component: 'Input',
    componentProps: {
      rows: 3,
      type: 'textarea',
      placeholder: '请输入描述内容'
    }
  },
  {
    field: 'config_tab_id',
    label: '配置参数ID',
    value: '',
    hidden: true,
    component: 'Input'
  },
  {
    field: 'id',
    label: 'id',
    value: '',
    hidden: true,
    component: 'Input'
  }
])

const rules = ref({
  info: [required('请填写配置名称')],
  menu_name: [required('请填写字段变量')],
  desc: [required('请填写描述')]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

watch(
  () => props.currentRow,
  async (value) => {
    if (!value) return
    const currentRow = cloneDeep(value)
    setValues(currentRow)
    await nextTick()
    changeType(currentRow.type)
    changeResult(currentRow.required)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
const showDrawer = ref(false)
const permissionEditingRow = ref<any>(null)
const handleClose = async (tag: any) => {
  const formData = await getFormData()
  // 删除对应的权限
  setValues({
    permissionList: formData?.permissionList?.filter((v: any) => v.value !== tag.value)
  })
}
const handleEdit = async (row: any) => {
  // 深拷贝当前行数据到编辑行
  permissionEditingRow.value = { ...row }
}
const handleSave = async () => {
  const formData = await getFormData()
  const index = formData?.permissionList?.findIndex((x) => x.id === permissionEditingRow.value.id)
  if (index !== -1) {
    formData.permissionList[index] = { ...permissionEditingRow.value }
    permissionEditingRow.value = null // 重置编辑状态
  }
}
const confirm = async (data: any) => {
  const formData = await getFormData()
  setValues({
    permissionList: [...(formData?.permissionList || []), data]
  })
}
const changeType = (val: string) => {
  if (val == 'Upload' || val == 'CheckboxGroup') {
    setSchema([
      {
        field: 'value',
        path: 'hidden',
        value: true
      }
    ])
  } else {
    setSchema([
      {
        field: 'value',
        path: 'hidden',
        value: false
      }
    ])
  }

  if (val == 'Select' || val == 'RadioGroup' || val == 'CheckboxGroup') {
    setSchema([
      {
        field: 'permissionList',
        path: 'hidden',
        value: false
      }
    ])
  } else {
    setSchema([
      {
        field: 'permissionList',
        path: 'hidden',
        value: true
      }
    ])
  }
  if (val === 'Input') {
    //显示隐藏部分
    setSchema([
      {
        field: 'input_type',
        path: 'hidden',
        value: false
      },
      {
        field: 'upload_type',
        path: 'hidden',
        value: true
      }
    ])
  } else if (val === 'Upload') {
    //显示隐藏部分
    setSchema([
      {
        field: 'input_type',
        path: 'hidden',
        value: true
      },
      {
        field: 'upload_type',
        path: 'hidden',
        value: false
      }
    ])

    //隐藏显示部分
  } else {
    setSchema([
      {
        field: 'input_type',
        path: 'hidden',
        value: true
      },
      {
        field: 'upload_type',
        path: 'hidden',
        value: true
      }
    ])
  }
}
const changeResult = (val: string) => {
  if (!val) {
    return
  }
  if (val.indexOf('lengthRange') > -1) {
    setSchema([
      {
        field: 'maxlength',
        path: 'hidden',
        value: false
      },
      {
        field: 'minlength',
        path: 'hidden',
        value: false
      }
    ])
  } else {
    setSchema([
      {
        field: 'maxlength',
        path: 'hidden',
        value: true
      },
      {
        field: 'minlength',
        path: 'hidden',
        value: true
      }
    ])
  }
}
</script>

<template>
  <div>
    <Form :rules="rules" @register="formRegister" :schema="formSchema" />
    <AddSeleltOption v-model="showDrawer" @confirm="confirm" />
  </div>
</template>
