<script setup lang="ts">
import type { Label } from '../types'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { updateStatusRuleList, dateUnitList, weekList, labelList } from '@/utils/dictionary'
import { createLabel, updateLabel } from '../api'
import { useLabelType } from '../composables/useLabelType'
import { pick } from 'lodash-es'

const props = defineProps<{
  data?: Label
}>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const isUpdate = $computed(() => !!props.data?.id)
const title = $computed(() => (isUpdate ? '修改标签' : '新建标签'))

const { typeList } = useLabelType()

const formRef = $ref<FormInstance>()
const form = reactive({
  id: '',
  name: '',
  type_id: '',
  update_status: '2',
  update_rule: { type: 1, info: 1 },
  status: '1',
  label: '',
  weight: 0
})
watchEffect(() => {
  if (props.data) {
    let updateRule = { type: 1, info: 1 }
    try {
      updateRule = JSON.parse(props.data.update_rule)
    } catch (error) {
      console.log(error)
    }
    Object.assign(form, props.data, { update_rule: updateRule, weight: parseFloat(props.data.weight) })
  }
})

const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入标签名称' }],
  label: [{ required: true, message: '请选择标签类型' }],
  type_id: [{ required: true, message: '请选择标签目录' }],
  update_status: [{ required: true, message: '请选择更新评率' }]
})

// 提交
function handleSubmit() {
  formRef?.validate().then(() => (isUpdate ? handleUpdate() : handleCreate()))
}
// 新建
function handleCreate() {
  const params = pick({ ...form, update_rule: JSON.stringify(form.update_rule) }, [
    'name',
    'type_id',
    'update_status',
    'update_rule',
    'status',
    'label',
    'weight'
  ])
  createLabel(params).then(() => {
    ElMessage({ message: '创建成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
// 修改
function handleUpdate() {
  const params = pick({ ...form, update_rule: JSON.stringify(form.update_rule) }, [
    'id',
    'name',
    'type_id',
    'update_status',
    'update_rule',
    'status',
    'label',
    'weight'
  ])
  updateLabel(params).then(() => {
    ElMessage({ message: '修改成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog :title="title" :close-on-click-modal="false" width="600px" @closed="$emit('update:modelValue', false)">
    <el-form ref="formRef" :model="form" :rules="rules" label-suffix="：" label-width="100px">
      <el-form-item label="标签名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="标签类型" prop="label">
        <el-select v-model="form.label" style="width: 100%" :disabled="isUpdate">
          <el-option v-for="item in labelList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签目录" prop="type_id">
        <el-select v-model="form.type_id" style="width: 100%">
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签权重" prop="weight">
        <el-slider v-model="form.weight" :max="1" :step="0.1" />
      </el-form-item>
      <el-form-item label="更新频率" prop="update_status">
        <el-radio-group v-model="form.update_status">
          <el-radio
            v-for="item in updateStatusRuleList"
            :key="item.value"
            :value="item.value"
            :disabled="item.value === '1'">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
        <div class="update-rule-wrap" v-if="form.update_status === '1'">
          <span>每</span>
          <el-select v-model="form.update_rule.type" placeholder=" " style="width: 60px">
            <el-option
              v-for="item in dateUnitList"
              :key="item.value"
              :label="item.label"
              :value="item.value"></el-option>
          </el-select>
          <template v-if="form.update_rule.type === 1">
            <span>的凌晨更新</span>
          </template>
          <template v-if="form.update_rule.type === 2">
            <span>的</span>
            <el-select v-model="form.update_rule.info" placeholder=" " style="width: 80px">
              <el-option v-for="item in weekList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <span>的凌晨更新</span>
          </template>
          <template v-if="form.update_rule.type === 3">
            <span>第</span>
            <el-select v-model="form.update_rule.info" placeholder=" " style="width: 60px">
              <el-option v-for="item in 6" :key="item" :label="item" :value="item"></el-option>
            </el-select>
            <span>天的凌晨更新</span>
          </template>
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" active-text="生效" active-value="1" inactive-text="失效" inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row justify="center">
        <el-button plain auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" auto-insert-space @click="handleSubmit">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.update-rule-wrap {
  width: 100%;
  .el-select {
    margin: 0 10px;
  }
}
</style>
