<template>
  <el-dialog v-model="showDialog" :title="dialogData.pageType == 'add' ? '新增用户' : dialogData.pageType == 'edit' ? '编辑用户' : ''" width="600px">
    <el-form :model="userForm" :rules="rules" ref="userFormRef">
      <el-form-item label="学校名称：" :label-width="formLabelWidth" prop="tenantName">
        <el-input v-model="userForm.tenantName" placeholder="请输入学校名称" />
      </el-form-item>
      <el-form-item label="学校简称：" :label-width="formLabelWidth" prop="abbreviation">
        <el-input v-model="userForm.abbreviation" placeholder="请输入学校名称" />
      </el-form-item>
      <el-form-item label="区域：" :label-width="formLabelWidth" required>
        <el-form-item prop="provinceCode">
          <el-select v-model="userForm.provinceCode" placeholder="请选择" @change="handleProvinceChange" style="width: 100px;">
            <el-option
              v-for="province in provinceTreeList || []"
              :key="province.provinceCode"
              :label="province.provinceName"
              :value="province.provinceCode"
            ></el-option>
          </el-select>
          <span class="margin_10">省</span>
        </el-form-item>
        <el-form-item prop="cityCode">
          <el-select v-model="userForm.cityCode" placeholder="请选择" @change="handleCityChange" style="width: 100px;">
            <el-option
              v-for="city in cityTreeList || []"
              :key="city.cityCode"
              :label="city.cityName"
              :value="city.cityCode"
            ></el-option>
          </el-select>
          <span class="margin_10">市</span>
        </el-form-item>
        <el-form-item prop="areaCode">
          <el-select v-model="userForm.areaCode" placeholder="请选择" @change="handleAreaChange" style="width: 100px;">
            <el-option
              v-for="district in areaList || []"
              :key="district.districtCode"
              :label="district.districtName"
              :value="district.districtCode"
            ></el-option>
          </el-select>
          <span class="margin_10">区/县</span>
        </el-form-item>
      </el-form-item>
      <el-form-item label="账号类型：" :label-width="formLabelWidth" prop="schoolType">
        <el-radio-group v-model="userForm.schoolType">
          <el-radio :value="0">单校版</el-radio>
          <el-radio :value="1">联考版</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="用户类型：" :label-width="formLabelWidth" prop="type">
        <el-radio-group v-model="userForm.type">
          <el-radio :value="1">正式用户</el-radio>
          <el-radio :value="0">体验用户</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="学校logo：" :label-width="formLabelWidth">
        <img v-if="userForm.image" :src="userForm.image" alt="" class="file_image">
        <img v-else src="@/assets/school/default_logo.svg" alt="" class="file_image">
        <el-upload :http-request="UploadLogo">
          <el-button size="small" type="primary">{{ userForm.image ? '重新上传' : '上传logo'}}</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="有效时间：" :label-width="formLabelWidth" required>
        <el-form-item prop="startDate">
          <el-date-picker
            v-model="userForm.startDate"
            type="date"
            placeholder="请选择"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledBeforeDate"
            :clearable="dialogData.pageType != 'edit'"
          /><span class="margin_10">至</span>
        </el-form-item>
        <el-form-item prop="endDate">
          <el-date-picker
            v-model="userForm.endDate"
            type="date"
            placeholder="请选择"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledAfterDate"
            :clearable="dialogData.pageType != 'edit'"
          />
        </el-form-item>
      </el-form-item>
      <el-form-item label="运维负责人：" :label-width="formLabelWidth" prop="sysUserId">
        <el-select v-model="userForm.sysUserId" placeholder="请选择" @change="handleUserChange" style="width: 320px;" multiple collapse-tags collapse-tags-tooltip>
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="button_border_gray cancel" @click="showDialog = false">取消</el-button>
      <el-button class="button_background" :loading="submitLoading" @click="SubmitForm(userFormRef)">确定</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts">
