<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"
          /><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"
          />
        </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, nextTick } 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')
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' }
  // ]
})

// 省份列表
const provinceTreeList = ref([])
// 市列表
const cityTreeList = ref([])
// 区/县列表
const areaList = ref([])
// 运维人员列表
const userList = ref([])
// 提交按钮loading
const submitLoading = ref(false)
onMounted (async () => {
  await GetProvinceTree()
  await GetUserList()
  if(dialogData.pageType == 'edit') {
    await GetUserDetail()
  }
})
// 获取用户详情
const GetUserDetail = () => {
  getSchoolInfo(dialogData.id).then(res => {
    if(res.code == 200 && res.data) {
      const { data } = res
      if(data.provinceCode) {
        cityTreeList.value = provinceTreeList.value.find(item => item.provinceCode == data.provinceCode).children
      }
      if(data.cityCode) {
        areaList.value = cityTreeList.value.find(item => item.cityCode == data.cityCode).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 => {
    if(res.code == 200 && res.data) {
      const { data } = res
      userList.value = data
    }
  })
}
// 获取省市区树列表
const GetProvinceTree = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    provinceTree().then(res => {
      if(res.code == 200 && res.data) {
        const { data } = res
        provinceTreeList.value = data
        resolve()
      }
    })
  })
}
const fileImageUrl = ref('')
// 选择省份
const handleProvinceChange = (val) => {
  userForm.provinceCode = val
  userForm.provinceName = provinceTreeList.value.find(item => item.provinceCode == val).provinceName
  cityTreeList.value = provinceTreeList.value.find(item => item.provinceCode == val).children
  areaList.value = []
  userForm.cityCode = ''
  userForm.areaCode = ''
}
// 选择市
const handleCityChange = (val) => {
  userForm.cityCode = val
  userForm.cityName = cityTreeList.value.find(item => item.cityCode == val).cityName
  areaList.value = cityTreeList.value.find(item => item.cityCode == val).children
  userForm.areaCode = ''
}
// 选择区/县
const handleAreaChange = (val) => {
  userForm.areaCode = val
  userForm.areaName = areaList.value.find(item => item.districtCode == val).districtName
}
// 上传学校logo
const UploadLogo = (file) => {
  let formData = new FormData();
  formData.append("file", file.file);
  uploadFile(formData).then(res => {
    console.log(res)
    if(res.code == 200 && res.data) {
      const { data } = res
      userForm.image = data.url
    }
  })
}
// 选择运维人员
const handleUserChange = (val) => {
  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, fields) => {
    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)
          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>