<template>
  <div ref="mod">
    <a-modal
      :get-container="() => $refs.mod"
      :open="open"
      :title="title"
      :mask-closable="false"
      @cancel="cancel"
      :footer="null"
    >
      <div class="body">
        <a-form
          v-if="props.type === 'tenant'"
          ref="formRef"
          :model="formState"
          :label-col="{ style: { width: '100px' } }"
        >
          <a-form-item
            label="小区名称"
            name="tenantName"
            :rules="[{ required: true, message: '请输入小区名称' }]"
          >
            <a-input
              v-model:value.trim="formState.tenantName"
              placeholder="请输入小区名称，如：天鹅湖畔（南区）"
              :maxlength="300"
              show-count
              allow-clear
            >
              <template #suffix>
                <a-tooltip title="建议添加标识，如: 南区、金寨路">
                  <info-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
                </a-tooltip>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item
            label="租户类型"
            name="tenantType"
            :rules="[{ required: true, message: '请选择租户类型' }]"
          >
            <a-select
              v-model:value="formState.tenantType"
              :options="dictList"
              placeholder="请选择租户类型"
            ></a-select>
          </a-form-item>

          <a-form-item
            label="归属省份"
            name="pcdCodes"
            :rules="[{ required: true, message: '请选择归属省份' }]"
          >
            <pcd-cascader
              v-model:value="formState.pcdCodes"
              v-model:values="formState.pcdStrs"
              placeholder="请选择归属省份"
            ></pcd-cascader>
          </a-form-item>

          <a-form-item
            label="详细地址"
            name="address"
            :rules="[{ required: true, message: '请输入详细地址' }]"
          >
            <a-input v-model:value.trim="formState.address" placeholder="请输入详细地址" />
          </a-form-item>

          <a-form-item label="其他备注" name="remark">
            <a-input v-model:value.trim="formState.remark" placeholder="请输入其他备注" />
          </a-form-item>
        </a-form>

        <a-form
          v-if="props.type === 'admin'"
          ref="adminFormRef"
          :model="adminFormState"
          :label-col="{ style: { width: '120px' } }"
        >
          <a-form-item
            label="管理员角色"
            name="roleId"
            :rules="[{ required: true, message: '请选择管理员角色' }]"
          >
            <a-select
              v-model:value="adminFormState.roleId"
              :options="roleList"
              placeholder="请选择管理员角色"
              :disabled="!isEditAdminForm"
            ></a-select>
          </a-form-item>

          <a-form-item
            label="管理员账号"
            name="account"
            :rules="[{ required: true, message: '请输入管理员账号' }]"
          >
            <a-input
              v-model:value.trim="adminFormState.account"
              placeholder="请输入管理员账号"
              :disabled="!isEditAdminForm"
            />
          </a-form-item>

          <a-form-item
            v-if="isEditAdminForm"
            label="管理员密码"
            name="password"
            :rules="[{ required: true, message: '请输入管理员密码' }]"
          >
            <a-input-password
              v-model:value.trim="adminFormState.password"
              placeholder="请输入管理员密码"
              :disabled="!isEditAdminForm"
            />
          </a-form-item>

          <a-form-item label="管理员电话">
            <a-input
              v-model:value.trim="adminFormState.phone"
              placeholder="请输入管理员电话"
              :disabled="!isEditAdminForm"
            />
          </a-form-item>
        </a-form>
      </div>

      <div class="footer">
        <a-button v-if="!isEditAdminForm" type="primary" @click="isEditAdminForm = true"
          >编辑</a-button
        >
        <a-space v-else>
          <a-button @click="cancel">取消</a-button>
          <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
        </a-space>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { message, type FormInstance } from 'ant-design-vue'
import * as tenantApi from '@/api/tenant'
import pcdCascader from '../pcdCascader/index.vue'
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import { pinyin } from 'pinyin-pro'
import * as systemApi from '@/api/system'
import { useDict } from '@/hooks/useDict'

defineOptions({
  name: 'addCommunity',
})

const formRef = ref<FormInstance>()
const adminFormRef = ref<FormInstance>()

type Props = {
  open: boolean
  title: string
  type: 'tenant' | 'admin' // 添加编辑类型：租户、管理员
  data?: Partial<FormState | AdminFormState>
}
const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'success', value: void): void
}>()

const props = withDefaults(defineProps<Props>(), {
  open: false,
  title: '',
  type: 'tenant',
  data: () => ({
    tenantId: '',
    tenantName: '',
    tenantType: null,
    pcdCodes: [],
    pcdStrs: [],
    address: '',
    remark: '',
    adminName: '',
    adminPhone: '',
    adminNotes: '',
  }),
})

interface FormState {
  tenantId: number | string // 租户ID 有就是更新,没有就是新增
  tenantName: string // 小区名称
  tenantType: string | null // 租户类型
  pcdCodes: string[] // 归属省份
  pcdStrs: string[] // 归属省份str
  address: string // 详细地址
  remark: string // 其他备注
}

const formState = reactive<FormState>({
  tenantId: '',
  tenantName: '',
  tenantType: null,
  pcdCodes: [],
  pcdStrs: [],
  address: '',
  remark: '',
})

