<template>
  <div class="org-title text-G900 text-2xl mt-24 mb-24 font-[600]">{{ createOrgItem.title }}</div>
  <Card class="org-card pl-32 pr-32">
    <div class="org-contentdiv overflow-hidden">
      <d-form class="org" ref="formRef" layout="vertical" :data="orgData" :pop-position="['right']" :rules="rules">
        <d-form-item field="name" :rules="rules.name" :show-feedback="false" :label="createOrgItem.orgName.label">
          <d-input v-model="orgData.name" style="width: 668px;" maxlength="50"
            :placeholder="createOrgItem.orgName.placeholder" @blur="handleNameBlur" />
        </d-form-item>
        <d-form-item class="org-url" field="path" :rules="rules.path" :label="createOrgItem.orgUrl.label"
          :help-tips="createOrgItem.orgUrl.desc" :extra-info="(true) ? '' : createOrgItem.orgUrl.occupied">
          <div class="org-path w-[fit-content]">
            <d-input class="org-prefix" v-model="createOrgItem.orgUrl.prefix" :validate-event="false" disabled />
            <div class="org-path-line">/</div>
            <d-input v-model="orgData.path" :placeholder="createOrgItem.orgUrl.placeholder" maxlength="50" />
          </div>
        </d-form-item>
        <d-form-item field="orgData.avatar" :label="createOrgItem.orgLogo.label" class="org-logo">
          <div class="img-container" v-if="!showUpload">
            <img class="img-preview" :src="orgData.avatar" />
            <div class="delete-img" @click="handleDel">
              <d-icon name="delete" size="14px"></d-icon>
            </div>
          </div>
          <d-upload class="upload-demo-new" accept=".png,.jpg,.gif,.jpeg" :before-upload="beforeUpload" v-if="showUpload"
            @file-select="fileSelect">
            <div class="upload-trigger">
              <d-icon name="add" size="24px"></d-icon>
            </div>
          </d-upload>
        </d-form-item>
        <d-form-item field="visibility" :label="createOrgItem.visibility.label">
          <d-radio-group direction="row" v-model="orgData.visibility">
            <d-radio v-for="(item, index) in visibility" :key="item.value" :value="item.value"
              :class="index != 0 ? 'org-radio' : ''">
              <div class="org-radiondiv">
                <Icon :name="item.icon" class="mr-1"></Icon>
                {{ item.name }}
              </div>
            </d-radio>
          </d-radio-group>
        </d-form-item>
      </d-form>
    </div>
    <div class="org-radiondiv pt-[12px] w-[668px] text-right">
      <d-button @click="cancel">取消</d-button>
      <d-button variant="solid" class="org-cancel" color="primary" :loading="btnLoading" :disabled="!isFormValid"
        @click="handleSubmit">
        创建组织
      </d-button>
    </div>
  </Card>
</template>

