<template>
  <BasicModal
    width="1200px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :useWrapper="true"
    :minHeight="500"
    :maxHeight="600"
  >
    <div style="height: 50vh">
      <!-- <div class="text-center text-black text-2xl">
        <a-typography-title style="font-size: 16px;">流域基础信息</a-typography-title>
        <a-menu v-model:selectedKeys="current" mode="horizontal" @click="menuClick">
          <a-menu-item key="mail1"> 基础信息 </a-menu-item>
          <a-menu-item key="mail2"> 版本信息 </a-menu-item>
        </a-menu>
      </div> -->
      <a-tabs v-model:activeKey="activeKey" class="res-a-tabs">
        <a-tab-pane key="1" tab="基本信息">
          <BasicForm @register="registerForm" v-if="show1">
            <template #upload>
              <a-upload
                name="file"
                :multiple="true"
                :fileList="fileList"
                action=""
                :showUploadList="true"
                :customRequest="() => {}"
              >
                <a-button type="primary">
                  <upload-outlined></upload-outlined>
                  选择文件
                </a-button>
                <span style="font-size: 14px; margin-left: 10px"
                  >支持上传png、jpeg、gif、tif、doc、xls、pdf等格式文件</span
                >
              </a-upload>
            </template>
            <template #upload-table>
              <upload-file-list :fileList="fileList"></upload-file-list>
            </template>
          </BasicForm>
        </a-tab-pane>
        <a-tab-pane key="2" tab="流程信息">
          <FlowStep :flowTitle="'文件资源上传流程信息'" :flowCode="'20220523001'"></FlowStep>
        </a-tab-pane>
      </a-tabs>
    </div>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref, reactive, onMounted, watch } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { accountFormSchema, accountFormSchema2 } from './fileUploadData';
import { cloneDeep } from 'lodash-es';
import { message, Upload } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { TOption } from '/@/views/rule/linkedge/config/config.data';
import { PlusOutlined } from '@ant-design/icons-vue';
import { addFileResource } from '../../api/fileUploadApi';
import UploadFileList from './uploadFileList.vue';
import FlowStep from '../flowStep/index.vue';

export default defineComponent({
  name: 'AccountModal',
  components: {
    BasicModal,
    BasicForm,
    Upload,
    PlusOutlined,
    UploadFileList,
    FlowStep,
  },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    let show1 = ref(true);
    const activeKey = ref('1');
    const current = ref(['mail1']);
    const tenantLogo = ref('');
    const loading = ref(false);
    const roleOptions = ref<TOption[]>([]);
    const isUpdate = ref(true);
    const rowId = ref('');
    const postData = reactive({});
    const fileList = [];
    onMounted(async () => {});

    const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
      labelWidth: 100,
      schemas: show1 ? accountFormSchema : accountFormSchema2,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 18,
      },
    });

    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      if (unref(isUpdate)) {
        rowId.value = data.record.id;
        setFieldsValue(data.record);
      }
    });
    const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    watch(
      () => fileList,
      (op) => {
        console.log('文件改变', op);
      }
    );
    async function handleSubmit() {
      setModalProps({ confirmLoading: true });
      try {
        const { createMessage } = useMessage();
        const values = await validate(['parentId']);
        Object.assign(postData, values);

        console.log('准备传递的参数' + JSON.stringify(postData));

        await addFileResource(paramsToFormData(postData as any), unref(isUpdate));
        closeModal();
        emit('success');
        createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
      } finally {
        setTimeout(() => {
          setModalProps({ confirmLoading: false });
        }, 300);
      }
    }
    // async function customUpload({ file }) {
    //   if (beforeUpload(file)) {
    //     tenantLogo.value = '';
    //     loading.value = true;
    //     const formData = new FormData();
    //     formData.append('file', file);
    //     const response = await upload(formData);
    //     if (response.fileStaticUri) {
    //       tenantLogo.value = response.fileStaticUri;
    //       loading.value = false;
    //     }
    //   }
    // }
    // const beforeUpload = (file: FileItem) => {
    //   const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    //   if (!isJpgOrPng) {
    //     message.error('只能上传图片文件!');
    //   }
    //   const isLt2M = (file.size as number) / 1024 / 1024 < 5;
    //   if (!isLt2M) {
    //     message.error('图片大小不能超过5MB!');
    //   }
    //   return isJpgOrPng && isLt2M;
    // };
    function preProcessData(data) {
      Object.keys(data).forEach((item) => {
        if (typeof data[item] === 'undefined' || data[item] === null || data[item] === '') {
          delete data[item];
        }
      });
      return data;
    }

    function paramsToFormData(obj) {
      const data = preProcessData(obj);
      const formData = new FormData();
      Object.keys(data).forEach((key) => {
        if (data[key] instanceof Array) {
          data[key].forEach((item) => {
            formData.append(key, item);
          });
          return;
        }
        formData.append(key, obj[key]);
      });
      return formData;
    }

    // 菜单点击事件
    const menuClick = async (value) => {
      if (value.key == 'mail1') {
        show1.value = true;
      } else {
        show1.value = false;
      }
      await resetFields();
    };

    return {
      current,
      activeKey,
      registerModal,
      registerForm,
      handleSubmit,
      getTitle,
      roleOptions,
      // customUpload,
      // beforeUpload,
      tenantLogo,
      loading,
      menuClick,
      show1,
      fileList,
    };
  },
});
</script>
<style scoped lang="less">
:deep(.vben-basic-tree) {
  width: 100% !important;
}

:deep(.is-unflod) {
  display: none !important;
}

:deep(.is-flod) {
  display: none !important;
}

:deep(.ant-menu-item-selected) {
  background: #ffffff !important;
  color: #231e1e !important;
  height: 46px !important;
  border-radius: 35px !important;
  line-height: 46px !important;
}
</style>
