<template>
  <div class="ele-body">
    <a-card :title="`创建${title}`" :bordered="false">
      <div class="form-box">
        <a-form
          ref="formRef"
          :model="form"
          :rules="rules"
          :label-col="{ md: { span: 4 }, sm: { span: 24 } }"
          :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
        >
          <template v-if="key === 'web'">
            <a-card :bordered="false" :body-style="{ padding: '16px' }">
              <div class="content">
                <div class="app-item-list">
                  <div class="ele-cell">
                    <div class="ele-cell-content">
                      <a-form-item
                        label="网站应用名称"
                        v-bind="validateInfos.appName"
                      >
                        <a-input
                          allow-clear
                          :maxlength="20"
                          placeholder="请输入应用名称"
                          v-model:value="form.appName"
                          @blur="
                            validate('appName', { trigger: 'blur' }).catch(
                              () => {}
                            )
                          "
                        />
                      </a-form-item>
                    </div>
                  </div>
                  <div class="ele-cell">
                    <div class="ele-cell-content">
                      <a-form-item
                        label="网站域名"
                        v-bind="validateInfos.appUrl"
                      >
                        <a-input
                          allow-clear
                          :maxlength="100"
                          placeholder="请输入网站域名"
                          v-model:value="form.appUrl"
                          @blur="
                            validate('appUrl', { trigger: 'blur' }).catch(
                              () => {}
                            )
                          "
                        />
                      </a-form-item>
                    </div>
                  </div>
                  <div class="ele-cell">
                    <div class="ele-cell-content">
                      <a-form-item
                        label="应用图标"
                        extra="请上传应用高清图片，支持.jpg .jpeg .png格式，建议320*320像素，小于1M"
                        v-bind="validateInfos.appIcon"
                      >
                        <ele-image-upload
                          v-model:value="images"
                          :limit="1"
                          :drag="true"
                          :upload-handler="uploadHandler"
                          @upload="onUpload"
                        />
                      </a-form-item>
                    </div>
                  </div>
                  <div class="ele-cell">
                    <div class="ele-cell-content">
                      <a-form-item
                        label="应用描述"
                        v-bind="validateInfos.comments"
                      >
                        <a-textarea
                          :rows="4"
                          :maxlength="200"
                          placeholder="请输入应用描述"
                          v-model:value="form.comments"
                        />
                      </a-form-item>
                    </div>
                  </div>
                </div>
              </div>
            </a-card>
          </template>
        </a-form>
        <div class="submit">
          <a-button type="primary" @click="save">确认创建</a-button>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  // import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue';
  import { ref, unref, reactive, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { Form, message } from 'ant-design-vue';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { FILE_SERVER, FILE_THUMBNAIL } from "@/config/setting";
  import { uploadFile } from '@/api/system/file';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { App } from '@/api/app/model';
  import { addApp } from '@/api/app';
  import { assignObject } from 'ele-admin-pro';
  import { openUrl } from '@/utils/common';

  const props = defineProps<{
    // 修改回显的数据
    data?: null;
  }>();

  const useForm = Form.useForm;

  // 定义参数
  const key = ref('web');
  const title = ref('网站应用');
  const { currentRoute } = useRouter();
  const formRef = ref<FormInstance | null>(null);
  // 已上传数据
  const images = ref<ItemType[]>([]);
  // 提交状态
  const loading = ref(false);

  // 表单验证规则
  const rules = reactive({
    appName: [
      {
        required: true,
        type: 'string',
        message: '请输入应用名称',
        trigger: 'blur'
      }
    ],
    appUrl: [
      {
        required: true,
        type: 'string',
        message: '请输入应用地址',
        trigger: 'blur'
      }
    ],
    appIcon: [
      {
        required: true,
        type: 'string',
        message: '请上传应用图片',
        trigger: 'blur'
      }
    ],
    comments: [
      {
        required: true,
        type: 'string',
        message: '请填写应用描述',
        trigger: 'blur'
      }
    ]
  });

  // 表单数据
  const form = reactive<App>({
    appName: '',
    appUrl: '',
    appIcon: '',
    comments: '',
    tenantId: undefined
  });

  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 1) {
      message.error('大小不能超过 1MB');
      return;
    }
    onUpload(item);
  };
  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: FILE_THUMBNAIL + data.path,
          status: 'done'
        });
        form.appIcon = data.path;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const { resetFields, validate, validateInfos } = useForm(form, rules);
  /* 保存编辑 */
  const save = () => {
    validate()
      .then(() => {
        loading.value = true;
        const data = {
          ...form,
          appType: key.value
        };
        addApp(data)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            openUrl('/app');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  const reload = () => {
    // 接收传参
    const { query } = unref(currentRoute);
    if (query.title) {
      key.value = `${query.key}`;
      title.value = `${query.title}`;
    }
  };
  reload();

  watch(
    () => props.data,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          assignObject(form, props.data);
        } else {
        }
      } else {
        resetFields();
      }
    }
  );
</script>

<script lang="ts">
  export default {
    name: 'AppCreate'
  };
</script>
<style lang="less" scoped>
  .form-box {
    max-width: 750px;
  }
  .submit {
    margin-left: 140px;
    margin-bottom: 30px;
  }
  /* 应用详情字段列表 */
  .app-item-list {
    & > .ele-cell {
      padding: 16px 8px;
      .ele-cell-content {
        .ele-cell-desc {
          margin-bottom: 5px;
        }
      }
    }

    .app-item-icon {
      color: #fff;
      padding: 8px;
      font-size: 26px;
      border-radius: 50%;

      &.anticon-qq {
        background: #3492ed;
      }

      &.anticon-wechat {
        background: #4daf29;
      }

      &.anticon-alipay {
        background: #1476fe;
      }
    }
  }
</style>
