<!-- @format -->

<template>
  <div>
    <page-title :title="editId ? '编辑磁盘' : '创建磁盘'" />
    <a-page-header>
      <template #extra>
        <ns-button @click="navigateBack()">返回</ns-button>
        <ns-button  type="primary" @click="submit"  :disabled="!mainRef?.validateResult">保存</ns-button>
      </template>
    </a-page-header>

    <ns-form
      style="margin-top: 30px; margin-left: 24px"
      ref="mainRef"
      formLayout="修改"
      :schemas="formSchema"
      :model="data"
      v-bind="$attrs" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, watch, computed, inject } from 'vue';
  import { authorizationService } from '/nerv-base/store/modules/authorization-service';
  import { NsMessage } from '/nerv-lib/component/message';
  import { http } from '/nerv-lib/util/http';
  import { useRouter } from 'vue-router';
  export default defineComponent({
    name: 'AppAdd',
    setup() {
      const mainRef = ref();
      const formLayout = 'ns-vertical-form';
      const router = useRouter();
      const data = ref({});
      const event = inject('event');
      const submitData = ref();
      const navigateBack = (type?: string) => {
        const msg = {
          type: type || 'back'
        }
        event.value.source.postMessage(msg, event.value.origin);
      };
      const onEventData = inject('onEventData')
      const eventData = computed(function () {
        return onEventData();
      })
      const params = router.currentRoute.value.params;
      if (params.id) {
        http.get(`/api/iaas/iaas/objs/RA/Volume/${params.id}`).then((res) => {
          initRes.value = res;
          data.value.ID = res.ID;
          data.value.description = res.description;
          data.value.name = res.name;
          data.value.projectName = res.projectName;
        });
      }
      const initRes = ref({});
      const errorItem = ref({});
      function submit() {
        mainRef.value
          .triggerSubmit()
          .then((data) => {
            submitData.value = data
            let objData = {
              alias: data['name'],
              projectID: data['projectID'],
              projectName: data['projectName'],
            }
            // saveData(submitData.value)
            event.value.source.postMessage({type:'getId', data: objData}, event.value.origin);
          })
          .catch(() => ({}));
      }

      function saveData(data){
        initRes.value.alias = data.name;
        initRes.value.RM_UUID = data.RM_UUID;
        initRes.value.projectID = data.projectID;
        initRes.value.projectName = data.projectName;
        http.post('/api/nerv-mock-ra/objs/Resources/Create', initRes.value).then(
            (res) => {
              NsMessage.success('操作成功', 1, () => {
                navigateBack('successBack')
              });
            },
            (error) => {
              if (error?.response?.data?.fieldErrors) {
                errorItem.value = error?.response?.data?.fieldErrors;
                mainRef.value.triggerSubmit(['name']);
              }
              // 删除RM_UUID
              let objData = {
                RM_UUID: data['RM_UUID'],
              }
              event.value.source.postMessage({type:'removeId', data: objData}, event.value.origin);
            },
        );
      }
      let formSchema = ref([
        {
          label: '项目',
          field: 'projectID',
          addModel: {
            projectName: 'projectname',
          },
          ifShow: params.id ? false : true,
          viewOnly: params.id ? true : false,
          component: 'NsSelectApi',
          componentProps: {
            api: {
              url: '/api/passport/passport/objs/Authorization/CheckAuthorization',
              method: 'POST',
            },
            autoSelectFirst: params.id ? false : true,
            showSearch: true,
            filterOption: (input: string, option: any) => {
              return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
            },
            filterData: (item) => {
              return authorizationService().checkPermission(
                'vdisk',
                'Volume',
                'add',
                item.projectname,
              );
            },
            resultField: 'projects',
            labelField: 'projectname',
            valueField: 'projectid',
            immediate: true,
            placeholder: '请选择项目',
          },
          rules: params.id
            ? []
            : [
                {
                  type: 'number',
                  required: true,
                  message: '项目必填',
                  trigger: 'blur',
                },
              ],
        },
        {
          field: 'name',
          label: '磁盘名称',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入',
          },
          rules: [
            {
              required: true,
              message: '磁盘名称必填',
              trigger: 'blur',
            },
            {
              trigger: 'blur',
              validator: async (rule, value) => {
                if (Object.keys(errorItem.value).indexOf('name') !== -1) {
                  const errorInfo = errorItem.value['name'];
                  delete errorItem.value['name'];
                  return Promise.reject(errorInfo);
                }
              },
            },
            {
              pattern: '^[a-zA-Z0-9][a-zA-Z0-9_-]{5,31}$',
              message:
                '只能包含字母，数字，短横线(-)和下划线(_)，且必须由大写字母、小写字母或数字开头。长度在6-32字符之间。',
              trigger: 'blur',
            },
          ],
        },
      ]);

      return {
        errorItem,
        navigateBack,
        editId: null,
        data,
        mainRef,
        submit,
        formSchema,
        formLayout,
        event,
        submitData,
        saveData,
        eventData,
      };
    },
    watch: {
      eventData: function (eventData) {
        const data  = this.event?.data;
        if (data.type === 'returnId' && data.data) {
          this.submitData['RM_UUID'] = data.data['RM_UUID'];
          this.saveData(this.submitData);
        }
      }
    },
    beforeCreate() {},
  });
</script>

<style lang="less" scoped>
  .ant-col {
    flex: 0 0 120px !important;
  }
  .ant-page-header {
    padding: 0 24px;
    margin-bottom: 15px;
  }

  :deep(.ant-page-header-heading-extra) {
    margin-right: auto !important;
    margin-left: 0;
  }
</style>
