<template>
  <Dialog v-model="dialogVisible" max-height="620px" :title="dialogTitle" scroll>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="上级机构" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="deptTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择上级机构"
          value-key="deptId"
        />
      </el-form-item>
      <el-form-item label="机构名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入机构名称" maxlength="60" />
      </el-form-item>
      <el-form-item label="原机构名称"  prop="originalName" >
        <el-input v-model="formData.originalName" placeholder="请输入原机构名称" maxlength="60" />
      </el-form-item>
      <el-form-item label="机构编码"  v-if="formData.id != undefined" prop="code"  >
        <el-input v-model="formData.code" placeholder="请输入编码" maxlength="30" disabled/>
      </el-form-item>
      <el-form-item label="原机构编码"  prop="originalCode" >
        <el-input v-model="formData.originalCode" placeholder="请输入原机构编码" maxlength="30" />
      </el-form-item>
      <el-form-item label="所在地" prop="areaId">
        <el-tree-select
          v-model="formData.areaId"
          :data="areaList"
          :props="customerProps"
          :render-after-expand="true"
        />
      </el-form-item>
      <el-form-item label="详细地址"  prop="address" >
        <el-input v-model="formData.address" placeholder="请输入详细地址" maxlength="100" />
      </el-form-item>
      <el-form-item label="机构别名"  prop="aliasName" >
        <el-input v-model="formData.aliasName" placeholder="请输入机构别名" maxlength="30" />
      </el-form-item>
      <el-form-item label="机构其他别名"  prop="aliasName" >
        <el-input v-model="formData.aliasNameOther" placeholder="请输入机构别名" maxlength="30" />
      </el-form-item>
<!--      <el-form-item label="原机构编码"  prop="originalCode" >-->
<!--        <el-input v-model="formData.originalCode" placeholder="请输入原机构编码" maxlength="30" />-->
<!--      </el-form-item>-->
      <el-form-item label="品牌名称" prop="brand">
        <el-select v-model="formData.brand" multiple clearable placeholder="请选择品牌名称">
          <el-option
            v-for="dict in brandOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机构性质" prop="propertypes">
        <el-select v-model="formData.propertypes" multiple clearable placeholder="请选择机构性质">
          <el-option
            v-for="dict in propertypesOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="已上系统" prop="applySystems">
        <el-select v-model="formData.applySystems" multiple clearable placeholder="请选择已上系统">
          <el-option
            v-for="dict in applySystemOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="经营方式" prop="businessPattern">
        <el-select v-model="formData.businessPattern" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in businessPatternOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="营业状态" prop="businessStatus">
        <el-select v-model="formData.businessStatus" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in businessStatusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支持BI" prop="supportBi">
        <el-select v-model="formData.supportBi" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in supportBiOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


<!--      <el-form-item label="显示排序" prop="sort">-->
<!--        <el-input-number v-model="formData.sort" :min="0" controls-position="right" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="负责人" prop="leaderUserId">-->
<!--        <el-select v-model="formData.leaderUserId" clearable placeholder="请输入负责人">-->
<!--          <el-option-->
<!--            v-for="item in userList"-->
<!--            :key="item.id"-->
<!--            :label="item.nickname"-->
<!--            :value="item.id"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="负责人" prop="leaderUserName">
        <el-input v-model="formData.leaderUserName" maxlength="30" placeholder="请输入负责人"  />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="formData.phone" maxlength="11" placeholder="请输入联系电话"  />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import * as AreaApi from '@/api/system/area'
import { CommonStatusEnum } from '@/utils/constants'
import { FormRules } from 'element-plus'

defineOptions({ name: 'SystemDeptForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const areaList = ref([]) // 地区列表

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: '',
  parentId: undefined,
  name: undefined,
  code: undefined,
  sort: undefined,
  leaderUserId: undefined,
  leaderUserName: undefined,
  phone: undefined,
  email: undefined,
  supportBi: 1,
  businessStatus: 1,
  businessPattern: 1,
  applySystems: [],
  propertypes: [],
  brand: [],
  aliasNameOther: undefined,
  aliasName: undefined,
  originalName: undefined,
  originalCode: undefined,
  status: CommonStatusEnum.ENABLE
})
const formRules = reactive<FormRules>({
  parentId: [{ required: true, message: '上级机构不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '机构名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '机构编码不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  areaId: [{ required: true, message: '所在地不能为空', trigger: 'blur' }],
  supportBi: [{ required: true, message: 'BI支持不能为空', trigger: 'blur' }],
  businessStatus: [{ required: true, message: '营业状态不能为空', trigger: 'blur' }],
  businessPattern: [{ required: true, message: '经营方式不能为空', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
  phone: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const deptTree = ref() // 树形结构
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeptApi.getDept(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得用户列表
  userList.value = await UserApi.getSimpleUserList()
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
  // 获得部门树
  await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeptApi.DeptVO
    if (formType.value === 'create') {
      await DeptApi.createDept(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeptApi.updateDept(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: '',
    parentId: undefined,
    name: undefined,
    code: undefined,
    sort: undefined,
    leaderUserId: undefined,
    leaderUserName: undefined,
    phone: undefined,
    email: undefined,
    supportBi: 1,
    businessStatus: 1,
    businessPattern: 1,
    applySystems: [],
    propertypes: [],
    brand: [],
    aliasNameOther: undefined,
    aliasName: undefined,
    originalName: undefined,
    originalCode: undefined,
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
}

/** 获得部门树 */
const getTree = async () => {
  deptTree.value = []
  const data = await DeptApi.getSimpleDeptList()
  let dept: Tree = { id: 0, name: '顶级机构', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}

const customerProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
}
const brandOptions = [
  {
    value: 1,
    label: '恒颐汇',
  },
  {
    value: 2,
    label: '楠山有约',
  },
  {
    value: 3,
    label: '萱悦庭',
  },
  {
    value: 4,
    label: '社区站点',
  },

]

const propertypesOptions = [
  {
    value: 1,
    label: '机构',
  },
  {
    value: 2,
    label: '旅居',
  },
  {
    value: 3,
    label: '站点',
  }
]
const applySystemOptions = [
  {
    value: 1,
    label: '机构系统',
  },
  {
    value: 2,
    label: '旅居系统',
  },
  {
    value: 3,
    label: '旅居系统-小程序核销端',
  }
]
const businessPatternOptions = [
  {
    value: 1,
    label: '自建自营',
  },
  {
    value: 2,
    label: '合作项目',
  },
  {
    value: 3,
    label: '委托运营',
  }
]
const businessStatusOptions = [
  {
    value: 0,
    label: '在营',
  },
  {
    value: 1,
    label: '未开业',
  }
]
const supportBiOptions = [
  {
    value: 0,
    label: '是',
  },
  {
    value: 1,
    label: '否',
  }
]

</script>