export default {
  name: 'AddUser',
}
</script>
<script lang="ts" setup>
import { ref, reactive, inject, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getUserList, addUser, uploadFile, provinceTree, getSchoolInfo, editSchoolInfo } from '@/api/school'
interface DialogData {
  pageType: string
  id: string
}
let showDialog = inject('showDialog')
let dialogData = inject<DialogData>('dialogData', {
  pageType: 'add',
  id: ''
})
const formLabelWidth = '120px'
// 新增用户表单数据定义
interface UserForm {
  id: string
  tenantName: string
  abbreviation: string
  provinceCode: string
  provinceName: string
  cityCode: string
  cityName: string
  areaCode: string
  areaName: string
  schoolType: number
  type: number
  image: string
  startDate: string
  endDate: string
  // selUserList: string[]
  sysUserId: string[]
}
// 新增用户表单数据初始化
const userForm = reactive<UserForm>({
  id: '',
  tenantName: '',
  abbreviation: '',
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  areaCode: '',
  areaName: '',
  schoolType: 0,
  type: 1,
  image: '',
  startDate: '',
  endDate: '',
  // selUserList: [],
  sysUserId: []
})
const userFormRef = ref<FormInstance>()
// 表单校验规则
const rules = reactive<FormRules<UserForm>>({
  tenantName: [
    { required: true, message: '请输入学校名称', trigger: 'blur' }
  ],
  // abbreviation: [
  //   { required: true, message: '请输入学校简称', trigger: 'blur' }
  // ],
  provinceCode: [
    { required: true, message: '请选择省', trigger: 'change' }
  ],
  cityCode: [
    { required: true, message: '请选择市', trigger: 'change' }
  ],
  areaCode: [
    { required: true, message: '请选择区/县', trigger: 'change' }
  ],
  schoolType: [
    { required: true, message: '请选择账号类型', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  // sysUserId: [
  //   { required: true, message: '请选择运维人员', trigger: 'change' }
  // ]
})
interface Province {
  provinceCode: string
  provinceName: string
  children?: City[] // 可选字段
}

interface City {
  cityCode: string
  cityName: string
  children?: District[]
}

interface District {
  districtCode: string
  districtName: string
}
// 省份列表
const provinceTreeList = ref<Province[]>([])
// 市列表
const cityTreeList = ref<City[]>([
  {
    cityCode: '',
    cityName: '',
    children: []
  }
])
// 区/县列表
const areaList = ref<District[]>([
  {
    districtCode: '',
    districtName: ''
  }
])
interface User {
  id: string
  nickname: string
}
// 运维人员列表
const userList = ref<User[]>([])
// 提交按钮loading
const submitLoading = ref(false)
onMounted (async () => {
  await GetProvinceTree()
  await GetUserList()
  if(dialogData.pageType == 'edit') {
    await GetUserDetail()
  }
})
// 获取用户详情
const GetUserDetail = () => {
  getSchoolInfo(dialogData.id).then((res: any) => {
    if(res.code == 200 && res.data) {
      const { data } = res
      if(data.provinceCode) {
        let list = provinceTreeList.value.find(item => item.provinceCode == data.provinceCode)
        cityTreeList.value = list?.children ?? []
      }
      if(data.cityCode) {
        let list = cityTreeList.value.find(item => item.cityCode == data.cityCode)
        areaList.value = list?.children ?? []
      }
      userForm.id = data.id
      userForm.tenantName = data.tenantName
      userForm.abbreviation = data.abbreviation
      userForm.provinceCode = data.provinceCode
      userForm.provinceName = data.provinceName
      userForm.cityCode = data.cityCode
      userForm.cityName = data.cityName
      userForm.areaCode = data.areaCode
      userForm.areaName = data.areaName
      userForm.schoolType = data.schoolType
      userForm.type = data.type
      userForm.image = data.image
      userForm.startDate = data.startDate
      userForm.endDate = data.endDate
      // userForm.selUserList = data.selUserList
      userForm.sysUserId = data.sysUserId
    }
  })
}
// 获取运维人员列表
const GetUserList = () => {
  getUserList({}).then((res: any) => {
    if(res.code == 200 && res.data) {
      const { data } = res
      userList.value = data
    }
  })
}
// 获取省市区树列表
const GetProvinceTree = (): Promise<void> => {
  return new Promise((resolve) => {
    provinceTree().then((res: any) => {
      if(res.code == 200 && res.data) {
        const { data } = res
        provinceTreeList.value = data
        resolve()
      }
    })
  })
}
// 选择省份
const handleProvinceChange = (val: any) => {
  userForm.provinceCode = val
  let name = provinceTreeList.value.find(item => item.provinceCode == val)
  userForm.provinceName = name?.provinceName ?? ''
  let list = provinceTreeList.value.find(item => item.provinceCode == val)
  cityTreeList.value = list?.children ?? []
  areaList.value = []
  userForm.cityCode = ''
  userForm.areaCode = ''
}
// 选择市
const handleCityChange = (val: any) => {
  userForm.cityCode = val
  let city = cityTreeList.value.find(item => item.cityCode == val)
  userForm.cityName = city?.cityName ?? ''
  let list = cityTreeList.value.find(item => item.cityCode == val)
  areaList.value = list?.children ?? []
  userForm.areaCode = ''
}
// 选择区/县
const handleAreaChange = (val: any) => {
  userForm.areaCode = val
  let name = areaList.value.find(item => item.districtCode == val)
  userForm.areaName = name?.districtName ?? ''
}
// 上传学校logo
const UploadLogo = (file: any) => {
  let formData = new FormData();
  formData.append("file", file.file);
  uploadFile(formData).then((res: any) => {
    console.log(res)
    if(res.code == 200 && res.data) {
      const { data } = res
      userForm.image = data.url
    }
  })
}
// 禁用目标日期之后的所有日期
const disabledBeforeDate = (time) => {
  const targetDate = userForm.endDate
  if(!targetDate) return false
  const end = new Date(targetDate)
  end.setHours(23, 59, 59, 999); // 设置为当天最后一刻
  return time.getTime() >= end.getTime();
};
// 禁用目标日期之前的所有日期
const disabledAfterDate = (time) => {
  const targetDate = userForm.startDate
  if(!targetDate) return false
  const start = new Date(targetDate)
  start.setHours(0, 0, 0, 0); // 设置为当天开始
  return time.getTime() <= start.getTime();
};
// 选择运维人员
const handleUserChange = (val: any) => {
  console.log(val)
  let result = userList.value.filter(item => val.includes(item.id)).map(item => {
    return { id: item.id }
  })
  console.log(result)
  // userForm.selUserList = val
  userForm.sysUserId = val
}
const emit = defineEmits(['AddUser'])
// 表单提交
const SubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        let res
        if(dialogData.pageType == 'add') {
          res = await addUser(userForm)
        }else if(dialogData.pageType == 'edit') {
          res = await editSchoolInfo(userForm)
        }
        if (res.code == 200) {
          ElMessage.success(res.msg)
          if(userFormRef.value) {
            userFormRef.value.resetFields()
          }
          emit('AddUser', false)
        } else {
          ElMessage.error(res.msg)
        }
        submitLoading.value = false
      }catch {
        submitLoading.value = false
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.file_image {
  width: 48px;
  height: 48px;
  margin-right: 10px;
  border-radius: 50%;
}
.margin_10 {
  margin: 0 10px;
}
.el-input {
  width: 320px;
}
.el-upload .el-button {
  width: 76px;
  height: 32px;
  background: #2E64FA1A;
  color: #2E64FA;
  border: none;
}
</style>