<template>
  <el-row :gutter="80">
    <el-col :span="10" :offset="0">
      <el-button class="mb-10px" type="primary" @click="handleInsert">新增属性</el-button>
      <el-table :data="tableList" :row-class-name="setRowClass" @row-click="handleRowClick">
        <el-table-column prop="label" label="名称" />
        <el-table-column prop="field" label="属性编码" />
        <el-table-column prop="component" label="类型" width="200px">
          <template #default="{ row }">
            {{ typeOptions.find((it) => it.value == row.component).label }}
          </template>
        </el-table-column>
        <el-table-column label="启用状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="0"
              :inactive-value="1"
              @change="changeStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80px" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text style="padding: 0" @click="remove(row.clueParamId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="14" :offset="0" v-if="tableList.length || formType == 'create'">
      <el-form :model="form" ref="fieldForm" :rules="rules" label-width="100px" :inline="false">
        <el-form-item label="属性名称" prop="label">
          <el-input v-model="form.label" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item prop="field">
          <template #label>
            <div class="flex justify-center" style="align-items: center">
              <span>属性编码</span>
              <Tooltip message="请输入字母或数字，必须以字母开头" />
            </div>
          </template>
          <el-input v-model="form.field" placeholder="请输入属性编码" />
        </el-form-item>
        <el-form-item label="属性类型" prop="component">
          <el-select
            v-model="form.component"
            placeholder="请选择属性类型"
            clearable
            filterable
            style="width: 100%"
            @change="form.options = []"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="['Checkbox', 'Radio', 'Select'].includes(form.component)"
          label="选项"
          prop="options"
          key="options"
        >
          <div>
            <el-button type="primary" @click="handleAddOption"> 新增选项 </el-button>
            <div
              class="flex justify-between mt-10px"
              v-for="(item, index) in form.options"
              :key="index"
            >
              <el-input
                v-model="item.name"
                placeholder="请输入选项内容"
                clearable
                style="width: 300px !important"
                @blur="item.id = item.name"
              />
              <el-button type="primary" text @click="form.options.splice(index, 1)">删除</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="formLoading" @click="onSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup name="FieldProduct">
import * as FieldApi from '@/api/mall/product/productField'
import { getDictOptions } from '@/utils/dict'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const tableList = ref([])
const currentRowId = ref('')

function setRowClass({ row }) {
  return row.field == currentRowId.value ? 'current-row' : ''
}

function handleRowClick(row) {
  formType.value = 'update'
  currentRowId.value = row.field
  form.value = { ...row }
}

const form = ref({
  label: undefined,
  field: '',
  component: undefined,
  options: [],
  status: 0,
  isCustom: true,
  isForm: true,
  isSearch: true,
  isTable: true
})

const loading = ref(false)

const typeOptions = ref([])

const rules = {
  label: { required: true, message: '名称不可为空', trigger: 'blur' },
  field: { required: true, message: '编码不可为空', trigger: 'blur' },
  component: { required: true, message: '类型不可为空', trigger: 'change' }
}

async function getList() {
  loading.value = true
  try {
    const data = await FieldApi.getDiyFieldList()
    tableList.value = data
    if (data.length) {
      handleRowClick(data[0])
    }
  } finally {
    loading.value = false
  }
}

const formType = ref('')

function handleInsert() {
  formType.value = 'create'
  form.value = {
    label: undefined,
    field: '',
    component: undefined,
    options: [],
    status: 0,
    isCustom: true,
    isForm: true,
    isSearch: true,
    isTable: true
  }
}

async function remove(id) {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FieldApi.deleteField(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (err) {
    console.log(err)
  }
}

async function changeStatus(row) {
  try {
    // 二次确认
    await message.confirm('是否确认修改状态')
    await FieldApi.updateFieldStatus(row.clueParamId, row.status)
    message.success('修改成功')
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status = row.status == 0 ? 1 : 0
  }
}

const fieldForm = ref()
const formLoading = ref(false)

function handleAddOption() {
  if (form.value.options) {
    form.value.options.push({})
  } else {
    form.value.options = []
  }
}

async function onSubmit() {
  // 校验表单
  if (!fieldForm.value) return
  const valid = await fieldForm.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await FieldApi.createField(form.value)
      message.success(t('common.createSuccess'))
    } else {
      await FieldApi.updateField(form.value)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    getList()
  } finally {
    formLoading.value = false
  }
}

onMounted(() => {
  typeOptions.value = getDictOptions('attribute_type')
  getList()
})
</script>

<style lang="scss" scoped></style>
