<template>
  <el-dialog v-model.trim="addShow" :title="title" width="30%" draggable :close-on-click-modal="false">
    <el-form :model="form" ref="ruleFormRef" label-width="102px" :rules="formRules" style="padding: 0 80px 0px 0;">
      <el-form-item label="企业类型：" prop="name">
        <el-input v-model.trim="form.name" placeholder="请输入企业类型" clearable maxlength="30" />
      </el-form-item>
      <el-form-item label="是否启用：" prop="status">
        <el-switch v-model.trim="form.status" :before-change="beforeChange" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelFn">取消</el-button>
        <el-button type="primary" @click="publishFn">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { apiAddOrUpdateCompanyType } from "http/api/enterprise"

const emits = defineEmits(['send'])
const addShow = ref(false)
let title = ref("新增")
const ruleFormRef: any = ref()
const form = reactive({
  name: '',
  status: false
})
let editId = ""
// const validatorLink = (rule: any, value: any, callback: any) => {
//   if (linkReg.test(value)) {
//     callback()
//   } else {
//     callback(new Error("请输入正确格式的跳转链接"))
//   }
// }
const formRules = reactive<FormRules<any>>({
  name: [
    { required: true, message: '请输入企业类型', trigger: 'blur' },
  ],


})

const publishFn = () => {
  if (!ruleFormRef) return
  ruleFormRef.value.validate(async (valid: any) => {
    if (valid) {
      const params = {
        name: form.name,
        status: form.status ? '1' : '0',
        id:editId
      }
      const res = await apiAddOrUpdateCompanyType(params)
      console.log("res-apiAddOrUpdateCompanyType", res)

      let tipMessage = title.value + "成功"
      addShow.value = false
      ElMessage({
        type: 'success',
        message: tipMessage
      })
      emits("send")
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const cancelFn = (formEl: FormInstance | undefined) => {
  if (!ruleFormRef) return
  ruleFormRef.value.resetFields()
  addShow.value = false
}

const beforeChange = (ev: any) => {
  return new Promise((resolve, reject) => {
    resolve(true)
  })

}



const open = (val: any) => {
  title.value = "新增"
  addShow.value = true
}

const edit = (val:any) => {
  title.value = "编辑"
  addShow.value = true
  form.name = val.name
  form.status=val.status=='1' ?true : false
  editId=val.id
}

defineExpose({
  open,
  edit
})

</script>

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