<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"
                v-modal:model="currentAppForm"
                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-number v-model:value="currentAppForm.edition" />
                </a-form-item>
                <a-form-item label="项目名称">
                  <a-input
                    v-model:value="currentAppForm.project_name"
                    defaultValue="drone_enforcement"
                    disabled="true"
                  />
                </a-form-item>
                <a-form-item label="上传">
                  <a-upload
                    v-model:file-list="fileList"
                    :name="name"
                    :multiple="true"
                    :customRequest="handleCustomRequest"
                    :headers="headers"
                    :progress="progress"
                    :beforeUpload="beforeUpload"
                  >
                    <a-button :loading="loading"> 点击上传 </a-button>
                  </a-upload>
                  {{ fileName }}
                  <DeleteOutlined v-if="fileName != ''" @click="deleteFileName" />
                </a-form-item>
                <a-form-item label="描述信息">
                  <a-textarea
                    type="textarea"
                    v-model:value="currentAppForm.description"
                    :rows="4"
                  />
                </a-form-item>
                <a-form-item label="是否必须更新" label-width="120px">
                  <a-radio-group v-model:value="currentAppForm.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="fly_form"
                v-model:model="fly_currentAppForm"
                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-number v-model:value="fly_currentAppForm.edition" />
                </a-form-item>
                <a-form-item label="项目名称">
                  <a-input v-model:value="fly_currentAppForm.project_name" />
                </a-form-item>
                <a-form-item label="上传">
                  <a-upload
                    v-model:file-list="fly_fileList"
                    :name="fly_name"
                    :multiple="true"
                    :customRequest="handleCustomRequest"
                    :headers="headers"
                    :progress="progress"
                    :beforeUpload="beforeUpload"
                  >
                    <a-button :loading="fly_loading"> 点击上传 </a-button>
                  </a-upload>
                  {{ fly_fileName }}
                  <DeleteOutlined v-if="fileName != ''" @click="deleteFileName" />
                </a-form-item>
                <a-form-item label="描述信息">
                  <a-textarea
                    type="textarea"
                    v-model:value="fly_currentAppForm.description"
                    :rows="4"
                  />
                </a-form-item>
                <a-form-item label="是否必须更新" label-width="120px">
                  <a-radio-group v-model:value="fly_currentAppForm.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-tab-pane key="jilu" tab="版本更新记录">
        <BasicTable @register="registerTable">
        </BasicTable>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script lang="ts" setup>
  // vue
  import { ref, onMounted } from 'vue';
  // vben
  import { useMessage } from '@/hooks/web/useMessage';
  import { DeleteOutlined, UploadOutlined } from '@ant-design/icons-vue';
  import { message, Upload } from 'ant-design-vue';
  import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
  import { useGlobSetting } from '@/hooks/setting';
  // api
  import { fun_GetUpdateFiles, fun_AddAppFiles } from '@/api/demo/version';
  import { fun_Load, fun_Upload } from '@/api/demo/files';
  import { BasicTable,useTable,TableAction } from '@/components/Table';
  import { SysAppFilesLoad } from '@/api/demo/system';

  const { createMessage } = useMessage();
  const { apiUrl } = useGlobSetting();

  // 表单栅格
  const labelCol = { span: 6 };
  const wrapperCol = { span: 18 };
  // 执法端APP-当前版本信息
  let currentAppInfo = ref({});
  // 标签页
  let activeKey = ref('zhifa');
  // 上传文件列表
  let fileList: any = ref([]);
  let fly_fileList: any = ref([]);
  const loading = ref<boolean>(false);
  const fly_loading = ref<boolean>(false);
  const name = ref<string>('');
  const fly_name = ref<string>('');
  // 上传的文件
  const fileName = ref('');
  const fly_fileName = ref('');
  let filePath = '';
  let fly_filePath = '';

  // 执法端APP
  const currentAppForm = ref({
    edition: '',
    description: '',
    filepath: '',
    must_update: '',
    project_name: '',
    createuser: '',
    createtime: '',
  });
  // 飞控端APP
  const fly_currentAppForm = ref({
    edition: '',
    description: '',
    filepath: '',
    must_update: '',
    project_name: '',
    createuser: '',
    createtime: '',
  });
  const columns = [
    {
      title: '时间',
      dataIndex: 'createtime',
    },
    {
      title: '内容',
      dataIndex: 'description',
    },
    {
      title: '版本',
      dataIndex: 'edition',
    },
    {
      title: '文件地址',
      dataIndex: 'filepath',
    },
    {
      title: '更新人员',
      dataIndex: 'createuser',
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
    },
  ]
  const [registerTable] = useTable({
    title: '版本更新记录',
    api: SysAppFilesLoad,
    columns,
    rowKey: 'id',
    // 使用搜索表单
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    afterFetch: (res) => {
      console.log(res)
    },
  });

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

  // 上传文件接口
  const handleCustomRequest = (file, progress) => {
    if (activeKey.value === 'zhifa') {
      fileList.value = [];
      fun_Upload(file, progress)
        .then((res: any) => {
          if (res.data.result.length > 0) {
            fileName.value = res.data.result[0].fileName;
            filePath = res.data.result[0].filePath;
            loading.value = false;
          }
        })
        .catch((err) => {
          loading.value = false;
          file.onError(err);
          createMessage.error(err.message);
        });
    } else if (activeKey.value === 'feikong') {
      fly_fileList.value = [];
      fun_Upload(file, progress)
        .then((res: any) => {
          if (res.data.result.length > 0) {
            fly_fileName.value = res.data.result[0].fileName;
            fly_filePath = res.data.result[0].filePath;
            fly_loading.value = false;
          }
        })
        .catch((err) => {
          fly_loading.value = false;
          file.onError(err);
          createMessage.error(err.message);
        });
    }
  };

  // 上传之前
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
    let size = file.size / 1024 / 1024;
    const isApk = extension === 'apk';
    const suitableSize = size < 100;

    if (activeKey.value === 'zhifa') {
      name.value = file.name;
    } else {
      fly_name.value = file.name;
    }
    if (!isApk) {
      createMessage.error('只能上传后缀是.apk的文件');
    }
    if (!suitableSize) {
      createMessage.error('文件大小不得超过100M');
    }
    if (isApk && suitableSize) {
      if (activeKey.value === 'zhifa') {
        loading.value = true;
      } else {
        fly_loading.value = true;
      }
    }
    return (isApk && suitableSize) || Upload.LIST_IGNORE;
  };

  // 删除文件
  function deleteFileName() {
    // 执法端APP-删除文件
    if (activeKey.value === 'zhifa') {
      fileName.value = '';
      filePath = '';
      fileList.value = [];
    } else {
      // 飞控端APP-删除文件
      fly_fileName.value = '';
      fly_filePath = '';
      fly_fileList.value = [];
    }
  }

  // 执法端APP-立即创建
  function onSubmit() {
    if (fileName.value == '' || filePath == '') {
      createMessage.warn(`请选择上传文件!`);
      return;
    }
    if (currentAppForm.value.edition == '') {
      createMessage.warn(`请先填写版本号!`);
      return;
    }
    if (currentAppForm.value.project_name != 'drone_enforcement') {
      createMessage.warn(`请不要修改项目名称!`);
      currentAppForm.value.project_name = 'drone_enforcement';
      return;
    }
    fun_Load({ key: fileName.value }).then((res) => {
      if (res.items.length > 0) {
        currentAppForm.value.filepath = res.items[0].filePath;
        fun_AddAppFiles(currentAppForm.value).then((res2) => {
          if (res2) {
            createMessage.success(`上传成功!`);
            currentAppForm.value = {
              createtime: '',
              createuser: '',
              edition: '',
              description: '',
              filepath: '',
              must_update: '',
              project_name: '',
            };
            fileList.value = [];
            getAppInfo();
          } else {
            createMessage.warn(`接口错误!`);
          }
        });
      } else {
        createMessage.warn(`上传文件出现错误!`);
      }
    });
  }

  // 飞控端APP-立即创建
  function onFlyControlSubmit() {
    if (fly_fileName.value == '' || fly_filePath == '') {
      createMessage.warn(`请选择上传文件!`);
      return;
    }
    if (fly_currentAppForm.value.edition == '') {
      createMessage.warn(`请先填写版本号!`);
      return;
    }
    if (fly_currentAppForm.value.project_name == '') {
      createMessage.warn(`请先填写项目名称!`);
      return;
    }
    fun_Load({ key: fly_fileName.value }).then((res) => {
      if (res.items.length > 0) {
        fly_currentAppForm.value.filepath = res.items[0].filePath;
        fun_AddAppFiles(fly_currentAppForm.value).then((res2) => {
          if (res2) {
            createMessage.success(`上传成功!`);
            fly_currentAppForm.value = {
              createtime: '',
              createuser: '',
              edition: '',
              description: '',
              filepath: '',
              must_update: '',
              project_name: '',
            };
            fly_fileList.value = [];
            getAppInfo();
          } else {
            createMessage.warn(`接口错误!`);
          }
        });
      } else {
        createMessage.warn(`上传文件出现错误!`);
      }
    });
  }

  onMounted(() => {
    // 版本
    getAppInfo();
  });
</script>
