<script setup lang="tsx">
import { watch, ref, reactive } from 'vue'
import { productRule, productRuleValue } from '@/api/goods/types'
import { getProductRuleDetail, putProductRule, addProductRule } from '@/api/goods'
import { ElForm, ElFormItem, ElInput, ElDivider, ElTag, ElMessage } from 'element-plus'
import type { FormRules, FormInstance } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()

const props = defineProps({
  id: {
    type: Number,
    default: 0
  },
  title: {
    type: String,
    default: ''
  }
})
const modelValue = defineModel<boolean>()
const ruleFormRef = ref<FormInstance>()
const submit = async () => {
  if (ruleFormRef.value) {
    const valid = await ruleFormRef.value.validate((valid, fields) => {
      // console.log(fields, 'fields')
      if (!valid) {
        console.log('error submit!', fields)
      }
    })
    if (valid) {
      loadingData.value = true
      try {
        let re: any = {}
        if (form.value.id > 0) {
          re = await putProductRule(form.value)
        } else if (form.value.id == 0) {
          re = await addProductRule(form.value)
        }
        if (re.status == 200) {
          ElMessage({
            showClose: true,
            message: '添加成功',
            type: 'success'
          })
        }
        emit('submit')
      } catch (error) {
        console.log(error)
      } finally {
        loadingData.value = false
      }
    }
  }
}
const loadingData = ref(false)
watch(
  () => props.id,
  async (value) => {
    if (value * 1 === 0) return
    loadingData.value = true
    const res = await getProductRuleDetail(value)
    form.value = res.data
    loadingData.value = false
  },
  {
    deep: true,
    immediate: true
  }
)
const form = ref<productRule>({
  id: 0,
  rule_name: '',
  rule_value: []
})
const rule_type = ref({
  name: '',
  value: ''
})
const addShow = ref(false)
const emit = defineEmits(['submit'])
const rules = reactive<FormRules<productRule>>({
  rule_name: [{ required: true, trigger: 'blur' }],
  rule_value: [
    {
      required: true,
      validator: (_, __, callback: any) => {
        // console.log(2333)
        if (form.value.rule_value.length < 1) {
          ElMessage.error('请添加规格参数')
          return callback(new Error('请添加规格参数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})
const addType = () => {
  form.value.rule_value.push({
    attrHidden: '',
    detail: [rule_type.value.value],
    detailValue: '',
    value: rule_type.value.name
  })
  rule_type.value.name = ''
  rule_type.value.value = ''
  addShow.value = false
}
const handleClose = (name: string, tag: productRuleValue) => {
  tag.detail.splice(tag.detail.indexOf(name), 1)
}
const handleCloseTag = (tag: productRuleValue) => {
  form.value.rule_value.splice(form.value.rule_value.indexOf(tag), 1)
}

const handleInputConfirm = (tag: productRuleValue) => {
  if (tag.detail.indexOf(tag.detailValue) > -1) {
    ElMessage.error('规格参数已存在')
    return
  }
  if (tag.detailValue) {
    tag.detail.push(tag.detailValue)
  }
  tag.attrHidden = ''
  tag.detailValue = ''
}
</script>

<template>
  <Dialog v-model="modelValue" :title="title" width="600px">
    <el-form
      v-loading="loadingData"
      ref="ruleFormRef"
      :model="form"
      label-width="auto"
      :rules="rules"
    >
      <el-form-item
        prop="rule_name"
        label="规格模版名称"
        :rules="[{ required: true, message: '请输入规格名', trigger: 'blur' }]"
      >
        <el-input v-model="form.rule_name" />
      </el-form-item>
      <el-form-item v-show="form.rule_value.length > 0" label="规格参数" prop="rule_value">
        <template v-for="(tag, index) in form.rule_value" :key="index">
          <div class="w-100 mb-10px!">
            <ElTag
              type="info"
              effect="plain"
              class="mr-10px!"
              closable
              @close="handleCloseTag(tag)"
            >
              {{ tag.value }}
            </ElTag>
          </div>
          <ElTag
            class="mr-10px! mb-10px!"
            v-for="(name, ind) in tag.detail"
            :key="ind"
            closable
            @close="handleClose(name, tag)"
          >
            {{ name }}
          </ElTag>
          <el-input
            v-model="tag.detailValue"
            class="w-20! mr-10px! mb-10px!"
            size="small"
            @keyup.enter="handleInputConfirm(tag)"
          />
          <BaseButton type="primary" class="mb-10px!" size="small" @click="handleInputConfirm(tag)">
            添加
          </BaseButton>
        </template>
      </el-form-item>
      <template v-if="addShow">
        <el-form-item label="规格名称">
          <el-input v-model="rule_type.name" />
        </el-form-item>
        <el-form-item label="规格参数">
          <el-input v-model="rule_type.value" />
        </el-form-item>
        <el-form-item>
          <div class="flex flex-justify-end w-100%">
            <BaseButton link type="primary" @click="addType">添加</BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link type="primary" @click="addShow = false">取消</BaseButton>
          </div>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item>
          <BaseButton type="success" @click="addShow = true">添加新规格</BaseButton>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <BaseButton type="primary" :loading="loadingData" @click="submit">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="modelValue = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
