<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    @ok="handleSubmit"
    title="图纸管理"
    width="900px"
    :min-height="600"
    :max-height="1000"
    scrollable
    centered
    :bodyStyle="{ padding: '20px' }"
  >
    <BasicForm @register="register">
      <template #fileupload="{ model, field }">
        <Upload v-model:file-list="model[field]" :maxCount="1" :customRequest="handleCustomUpload">
          <a-button>
            <template #icon><UploadOutlined /></template>
            上传文件
          </a-button>
        </Upload>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script setup lang="ts">
  import { message, Upload } from 'ant-design-vue';
  import { formSchema } from '../cad.data';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import vjmap from 'vjmap';
  import dayjs from 'dayjs';
  import { addMineFile, updateMineFile } from '../cad.api';
  import { useMineDepartmentStore } from '/@/store/modules/mine';
  import { env } from '../env';

  const mineStore = useMineDepartmentStore();

  const emit = defineEmits(['success']);

  const [register, { setFieldsValue, resetFields, validate }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  // 注册模态框并初始化数据
  const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });

    data.deptId = mineStore.findDepart((n) => n.fax === data.mineCode, mineStore.getDepartTree)?.id;
    data.fileAttach = [{ name: data.filePath }];
    resetFields().then(() => setFieldsValue(data));
  });

  async function handleSubmit() {
    const formData = await validate();
    const dept = mineStore.findDepartById(formData.deptId);

    if (!dept || !dept.isLeaf) {
      message.info('请选择具体矿名');
      throw Error('请选择具体矿名');
    }

    setModalProps({ confirmLoading: true });

    formData.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    formData.mineCode = dept.fax;

    if (!formData.id) {
      await addMineFile(formData);
      message.success('新增成功');
    } else {
      await updateMineFile(formData);
      message.success('修改成功');
    }

    emit('success', true);
    closeModal();
  }

  async function handleCustomUpload(options: any) {
    const { file, onSuccess, onError } = options;

    try {
      // 调用上传接口
      const svc = new vjmap.Service(env.serviceUrl, env.accessToken);
      const res = await svc.uploadMap(file);

      setFieldsValue({ wjId: res.fileid, filePath: file.name });
      onSuccess(res);
    } catch (err: any) {
      console.error('上传错误:', err);
      message.error(err.message || '文件上传失败');
      onError(err);
    }
  }
</script>

<style scoped>
  .mine-base-info {
    padding: 12px 16px;
    border: 1px solid #cad2e0;
    border-radius: 5px;
    background-color: #f8f9fc;
  }
</style>
