<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10vh"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="140px"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formModel.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-input v-model="formModel.province" placeholder="请输入省份" />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="formModel.city" placeholder="请输入城市" />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formModel.address" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item
        v-if="props.statusInfo?.doubleTrack"
        label="开启双评轨迹"
        prop="doubleTrack"
      >
        <el-switch v-model="formModel.doubleTrack" />
      </el-form-item>
      <el-form-item
        v-if="props.statusInfo?.groupDeleteWarn"
        label="删除分组授权码"
        prop="groupDeleteCheck"
      >
        <el-switch v-model="formModel.groupDeleteCheck" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formModel.description"
          type="textarea"
          placeholder="请输入描述"
          :maxlength="999"
        />
      </el-form-item>
      <el-form-item label="AccessKey">
        <el-input :value="formModel.accessKey" readonly disabled />
      </el-form-item>
      <el-form-item label="AccessSecret">
        <el-input :value="formModel.accessSecret" readonly disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import type { SchoolItem, SchoolStatusInfo } from '@/api/types/admin';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objAssign, objModifyAssign } from '@/utils/utils';
  import { updateSchool } from '@/api/admin';

  defineOptions({
    name: 'ModifySchool',
  });

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  interface Props {
    rowData: SchoolItem;
    statusInfo: SchoolStatusInfo;
  }

  const props = withDefaults(defineProps<Props>(), {
    rowData: {} as SchoolItem,
    statusInfo: {} as SchoolStatusInfo,
  });
  const emit = defineEmits(['modified']);

  const isEdit = computed(() => !!props.rowData?.id);
  const title = computed(() => `${isEdit.value ? '编辑' : '新增'}学校`);

  const formRef = ref<FormInstance>();
  const initialFormState: Partial<SchoolItem> = {
    name: '',
    province: '',
    city: '',
    address: '',
    doubleTrack: false,
    groupDeleteCheck: false,
    description: '',
    accessKey: '',
    accessSecret: '',
  };

  const formModel = reactive({ ...initialFormState });

  const rules: FormRules<keyof SchoolItem> = {
    name: [{ required: true, message: '请输入名称', trigger: 'change' }],
    province: [
      { required: false, message: '最多50字符', max: 50, trigger: 'change' },
    ],
    city: [
      { required: false, message: '最多50字符', max: 50, trigger: 'change' },
    ],
  };

  const handleClose = () => {
    formRef.value?.resetFields();
  };

  /* confirm */
  const { loading, setLoading } = useLoading();
  async function confirm() {
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    setLoading(true);
    const datas = objAssign(formModel, {});
    let res = true;
    await updateSchool(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    ElMessage.success('修改成功！');
    emit('modified', datas);
    close();
  }

  /* init modal */
  function modalBeforeOpen() {
    if (props.rowData.id) {
      objModifyAssign(formModel, props.rowData);
    } else {
      objModifyAssign(formModel, initialFormState);
    }
  }
</script>
