<template>
  <BasicModal width="1200px" v-bind="$attrs" @register="registerModal" @cancel="handleCancel" :title="getTitle"
    @ok="handleSubmit" :useWrapper="true" :minHeight="500">
    <div style="height: 50vh">
      <!-- <BasicForm @register="registerForm">
        <template #title>
          <div class="text-center text-black text-2xl">
            <a-menu v-model:selectedKeys="current" mode="horizontal">
              <a-menu-item key="mail1"> 场景资源信息 </a-menu-item>
              <a-menu-item key="mail2"> 流程信息 </a-menu-item>
            </a-menu>
          </div>
        </template>
        <template #basicinfo>
          <div class="basic-info-title">基础信息</div>
        </template>

        <template #descinfo>
          <div class="basic-info-title">描述信息</div>
        </template>

        <template #upload>
          <a-upload name="file" :multiple="true">
            <a-button type="primary">
              <upload-outlined></upload-outlined>
              文件上传
            </a-button>
            <span style="font-size: 14px; margin-left: 10px"
              >支持上传png、jpeg、gif、tif等格式文件</span
            >
          </a-upload>
        </template>
      </BasicForm> -->

      <a-tabs v-model:activeKey="activeKey" class="res-a-tabs">
        <a-tab-pane key="1" tab="场景资源信息">
          <BasicForm @register="registerForm">
            <template #basicinfo>
              <div class="basic-info-title">基础信息</div>
            </template>

            <template #descinfo>
              <div class="basic-info-title">描述信息</div>
            </template>
            <template #keywords="{ model, field }">
              <a-select mode="multiple" :disabled="isView" allowClear placeholder="请选择资源标签" v-model:value="model[field]"
                :options="serviceTags">
              </a-select>
            </template>
            <template #upload>
              <a-upload id="thumbnail2" name="thumbnail1" :custom-request="customUpload" v-model:file-list="fileList"
                :disabled="isView">
                <a-button style="background-color: #0671dd; color: #fff; border-radius: 4px" :disabled="isView">
                  <upload-outlined></upload-outlined>
                  文件上传
                </a-button>
              </a-upload>
              <span class="updateImg" @click="imgBut" v-if="!isView"></span>
            </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 } from 'vue';
import { serviceTags } from '../sysDic';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { accountFormSchema } from './sceneUploadData';
import { filterRoleList } from '/@/api/system/system';
// import { addDzsbsjjr } from '/@/api/datamanager/groundDisasterId/muSourceData';

import { message, Upload } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
// import { FileItem } from '/@/components/Upload/src/typing';
import { TOption } from '/@/views/rule/linkedge/config/config.data';
import { PlusOutlined } from '@ant-design/icons-vue';
// import { upload } from '/@/api/oss/ossFileUploader';
import FlowStep from '../flowStep/index.vue';
import { addFileResource } from '../../api/fileUploadApi';
import { update, getImgUrl } from '/@/api/dataAdmin/assembly';
import { insertService, updateService } from '/@/api/resource/map';
import { session } from '/@/utils/Memory.js';
import { img } from '/@/api/resource/plat';