interface AdminFormState {
  account: string // 管理员账号
  password: string // 管理员密码
  phone?: string // 管理员电话
  roleId: string | null // 管理员角色
  tenantId?: string | number
  userId?: string | number // 主键id, 有就是更新,没有就是新增
}

const adminFormState = reactive<AdminFormState>({
  account: '',
  password: '',
  phone: '',
  roleId: null,
  tenantId: '',
  userId: '',
})

watch(
  () => props.open,
  (val) => {
    if (val) {
      console.log('PROPS', props)
      fetchDict()
      if (Object.keys(props.data).length !== 0) {
        if (props.type === 'tenant') {
          Object.assign(formState, props.data)
          // 处理省市区转换， ['34,安徽省'] > ['34']
          formState.pcdCodes = formState.pcdStrs.map((item) => {
            const code = item.split(',')[0]
            return code
          })
          console.log('props.type === tenant', formState)
        }
        if (props.type === 'admin') {
          Object.assign(adminFormState, props.data)
          console.log('props.type === admin', adminFormState)
          fetchAdminInfo()
        }
      } else {
        resetState()
      }
    }
  }
)

// 重置表单数据
const resetState = () => {
  formState.tenantName = ''
  formState.tenantId = ''
  formState.tenantType = null
  formState.pcdCodes = []
  formState.pcdStrs = []
  formState.address = ''
  formState.remark = ''
  adminFormState.account = ''
  adminFormState.password = ''
  adminFormState.phone = ''
  adminFormState.roleId = null
}

const { dictList, fetchDict } = useDict('institution_type')

const roleList = ref<{ label: string; value: string }[]>([])
// 查询角色下拉列表
const fetchRoleList = async () => {
  try {
    const res = await systemApi.queryRoleList()
    console.log('获取角色列表成功', res)
    const data = res.data
    roleList.value =
      (Array.isArray(data) &&
        data.map((item) => ({
          label: item.roleName,
          value: item.roleId,
        }))) ||
      []
  } catch (err) {
    console.log('获取角色列表失败', err)
  }
}
fetchRoleList()

const isEditAdminForm = ref<boolean>(true) // 管理员表单模式：查看、编辑
// 查询是否存在管理员信息
const fetchAdminInfo = async () => {
  try {
    const res = await tenantApi.queryTenantAdminInfo({
      tenantId: adminFormState.tenantId || '',
    })
    console.log('获取角色列表成功', res)
    const data = res.data
    isEditAdminForm.value = data === null ? true : false
    if (data) {
      adminFormState.account = data.account
      adminFormState.password = data.password
      adminFormState.phone = data.phone
      adminFormState.roleId = data.userRole && data.userRole.roleId
      adminFormState.userId = data.userId
    }
  } catch (err) {
    console.log('获取角色列表失败', err)
  }
}

// 关闭弹窗
const cancel = () => {
  formRef?.value?.resetFields()
  adminFormRef?.value?.resetFields()
  resetState()
  emit('update:open', false)
}

// 添加小区
const addCommunity = async () => {
  try {
    const tenantCodes = pinyin(formState.tenantName, { toneType: 'none', type: 'array' })
      .map((word) => word.charAt(0))
      .join('')
    const res = await tenantApi.queryTenantAdd({
      tenantId: formState.tenantId || '',
      tenantCode: tenantCodes,
      tenantName: formState.tenantName,
      tenantType: formState.tenantType! || '', // 'residential_property'
      province: formState.pcdStrs[0] || '',
      city: formState.pcdStrs[1] || '',
      district: formState.pcdStrs[2] || '',
      address: formState.address,
      remark: formState.remark,
    })
    console.log('添加小区成功', res)
    submitLoading.value = false
    message.success('添加成功')
    emit('success')
    cancel()
  } catch (err) {
    console.log('添加小区失败', err)
    submitLoading.value = false
  }
}

// 添加管理员
const addAdmin = async () => {
  try {
    const res = await tenantApi.queryTenantAddAdmin({
      account: adminFormState.account,
      password: adminFormState.password,
      phone: adminFormState.phone,
      roleId: adminFormState.roleId || '',
      tenantId: adminFormState.tenantId || '',
      userId: adminFormState.userId || null,
    })
    console.log('添加管理员成功', res)
    submitLoading.value = false
    message.success('添加成功')
    emit('success')
    cancel()
  } catch (err) {
    console.log('添加管理员失败', err)
    submitLoading.value = false
  }
}

const submitLoading = ref(false)
// 确定保存
const submit = () => {
  if (props.type === 'tenant') {
    formRef?.value
      ?.validate()
      .then(() => {
        console.log('校验通过', formState)
        submitLoading.value = true
        addCommunity()
      })
      .catch((err) => {
        console.log('校验失败', err)
      })
  }
  if (props.type === 'admin') {
    adminFormRef?.value
      ?.validate()
      .then(() => {
        console.log('校验通过', adminFormState)
        submitLoading.value = true
        addAdmin()
      })
      .catch((err) => {
        console.log('校验失败', err)
      })
  }
}
</script>

<style scoped lang="less">
:deep(.ant-modal) {
  .body {
    padding: 24px 0;
  }
  .footer {
    text-align: right;
  }
}
</style>