<script setup lang="ts">
import { reactive, ref, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import debounce from 'lodash/debounce';
import { reqCatch } from '@/utils/catch';
import { createOrg, inquireOrgPathIsRepeat } from '@/api/org';
import * as types from '@/api/org/types';
import { uploadFile } from '@/api/user';
import { Message } from 'vue-devui/message';
import { orgNameRegExp, orgPathRegExp } from '@/utils/regex';
import { orgInfoStore } from '@/stores/Org/index';
import { getOrgInfo } from '@/views/Org/hooks/orgInfo';
const { getUserCreateOrg } = getOrgInfo();
getUserCreateOrg();
const orgStore = orgInfoStore();
const router = useRouter();
watch(() => orgStore.isCreateOrg, () => {
  orgCreateFun();
});
const orgCreateFun = () => {
  if (!orgStore.isCreateOrg) {
    Message({
      type: 'warning',
      message: '你最多可以创建或管理 5 个组织，无法创建新的组织。'
    });
    router.replace({
      name: 'settingOrganization'
    });
  }
};
orgCreateFun();
const showUpload = ref(true);
const btnLoading = ref(false);
const beforeUpload = (file: any) => {
  // if (file.length > 0 && file[0].size > 200 * 1024) {
  //   return Message({
  //     type: 'warning',
  //     message: '图片大小不超过200kb!'
  //   });
  // }
  // const reader = new FileReader();
  // reader.onload = async() => {
  //   showUpload.value = false;
  //   await nextTick();
  //   document.getElementsByClassName('img-preview')[0].src = reader.result;
  // };
  // reader.readAsDataURL(file[0].file);
  return false;
};
const handleDel = () => {
  showUpload.value = true;
  orgData.avatar = '';
};
const visibility = ref([
  {
    value: 'public',
    name: '公开',
    icon: 'gt-public-c'
  },
  {
    value: 'private',
    name: '私密',
    icon: 'gt-lock-c'
  }
]);
interface orgDataObj {
  name: string,
  path: string,
  avatar: string,
  visibility: string,
}
const orgData = reactive<orgDataObj>({
  name: '',
  path: '',
  avatar: '',
  visibility: 'public'
});
const createOrgItem = {
  title: '新建组织',
  orgName: {
    label: '组织名称',
    placeholder: '请输入组织名称',
    ruleDesc: {
      notNull: '组织名称不能为空'
      // regex: '组织名称由字母、数字和连字符（-）组成；组织名称必须以字母或数字开头；连续的连字符（-）是不允许的；组织名称最多可以包含 50 个字符。'
    }
  },
  orgUrl: {
    label: '组织URL',
    // prefix: `${(import.meta as any).env.VITE_HOST}/`,
    prefix: `${window.location.origin}/openRepoPortal/`,
    placeholder: '请输入',
    occupied: 'namespace已被使用',
    ruleDesc: {
      notNull: 'url不能为空',
      regex: ''
    }
  },
  orgLogo: {
    label: '组织LOGO',
    desc: '图片宽度*高度至少为150*150像素，大小不超过200KB。',
    placeholder: '将图片拖到此处，或',
    button: '点击上传',
    delete: '删除'
  },
  visibility: {
    label: '组织可见性',
    default: '公开',
    internal: '私密'
  },
  createOrg: '创建组织',
  cancel: '取消'
};

// 验证path是否重复
const isPathValid = ref<boolean>(false);
const lastPath = ref<string>('');
const formRef = ref(null);
const inquireOrgPath = async() => {
  if (orgData.path) {
    if (orgData.path !== lastPath.value) {
      const params: types.commonGroupReqType = {
        path_name: orgData.path
      };
      const res = await reqCatch(inquireOrgPathIsRepeat, params);
      isPathValid.value = (!res.data) || (res.data.data.devpress_exist !== false) || (res.data.data.type !== null);
      lastPath.value = orgData.path;
    }
  } else {
    isPathValid.value = false;
  }
  // validateForm();
};
const validateForm = () => new Promise((resolve, reject) => {
  formRef.value.validate((isValid: boolean, invalidFields: any) => {
    isFormValid.value = isValid;
    isValid ? resolve(true) : reject(invalidFields);
  });
});
// watch(() => orgData.path, debounce(validateForm, 500));

const checkOrgName = (rule: object, value: string, callback: Function) => {
  isFormValid.value = false;
  if (!value) {
    return callback(new Error('组织名称不能为空！'));
  }
  if (!orgNameRegExp.test(value)) {
    return callback(
      new Error(
        '组织名称仅包含中文、字母、数字、下划线和连字符（-），不支持连字符或下划线开头和结尾，不支持连续的连字符或下划线，最多50个字符。'
      )
    );
  }
  isFormValid.value = true;
  return callback();
};
const checkOrgPath = async(rule: object, value: string, callback: Function) => {
  isFormValid.value = false;
  if (!value) {
    lastPath.value = '';
    return callback(new Error('组织路径不能为空！'));
  }
  if (!orgPathRegExp.test(value)) {
    lastPath.value = '';
    return callback(
      new Error(
        '路径须以字母开头，以字母或数字结尾，仅包含字母（大小写不敏感）、数字、连字符（-）、下划线（_），长度在3到50个字符之间。'
      )
    );
  }
  if (~['v1', 'backend', 'organization', 'public'].indexOf(value)) {
    lastPath.value = '';
    return callback(new Error('路径已被使用，请重新输入'));
  }
  // 验证重复
  await inquireOrgPath();
  if (isPathValid.value) {
    // lastPath.value = '';
    return callback(new Error('路径已被使用，请重新输入'));
  }
  isFormValid.value = true;
  return callback();
};

const rules = {
  name: [{required: true, message: '组织名称不能为空！'},{ validator: checkOrgName }],
  path: [{required: true, message: '组织路径不能为空！'},{ validator: checkOrgPath }],
  logo: ''
};

// 上传图片
const imgLoading = ref<boolean>(false);
const fileSelect = async(fileInfo: any) => {
  if (fileInfo.length > 0 && fileInfo[0].size > 200 * 1024) {
    return Message({
      type: 'warning',
      message: '图片大小不超过200kb!'
    });
  }
  imgLoading.value = true;
  const resImg: any = await uploadFile(fileInfo, false, fileInfo[0].type);
  orgData.avatar = resImg + '?time' + new Date().getTime();
  imgLoading.value = false;
  showUpload.value = false;
};

const isFormValid = ref(false);
const handleSubmit = async() => {
  try {
    await validateForm();
    await create();
  } catch (err) {
    // ignore
  }
};

const create = async() => {
  btnLoading.value = true;
  const params = { // 暂定只需要传递name,path,visibility
    name: orgData.name,
    path: orgData.path,
    visibility: orgData.visibility,
    avatar: orgData.avatar
  };
  const res = await reqCatch(createOrg, params);
  btnLoading.value = false;
  if (!res.error) {
    router.push({
      name: 'homepage',
      params: {
        namespace: orgData.path,
        repoName: orgData.name
      }
    });
  }
};
const cancel = () => {
  router.go(-1);
};

// 输入名称补全path
const handleNameBlur = () => {
  if (orgPathRegExp.test(orgData.name)) {
    orgData.path = orgData.name;
  }
};
</script>

<style lang="scss" scoped>
.org {
  :deep(.devui-form__label--required:before) {
    margin-left: 0px;
  }
  &-prefix {
    :deep(.devui-input--error) {
      background: #FBFBFB;
      border-color: #E6E7E8;
      color: #7E7E80;
    }
  }
  :deep(.devui-radio) {
    display: flex;
    align-items: center;
  }

  &-path {
    display: flex;

    :deep(.devui-input) {
      width: 326px;
    }

    &-line {
      padding: 5px 6px;
      font-size: 18px;
    }
  }

  :deep(.devui-form__control .devui-form__control-info .error-message) {
    white-space: nowrap;
    margin: 8px auto 20px auto;
  }
}

.org-card {
  padding: 20px;
}

.org-cancel {
  // width: 96px;
  margin-left: 8px;
}

.org-contentdiv {
  width: 888px;
}

.org-imgdiv {
  display: flex;
  align-items: flex-end;
  margin-bottom: 8px;
}

.org-radiondiv {

  .org-radioicon {
    margin-right: 8px;
  }
}

.org-imgbg {
  width: 120px;
  height: 120px;
}

.org-logo-desc {
  font-weight: 400;
  line-height: 20px;
}

:deep(.devui-icon--no-slots i) {
  display: inline;
}

.upload-demo-new .upload-trigger {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 180px;
  height: 180px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.upload-demo .upload-trigger .link {
  color: #5e7ce0;
}

.img-container {
  position: relative;
}

.img-preview {
  width: 180px;
  height: 180px;
  border-radius: 6px;
}

.delete-img {
  width: 24px;
  height: 24px;
  background-color: #f7f7f9;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: -12px;
  left: 168px;
}
</style>
