<template>
  <div style="padding: 24px; overflow-y: hidden">
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="zhifa" tab="执法端APP">
        <div class="flex-column">
          <a-row style="overflow-y: hidden">
            <a-col :span="12" style="padding: 20px; border: 1px silver solid; margin-left: 10px">
              <a-form
                ref="form"
                :model="form"
                labelAlign="right"
                label-width="80px"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
                size="mini"
              >
                <a-form-item label="当前版本">
                  <span style="font-size: 15px; font-weight: bold; color: #000">
                    <a-input v-model:value="currentAppInfo.edition" :bordered="false" />
                  </span>
                </a-form-item>
                <a-form-item label="版本号">
                  <a-input v-model:value="form.edition" />
                </a-form-item>
                <a-form-item label="项目名称">
                  <a-input v-model:value="form.project_name" defaultValue="drone_enforcement" />
                </a-form-item>
                <a-form-item label="上传">
                  <a-upload-dragger
                    v-model:fileList="fileList"
                    :action="uploadFileUrl"
                    :headers="headers"
                    :progress="progress"
                    name="file"
                    :maxCount="limit"
                    :multiple="false"
                    :beforeUpload="beforeUpload"
                    @change="handleChange"
                    accept=".apk"
                  >
                    <p class="ant-upload-drag-icon">
                      <InboxOutlined />
                    </p>
                    <p class="ant-upload-text">点击或拖拽文件至此处以上传</p>
                  </a-upload-dragger>
                </a-form-item>
                <a-form-item label="描述信息">
                  <a-textarea type="textarea" v-model:value="form.description" :rows="4" />
                </a-form-item>
                <a-form-item label="是否必须更新" label-width="120px">
                  <a-radio-group v-model:value="form.must_update" size="medium">
                    <a-radio :bordered="false" :value="1">是</a-radio>
                    <a-radio :bordered="false" :value="0">否</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item :wrapper-col="{ offset: 10, span: 14 }">
                  <a-button type="primary" @click="onSubmit">立即创建</a-button>
                </a-form-item>
              </a-form>
            </a-col>
          </a-row>
        </div>
      </a-tab-pane>
      <a-tab-pane key="feikong" tab="飞控端APP">
        <div class="flex-column">
          <a-row style="overflow-y: hidden">
            <a-col :span="12" style="padding: 20px; border: 1px silver solid; margin-left: 10px">
              <a-form
                ref="flyControlForm"
                :model="flyControlForm"
                labelAlign="right"
                label-width="80px"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
                size="mini"
              >
                <a-form-item label="当前版本">
                  <span style="font-size: 15px; font-weight: bold; color: #000">
                    <a-input :bordered="false" />
                  </span>
                </a-form-item>
                <a-form-item label="版本号">
                  <a-input v-model:value="flyControlForm.edition" />
                </a-form-item>
                <a-form-item label="项目名称">
                  <a-input v-model:value="flyControlForm.project_name" />
                </a-form-item>
                <a-form-item label="上传">
                  <a-upload-dragger
                    v-model:fileList="fileList"
                    :action="uploadFileUrl"
                    :headers="headers"
                    :progress="progress"
                    name="file"
                    :maxCount="limit"
                    :multiple="false"
                    :beforeUpload="beforeUpload"
                    @change="handleChange"
                    accept=".apk"
                  >
                    <p class="ant-upload-drag-icon">
                      <InboxOutlined />
                    </p>
                    <p class="ant-upload-text">点击或拖拽文件至此处以上传</p>
                  </a-upload-dragger>
                </a-form-item>
                <a-form-item label="描述信息">
                  <a-textarea
                    type="textarea"
                    v-model:value="flyControlForm.description"
                    :rows="4"
                  />
                </a-form-item>
                <a-form-item label="是否必须更新" label-width="120px">
                  <a-radio-group v-model:value="flyControlForm.must_update" size="medium">
                    <a-radio :bordered="false" :value="1">是</a-radio>
                    <a-radio :bordered="false" :value="0">否</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item :wrapper-col="{ offset: 10, span: 14 }">
                  <a-button type="primary" @click="onFlyControlSubmit">立即创建</a-button>
                </a-form-item>
              </a-form>
            </a-col>
          </a-row>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script lang="ts" setup>
  // vue
  import { ref } from 'vue';
  // vben
  import { useMessage } from '@/hooks/web/useMessage';
  import { useGlobSetting } from '@/hooks/setting';
  import { InboxOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '@/store/modules/user';
  import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
  // api
  import { fun_GetUpdateFiles, fun_AddAppFiles } from '@/api/demo/version';
  import { fun_Load } from '@/api/demo/files';
  //上传部件
  const { apiUrl } = useGlobSetting();
  const uploadFileUrl = apiUrl + '/api/Files/Upload';
  const userStore = useUserStore();
  const headers = {
    Accept: 'text/plain',
    'X-Token': userStore.getToken,
  };

  const { createMessage } = useMessage();

  // 表单栅格
  const labelCol = { span: 4 };
  const wrapperCol = { span: 20 };

  let currentAppInfo = ref({});
  let activeKey = ref('zhifa');
  let limit = 1;
  let fileList: any = ref([]);
  // 是否在上传的
  let uploading = false;

  let fileName = '';

  // 执法端APP
  const form = ref({
    edition: '',
    description: '',
    filename: '',
    filepath: '',
    must_update: '',
    project_name: '',
    createuser: '',
    createtime: '',
  });
  // 飞控端APP
  const flyControlForm = ref({
    edition: '',
    description: '',
    filename: '',
    filepath: '',
    must_update: '',
    project_name: '',
    createuser: '',
    createtime: '',
  });

  // 版本
  async function getAppInfo() {
    fun_GetUpdateFiles({ project: 'drone_enforcement' }).then(async (res) => {
      if (res) {
        form.value.project_name = res.project_name;
        currentAppInfo.value = res;
      }
    });
  }
  // 版本
  getAppInfo();

  // 文件状态改变
  function handleChange(info: UploadChangeParam) {
    const file = info.file;
    const status = file?.status;

    if (status === 'uploading') {
      if (!uploading) {
        createMessage.success('文件上传中...');
        uploading = true;
      }
    } else if (status === 'done') {
      createMessage.success('文件上传成功');
      fileName = info.file.name;
      uploading = false;
    } else if (status === 'error') {
      createMessage.error('文件' + info.file.name + '上传失败');
      uploading = false;
    } else if (status === 'removed') {
      createMessage.warn('上传文件删除');
      uploading = false;
    }
  }
  // 上传进度条
  const progress: UploadProps['progress'] = {
    strokeColor: {
      '0%': '#108ee9',
      '100%': '#87d068',
    },
    strokeWidth: 3,
    format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
    class: 'test',
  };
  // 上传之前
  function beforeUpload(file) {
    let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
    let size = file.size / 1024 / 1024;
    if (extension != 'apk') {
      createMessage.warn('只能上传后缀是.apk的文件');
      return false;
    } else if (size > 100) {
      createMessage.warn('文件大小不得超过100M');
      return false;
    } else {
      return true;
    }
  }
  // 执法端APP-立即创建
  function onSubmit() {
    console.log(fileList.value);
    if (fileList.value.length === 0) {
      createMessage.warn(`请选择上传文件!`);
      return;
    }
    fun_Load({ key: fileName }).then((res) => {
      if (res.items.length > 0) {
        form.value.filepath = res.items[0].filePath;
        form.value.project_name = 'drone_enforcement';
        fun_AddAppFiles(form.value).then((res2) => {
          if (res2) {
            createMessage.success(`上传成功!`);
            form.value = {
              createtime: '',
              createuser: '',
              edition: '',
              description: '',
              filename: '',
              filepath: '',
              must_update: '',
              project_name: '',
            };
            fileList.value = [];
            getAppInfo();
          } else {
            createMessage.warn(`接口错误!`);
          }
        });
      } else {
        createMessage.warn(`上传文件出现错误!`);
      }
    });
  }
  // 飞控端APP-立即创建
  function onFlyControlSubmit() {
    if (fileList.value.length === 0) {
      createMessage.warn(`请选择上传文件!`);
      return;
    }
    flyControlForm.value.filename = fileList.value[0].name;
    fun_Load({ key: fileName }).then((res) => {
      if (res.items.length > 0) {
        flyControlForm.value.filepath = res.items[0].filePath;
        // flyControlForm.value.project_name = 'drone_enforcement';
        fun_AddAppFiles(flyControlForm.value).then((res2) => {
          if (res2) {
            createMessage.success(`上传成功!`);
            flyControlForm.value = {
              createtime: '',
              createuser: '',
              edition: '',
              description: '',
              filename: '',
              filepath: '',
              must_update: '',
              project_name: '',
            };
            fileList.value = [];
            getAppInfo();
          } else {
            createMessage.warn(`接口错误!`);
          }
        });
      } else {
        createMessage.warn(`上传文件出现错误!`);
      }
    });
  }
</script>