export default defineComponent({
  name: 'AccountModal',
  components: {
    BasicModal,
    BasicForm,
    Upload,
    PlusOutlined,
    FlowStep,
  },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    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 serviceid = ref('');
    const postData = reactive({});
    const activeKey = ref('1');
    const getRoleList = async () => {
      const res = await filterRoleList();
      console.log(res);
      roleOptions.value = res.map((m) => {
        return {
          label: m.name,
          value: m.id,
        };
      });
    };
    onMounted(async () => {
      //await getRoleList();   //这个会导致查询失败
    });

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

    function getImg(i) {
      img(i).then(r => {
        if (r && r.length) {
          r.map(i => {
            if (i.thumbnail && i.thumbnail.indexOf(',') > -1) {
              var arr = i.thumbnail.split(',')
              getImgUrl(arr[0], arr[1]).then(res => {
                console.log("tup:", res)
                var name = res.match(/\/([^/]+)\?/)[1];
                fileList.value = [{
                  uid: '1',
                  name: name,
                  status: 'done',
                  url: res,
                }];
              })
            }
          })
        }
      })
    }

    var formData = ref(null);
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      isView.value = !!data?.isView;
      if (unref(isUpdate)) {
        rowId.value = data.record.id;
        serviceid.value = data.record.serviceid;
        setFieldsValue(data.record);
        getImg(data.record.serviceid)
      }
      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;
      }
      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 '新增场景资源'
      }
    });

    var thumbnail = ref('');
    async function handleSubmit() {
      if (isView.value) {
        return closeModal();
      }
      setModalProps({ confirmLoading: true });
      try {
        const { createMessage } = useMessage();
        const values = await validate(); //validate(['parentId']);
        Object.assign(postData, values);
        const userinfo = session.getItem('userInfo');
        let servicebase = Object.assign(values,
          {
            name: values.servicename, // 资源名称
            thumbnail: thumbnail.value, //缩略图名称-------------根据上传的缩略图更新
            workSpace: '', //工作空间
            urlInfo: '', //路径信息
            otherService: '', //其他服务
            bz: '', //备注
            externalApply: '1', //是否申请应用
            publisher: userinfo?.EMPLOYEE?.NAME, //发布者
            username: userinfo?.EMPLOYEE?.NAME, //用户名称
            userid: userinfo?.EMPLOYEE?.EMPLOYEE_ID, //用户id
          });
        let metadata = Object.assign(values,
          {
            thumbnail: thumbnail.value, //缩略图名称-------------根据上传的缩略图更新
            workSpace: '', //工作空间
            urlInfo: '', //路径信息
            otherService: '', //其他服务
            bz: '', //备注
            externalApply: '1', //是否申请应用
            publisher: userinfo?.EMPLOYEE?.NAME, //发布者
            username: userinfo?.EMPLOYEE?.NAME, //用户名称
            userid: userinfo?.EMPLOYEE?.EMPLOYEE_ID, //用户id
          });
        let res = null;
        if (!unref(isUpdate)) {
          let postFormData = {
            type: 'ER',
            servicebase: servicebase,
            metadata: metadata,
          };
          res = await insertService(postFormData);
        } else {
          Object.assign(servicebase, { serviceid: serviceid.value })
          Object.assign(metadata, { serviceid: serviceid.value, id: rowId.value })
          let postFormData = {
            type: 'ER',
            servicebase: servicebase,
            metadata: metadata,
          };
          res = await updateService(postFormData);
        }
        if (res) {
          closeModal();
          emit('success');
          createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
        } else {
          setModalProps({ confirmLoading: false });
        }
      } 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;
    }

    function func(row, label) {
      console.log(row, label);
    }

    var fileList = ref([]);
    function imgBut() {
      if (fileList.value.length) {
        return message.error('只能上传一个文件,请先删除之前的文件！')
      } else if (fileList.value.length == 0) {
        document.getElementById("thumbnail2").click()
      }
    }

    function customUpload({ file, onSuccess, onError }) {
      const formData = new FormData();
      formData.append('file', file);
      update(formData, session.getItem('sysFild').dirId).then(r => {
        if (r && r.resp_code == 0 && r.resp_msg == "OK") {
          thumbnail.value = `${r.datas.id},${r.datas.dirId}`;
          onSuccess()
        } else {
          onError()
        }
      })
    }

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

    return {
      handleCancel,
      fileList,
      imgBut,
      customUpload,
      serviceTags,
      formData,
      isView,
      current,
      activeKey,
      registerModal,
      registerForm,
      handleSubmit,
      getTitle,
      roleOptions,
      // customUpload,
      // beforeUpload,
      tenantLogo,
      loading,
      func,
    };
  },
});
</script>
<style scoped lang="less">
.updateImg {
  top: 0px;
  display: inline-block;
  background-color: rgb(6, 113, 221);
  color: rgb(255, 255, 255);
  border-radius: 4px;
  width: 110px;
  height: 32px;
  position: absolute;
  opacity: 0;
  cursor: pointer;
  z-index: 2;
}

:deep(.vben-basic-tree) {
  width: 100% !important;
}

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

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

.basic-info-title {
  height: 19px;
  line-height: 18px;
  padding-left: 6px;
  margin-left: 20px;
  border-left: 3px solid #0671dd;
  font-family: Source Han Sans CN;
  font-size: 16px;
  font-weight: 350;
  letter-spacing: 0px;
}

:deep(.ant-calendar-picker) {
  width: 100% !important;
}
</style>
