<template>
  <BasicModal width="1200px" v-bind="$attrs" @register="registerModal" @cancel="handleCancel" :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 :disabled="isView" name="file" :multiple="true" :fileList="fileList" action=""
                :showUploadList="false" :customRequest="() => { }" @change="fileChange">
                <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>
              <div style="height: auto; width: 100%; padding: 0 20px">
                <upload-file-list :isView="isView" ref="imgList" :fileList="fileList"></upload-file-list>
              </div>
            </template>
            <template #roleSlot="{ model, field }">
              <a-select :disabled="isView" mode="multiple" allowClear placeholder="请选择资源标签" v-model:value="model[field]"
                :options="serviceTags">
              </a-select>
            </template>
          </BasicForm>
        </a-tab-pane>
        <a-tab-pane key="2" tab="流程信息" force-render :disabled="!formData || !formData.bussid">
          <FlowStep :flowTitle="'文件资源上传'" :flowCode="'20220523001'" :formData="formData"></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';
import { update } from '/@/api/dataAdmin/assembly';
import { insertFilesService, updateService } from '/@/api/resource/map';
import { session } from '/@/utils/Memory.js';
import { serviceTags } from '../sysDic';

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 isView = ref(false);
    const rowId = ref('');
    const postData = reactive({});
    const fileList = ref([]);
    const serviceid = ref(null);
    const imgList = ref(null)

    const { createMessage } = useMessage();
    onMounted(async () => { });

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

    var formData = ref(null);
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      console.log('文件资源查看某个:', data);
      await resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      isView.value = !!data?.isView;
      //修改
      if (unref(isUpdate)) {
        rowId.value = data.record.id;
        setFieldsValue(data.record);
      }
      setProps({ disabled: isView.value });
      if (isUpdate.value || isView.value) {
        data.record.keywords = data.record.keywords.indexOf('[') > -1 ? JSON.parse(data.record.keywords) : [data.record.keywords];
        formData.value = data.record;
        serviceid.value = data.record.serviceid;
        setFileList(data.record)
      }
      if (!isUpdate.value) formData.value = null;
      activeKey.value = '1';
    });

    //修改标题
    const getTitle = computed(() => {
      if (isUpdate.value && !isView.value) {
        return '编辑文件资源'
      } else if (isView.value) {
        return '查看文件资源'
      } else {
        return '新增文件资源'
      }
    });

    watch(
      () => fileList.value,
      (op) => {
        console.log('文件改变-----', op);
      }
    );

    //获取文件资源列表
    function setFileList(i) {
      fileList.value = [{
        fileId: i.fileid,
        fileName: i.name,
        fileFormat: i.format,
        fileCode: i.servicealiasname,
        thumbnail: i.thumbnail,
        status: '上传成功',
        mapingurl: i.mapingurl,
      }];
    }

    //提交表单
    async function handleSubmit() {
      if (isView.value) {
        return closeModal();
      }
      setModalProps({ confirmLoading: true });
      try {
        const values = await validate();
        Object.assign(postData, values);
        const userinfo = session.getItem('userInfo');
        const validateValue = validateFiles();
        if (!validateValue) {
          createMessage.warning('请维护完整资源编码!');
          return;
        }
        const servicebase = Object.assign(
          {
            name: values.servicename, // 资源名称
            thumbnail: '', //缩略图名称-------------根据上传的缩略图更新
            workSpace: '', //工作空间
            bz: '', //备注
            publisher: userinfo?.EMPLOYEE?.NAME, //发布者
            username: userinfo?.EMPLOYEE?.NAME, //用户名称
            userid: userinfo?.EMPLOYEE?.EMPLOYEE_ID, //用户id
          },
          values
        );
        const metadata = Object.assign(
          {
            thumbnail: '', //缩略图名称-------------根据上传的缩略图更新
            workSpace: '', //工作空间
            publisher: userinfo?.EMPLOYEE?.NAME, //发布者
            username: userinfo?.EMPLOYEE?.NAME, //用户名称
            userid: userinfo?.EMPLOYEE?.EMPLOYEE_ID, //用户id
          },
          values
        );
        let formDataList = [];

        if (unref(isUpdate)) {
          servicebase.serviceid = serviceid.value;
          metadata.serviceid = serviceid.value;
        }

        var dataVersionConf = {
          active: metadata.isnew || servicebase.isnew,
          versionNum: servicebase.versionNum || metadata.versionNum,
          vid: servicebase.vid || metadata.vid
        }
        if (unref(isUpdate)) dataVersionConf.rid = serviceid.value;


        fileList.value.map((item) => {
          var n = {
            name: item['fileName'],
            mapingurl_show: item['fileId'],
            mapingurl: item['fileId'],
            fileId: item['fileId'],
            format: item['fileFormat'],
            servicename: item['fileName'],
            servicealiasname: item['fileCode'],
            fileListUrls: item['fileId'],
            thumbnail: item['thumbnail'],
          };
          let postFormData = {
            type: 'DR',
            servicebase: Object.assign({}, servicebase, n),
            metadata: Object.assign({}, metadata, n),
          };
          if (dataVersionConf) postFormData.dataVersionConf = dataVersionConf;
          formDataList.push(postFormData);
        });
        console.log("文件资源上传参数:", formDataList);
        var type = unref(isUpdate);
        const res = await insertFilesService(type ? formDataList[0] : formDataList, type);
        if (res && res.status === '0') {
          var obj = JSON.parse(res.result);
          if (obj?.errList?.length) {
            var arr = obj.errList.map(i => i.servicebase.servicealiasname);
            message.error(arr.toString() + '等文件资源的编码已经存在！')
          } else {
            handleCancel();
            closeModal();
            emit('success');
            createMessage.success(type ? '修改成功' : '新增成功');
          }
        }
      } 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();
    };

    /**
     * 上传文件
     */
    const fileChange = async (file, files, event) => {
      const formData = new FormData();
      formData.append('file', file.file.originFileObj);
      update(formData, session.getItem('sysFild').dirId).then((r) => {
        if (r && r['resp_code'] === 0) {
          const datas = r['datas'] as any;
          const mapingurl = `${datas.id},${datas.dirId}`;
          const objFile = {
            fileId: datas.id,
            fileName: datas.fileName.split('.')[0], //文件名称
            fileFormat: datas.format, //文件格式
            fileCode: '', //文件编码
            thumbnail: '', //缩略图
            status: '上传成功', //状态
            mapingurl: mapingurl,
            file: file,
          };
          fileList.value.push(objFile);
        } else {
          createMessage.error('文件上传失败!');
        }
      });
    };

    /**
     * 校验文件完整性
     */
    const validateFiles = () => {
      if (fileList.value.length === 0) {
        createMessage.warning('请上传文件');
        return false;
      }
      let flag = true;

      //检查是否维护完整信息
      fileList.value.map((item) => {
        if (item['fileCode'] === '') flag = false;
      });
      return flag;
    };

    function handleCancel() {
      fileList.value = [];
      if (imgList.value) imgList.value.imgListClear();
    }

    return {
      handleCancel,
      isView,
      imgList,
      serviceTags,
      formData,
      createMessage,
      current,
      activeKey,
      registerModal,
      registerForm,
      handleSubmit,
      getTitle,
      roleOptions,
      // customUpload,
      // beforeUpload,
      tenantLogo,
      loading,
      menuClick,
      show1,
      fileList,
      fileChange,
      validateFiles,
    };
  },
});
</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>
