<template>
  <ElForm ref="formRef" :model="formData" :rules="rules" label-width="auto">
    <el-row :gutter="20">
      <el-col>
        <ElFormItem label="食堂名称" prop="name">
          <ElInput style="max-width: 400px" v-model="formData.name" maxlength="20" type="text" />
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="档口数量" prop="stall_num">
          <ElInput style="max-width: 400px" v-model="formData.stall_num" type="number" />
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="是否直营" prop="is_direct">
          <el-select style="max-width: 200px" v-model="formData.is_direct" placeholder="请选择">
            <el-option
              v-for="item in [
                { label: '非直营', value: 0 },
                { label: '直营', value: 1 }
              ]"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="学校（校区）" prop="school_id">
          <ElSelect style="max-width: 200px" v-model="formData.school_id" placeholder="请选择" :empty-values="[0]" :value-on-clear="0">
            <ElOption
              v-for="item in selectList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </ElSelect>
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="餐饮公司" prop="school_id">
          <ElInput style="max-width: 400px" v-model="formData.school_id" type="number" />
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="食堂经理" prop="username">
          <ElInput style="max-width: 400px" v-model="formData.username" maxlength="20" type="text" />
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="手机号" prop="phone">
          <ElInput style="max-width: 400px" v-model="formData.phone" maxlength="20" type="text" />
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="微信号" prop="weixin">
          <ElInput style="max-width: 400px" v-model="formData.weixin" maxlength="20" type="text" />
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="档口照片" prop="tall_imgs">
          <ArtUploadImgs
              :imgs="formData.stall_imgs"
              :limit = "12"
              file-name="canteen"
              :maxSizeMB="3"
              @update:imgs="(value:string[]) => formData.stall_imgs = value"
          />
        </ElFormItem>
      </el-col>
      <el-col>
        <ElFormItem label="备注" prop="memo">
          <ElInput rows="4" v-model="formData.memo" maxlength="255" type="textarea" />
        </ElFormItem>
      </el-col>
      <el-col :span="24">
        <ElFormItem label=" " prop="">
          <ElButton type="primary" @click="handleSubmit">提交</ElButton>
        </ElFormItem>
      </el-col>
    </el-row>
  </ElForm>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import {canteenApi, canteenApi as Api} from '@/api/canteenApi'
  import { onMounted } from 'vue'
  import { router } from '@/router'
  import { ElMessageBox } from 'element-plus'
  import { RoutesAlias } from '@/router/routesAlias'

  // 表单实例
  const formRef = ref<FormInstance>()

  const DefaultData = <Form.Canteen>{
    id: 0,
    school_id: 0,
    name: '',
    stall_num: 0,
    is_direct: 0,
    stall_imgs: [],
    username: '',
    phone: '',
    weixin: '',
    memo: '',
    last_user_id: 0,
    last_user_name: '',
    last_date: ''
  }
  // 表单数据
  const formData = reactive<Form.Canteen>({ ...DefaultData })

  // 表单验证规则
  const rules: FormRules = {
    school_id: [{ required: true, message: '请输入学校ID', trigger: 'blur' }],
    name: [
      { required: true, message: '请输入名称', trigger: 'blur' },
      { max: 20, message: '长度最多20个字符', trigger: 'blur' }
    ],
    stall_num: [{ required: true, message: '请输入档口数量', trigger: 'blur' }],
    username: [
      { required: true, message: '请输入食堂经理', trigger: 'blur' },
      { max: 20, message: '长度最多20个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    weixin: [
      { required: true, message: '请输入微信号', trigger: 'blur' },
      { max: 20, message: '长度最多20个字符', trigger: 'blur' }
    ],
    memo: [{ max: 255, message: '长度最多255个字符', trigger: 'blur' }]
  }

  const route = useRoute()
  let id = 0

  // 初始化表单数据
  const initFormData = () => {
    if (id == 0) {
      Object.assign(formData, DefaultData)
    } else {
      Api.info(id).then((res) => {
        Object.assign(formData, res)
      })
    }
  }

  const selectList = ref<Api.Common.SelectRelationInfo[]>([])
  const getSelectList = async () => {
    await canteenApi.selectList().then(res => {
      selectList.value = res
    })
  }

  onMounted(() => {
    id = route.query.id ? parseInt(route.query.id as string) : 0
    getSelectList()
    initFormData()
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  })

  const afterOk = () => {
    ElMessageBox.confirm('操作成功，是否返回列表', 'Success', {
      confirmButtonText: '返回列表',
      cancelButtonText: '留在此页',
      type: 'info'
    })
      .then(() => {
        router.push({ path: RoutesAlias.CanteenList })
      })
      .catch(() => {
        // ... do nothing
      })
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate((valid) => {
      if (valid) {
        if (id == 0) {
          Api.add(formData).then(() => {
            afterOk()
          })
        } else {
          Api.edit(formData).then(() => {
            afterOk()
          })
        }
      }
    })
  }
</script>