<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, ref, onMounted } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'
import { ElInput, ElSwitch, ElTable, ElTableColumn } from 'element-plus'
import { BaseButton } from '@/components/Button'
import { UpImgButtom } from '@/components/UpFile'
import addLevelTesk from './addLevelTesk.vue'
import { levelTaskBase } from '@/api/user'

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

const formSchema = ref<FormSchema[]>([
  {
    field: 'name',
    label: '等级名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入等级名称'
    }
  },
  {
    field: 'grade',
    label: '等级',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'number',
      placeholder: '请输入等级'
    }
  },
  {
    field: 'is_forever',
    label: '是否永久',
    component: 'Switch',
    value: true
  },
  {
    field: 'valid_date',
    label: '有效期',
    value: 0,
    component: 'Input',
    componentProps: {
      type: 'number',
      placeholder: '有效时间(天) 0为永久'
    }
  },

  {
    field: 'is_show',
    label: '是否启用',
    component: 'Switch',
    value: true
  },
  {
    field: 'icon',
    label: '图标',
    value: [],
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入图标'
    },
    formItemProps: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <UpImgButtom v-model={data.icon} />
            </>
          )
        }
      }
    }
  },
  {
    field: 'image',
    label: '背景',
    component: 'Input',
    value: [],
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入背景'
    },
    formItemProps: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <UpImgButtom v-model={data.image} />
            </>
          )
        }
      }
    }
  },
  {
    field: 'explain',
    label: '等级描述',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea',
      placeholder: '请输入等级描述',
      row: 4
    }
  },
  {
    field: 'task',
    label: '等级任务',
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => {
          // console.log(data, 'data')
          return (
            <>
              <BaseButton
                class="m-t-5px"
                type="primary"
                size="small"
                onClick={() => (showDrawer.value = true)}
              >
                添加选项
              </BaseButton>
              <ElTable data={data?.task}>
                <ElTableColumn
                  prop="label"
                  label="名称"
                  v-slots={{
                    default: ({ row }: any) => {
                      if (row.name && taskList.value && taskList.value[row.name]) {
                        const info = taskList.value[row.name].info
                        const list = info.split(/\{%num[0-9]+\%\}/g).filter((item) => item !== '')
                        return (
                          <>
                            {list.map((item, ind) => {
                              console.log(item, 'item')
                              return (
                                <>
                                  {item}
                                  <ElInput
                                    class={'m-l-5px m-r-5px list'}
                                    v-model={row.units[ind].value}
                                  />
                                  {row.units[ind].label}
                                </>
                              )
                            })}
                          </>
                        )
                      } else {
                        return <></>
                      }
                    }
                  }}
                />
                <ElTableColumn
                  prop="label"
                  label="必须完成"
                  width={'100px'}
                  align="center"
                  v-slots={{
                    default: ({ row }: any) => {
                      return (
                        <ElSwitch
                          v-model={row.must}
                          activeValue="1"
                          inactiveValue="0"
                          on-text="是"
                          off-text="否"
                        />
                      )
                    }
                  }}
                />
                <ElTableColumn
                  prop="label"
                  label="操作"
                  fixed="right"
                  width={'100px'}
                  align="center"
                  v-slots={{
                    default: ({ $index }: any) => {
                      return (
                        <>
                          <BaseButton
                            type="danger"
                            link
                            size="small"
                            onClick={() => delTask($index, data)}
                          >
                            删除
                          </BaseButton>{' '}
                        </>
                      )
                    }
                  }}
                />
              </ElTable>
            </>
          )
        }
      }
    }
  },
  {
    field: 'id',
    label: '',
    hidden: true,
    component: 'Input'
  }
])

const rules = ref({
  name: [required('请填写等级名称')],
  grade: [required('请输入等级')],
  explain: [required('请填写等级描述')],
  task: [
    required('请选择最少一个等级任务'),
    {
      validator: (_, val, callback) => {
        if (!val) return callback()
        if (val.length == 0) {
          callback(new Error('请选择最少一个等级任务'))
        } else {
          callback()
        }
      }
    }
  ]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = 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)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
const showDrawer = ref(false)
const checkedLevelTesk = async (res: any) => {
  // console.log(res)
  const formData = await getFormData()
  res.units = res.units.map((item: any) => {
    return {
      key: item.key,
      value: 0,
      label: item.label,
      replace: item.replace
    }
  })
  //默认是否选中
  res.must = true
  setValues({
    task: [...(formData?.task || []), res]
  })
  showDrawer.value = false
}
const delTask = (index: number, data: any) => {
  // console.log(index, data, 'data')
  data.task.splice(index, 1)
  return
}
const taskList = ref({})
const getTaskList = async () => {
  const { data } = await levelTaskBase()
  taskList.value = data
}
</script>

<template>
  <div>
    <Form :rules="rules" @register="formRegister" :schema="formSchema" />
    <addLevelTesk :list="taskList" v-model="showDrawer" @confirm="checkedLevelTesk" />
  </div>
</template>
<style lang="less" scoped>
:deep(.el-table__row) {
  .list {
    width: 50px;
    text-align: center;
  }
}
</style>
