<template>
  <div class="layout-pd">
    <el-row>
      <!--操作-->
      <el-col :xs="24" >
        <el-card class="mt8"  shadow="hover" >
          <el-form :model="softwareData.Filter" :inline="true" @submit.stop.prevent>
            <el-form-item prop="name" style="width: 100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="软件类型">
                  <el-select  v-model="softwareData.Filter.softwareType" placeholder="请选择软件类型" >
                    <el-option v-for="(value, key) in softwareType" :key="key" :label="value[1].name"  :value="Number(value[1].value)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="软件名称">
                  <el-input v-model="softwareData.Filter.softwareName" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="版本">
                  <el-input v-model="softwareData.Filter.version" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="设备类型">
                  <el-select  v-model="softwareData.Filter.equipmentType" placeholder="请选择设备类型" >
                    <el-option v-for="(value, key) in equipmentType" :key="key" :label="value[1].name"  :value="Number(value[1].value)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="选择时间">
                  <el-date-picker
                    v-model="softwareData.time"
                    type="datetimerange"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="To"
                    start-placeholder="Start date"
                    end-placeholder="End date"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item>
                  <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
                  <el-button type="primary" icon="ele-RefreshRight" @click="onReset"> 重置 </el-button>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>
          <div class="my-flex my-flex-start" >
            <el-button  type="primary" icon="ele-CirclePlus" @click="onAdd"> 上传软件包 </el-button>
          </div>
        </el-card>
      </el-col>
      <!--表格-->
      <el-col  :xs="24" >
        <el-card style="height: 70vh" class="my-fill mt8" shadow="hover">
          <el-table v-loading="softwareData.loading" stripe :data="softwareData.tableModel" row-key="id" style="width: 100%">
            <el-table-column v-for="column in softwareData.dynamicColumns" :key="column.prop" :prop="column.prop" :label="column.label"  >
              <template #default="{ row }">
                <span :style="getColor(column.prop,row)">
                  {{getProp(column.prop,row)}}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作"  fixed="right" header-align="center" align="center" class="right-operation" width="140">

              <template #default="{ row }" >
                <el-link
                  class="my-el-link mr12 ml12"
                  v-if="row.state === 0"
                  type="primary"
                  icon="ele-Upload"
                  size="small"
                  @click="onRelease(row)"
                  :underline="false"
                  target="_blank"
                >发布</el-link>
                <el-link
                  class="my-el-link mr12 ml12"
                  v-if="row.state === 0"
                  type="primary"
                  icon="ele-Edit"
                  size="small"
                  @click="editTableData(row)"
                  :underline="false"
                  target="_blank"
                >编辑</el-link>
                <el-link
                  class="my-el-link mr12 ml12"
                  v-if="row.state === 1"
                  type="primary"
                  icon="ele-Download"
                  size="small"
                  @click="onDownload(row)"
                  :underline="false"
                  target="_blank"
                >下载</el-link>
                <el-link
                  class="my-el-link mr12 ml12"
                  v-if="row.state === 1"
                  type="primary"
                  icon="ele-WarningFilled"
                  size="small"
                  @click="onFailure(row)"
                  :underline="false"
                  target="_blank"
                >失效</el-link>
                <el-link
                  class="my-el-link mr12 ml12"
                  v-if="row.state !== 0"
                  type="primary"
                  icon="ele-Tickets"
                  size="small"
                  @click="onDownloadRecord(row.guid)"
                  :underline="false"
                  target="_blank"
                >下载记录</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 20px">
            <el-pagination
              v-model:currentPage="softwareData.pageInput.CurrentPage"
              v-model:page-size="softwareData.pageInput.PageSize"
              :total="softwareData.total"
              :page-sizes="[10, 20, 50, 100]"
              small
              background
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
          <template>
            <a ref="downloadLink" style="display: none;"></a>
          </template>
        </el-card>
      </el-col>
    </el-row>
    <EditDialog ref="editDialogRef" />
    <DownloadDialog ref="downloadDialogRef" />
  </div>
</template>

<script setup lang="ts">

import {defineAsyncComponent, onBeforeMount, onMounted, reactive, ref, watch} from "vue";
import {useGlobalCacheStore} from "/@/stores/globalCacheStore";
import {
  softwarePackageManagement_AllDto,
  softwarePackageManagement_SearchFilter,
  softwarePackageManagement_TableData
} from "/@/api/admin/deviceAuthorization/softwarePackageManagementDto";
import type {pageInput} from "/@/api/admin/shareDto/shareDto";
import eventBus from "/@/utils/mitt";
import {SoftwarePackageManagementApi} from "/@/api/admin/deviceAuthorization/softwarePackageManagementApi";
import { storeToRefs } from 'pinia'
import { useUserInfo } from '/@/stores/userInfo'

/**引入组件*/
const EditDialog = defineAsyncComponent(() => import('./components/form-edit.vue'))
const DownloadDialog = defineAsyncComponent(() => import('./components/table-download.vue'))
// import {pageInput} from "/@/api/admin/shareDto/shareDto";
const editDialogRef = ref()
const downloadDialogRef=ref()


/**获取全局缓存*/
const globalCacheStore = useGlobalCacheStore()
/**设备类型缓存*/
const equipmentType = ref(globalCacheStore.getGlobalStore().get('equipmentType'))
/**软件类型缓存*/
const softwareType = ref(globalCacheStore.getGlobalStore().get('softwareType'))
/**软件包状态缓存*/
const softwarePackageStatus = ref(globalCacheStore.getGlobalStore().get('softwarePackageStatus'))

/**软件包管理对象*/
const softwareData = reactive({
  time:'',
  /**加载显示 */
  loading: false,
  /**条件查询模块 */
  Filter: {
    /**软件类型 */
    softwareType: "",
    /**软件名称 */
    softwareName: "",
    /**版本 */
    version: "",
    /**设备类型*/
    equipmentType: "",
    /**开始的时间 */
    BeginTime: null,
    /**开始的时间 */
    EndTime: null,
  } as softwarePackageManagement_SearchFilter,
  /**表格信息 */
  tableModel: [] as softwarePackageManagement_TableData,
  /**动态表头 */
  dynamicColumns: [
    { prop: 'date', label: '日期' },
    { prop: 'softwareType', label: '软件类型' },
    { prop: 'equipmentType', label: '设备类型' },
    { prop: 'softwareName', label: '软件名称' },
    { prop: 'version', label: '版本号' },
    { prop: 'explain', label: '说明' },
    { prop: 'state', label: '状态' },
    { prop: 'numberOfDownloads', label: '下载次数' },
    { prop: 'remark', label: '备注' },
    { prop: 'releaseTime', label: '发布日期' },
    { prop: 'uploadTime', label: '上传日期' },
  ],
  /**分页标识 */
  pageInput:{
    CurrentPage: 1,
    PageSize: 10,
  } as pageInput,
  /**分页总数 */
  total: 0,
} as softwarePackageManagement_AllDto)

const downloadLink = ref()
/**条件查询 */
const onQuery = () => {
  init()
}

/**将Filter对象成.的连接方式*/
const flattenObject = (obj, parentKey = '') => {
  const result = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const newKey = parentKey ? `${parentKey}.${key}` : key;
      if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
        const flattened = flattenObject(obj[key], newKey);
        Object.assign(result, flattened);
      } else {
        result[newKey] = obj[key];
      }
    }
  }

  return result;
}

/**初始化 */
const init = async () => {
  softwareData.loading = true
  const query = flattenObject({ Filter: softwareData.Filter})
  debugger
  const res:any = await new SoftwarePackageManagementApi().getPageData({...softwareData.pageInput, Filter:softwareData.Filter})
  softwareData.tableModel = res?.data?.list ?? []
  softwareData.total = res?.data?.total ?? 0
  softwareData.loading = false
}

onMounted(() => {
  init()
  eventBus.off('refreshView')
  eventBus.on('refreshView', async () => {
    await init()
  })
  console.log()
})

onBeforeMount(() => {
  eventBus.off('refreshView')
})

/**
 * 监听时间变换
 */
watch(() => softwareData.time, (newVal ) => {
  if(newVal.length === 0){
    return
  }
  softwareData.Filter.BeginTime = newVal?.[0].toString()
  softwareData.Filter.EndTime = newVal?.[1].toString()
})

/**重置查询条件 */
const resetQuery = () => {
  softwareData.Filter.softwareType = ''
  softwareData.Filter.softwareName = ''
  softwareData.Filter.version = ''
  softwareData.Filter.equipmentType = ''
  softwareData.Filter.BeginTime =  ''
  softwareData.Filter.EndTime = ''
  softwareData.time = ''
  softwareData.pageInput.CurrentPage = 1
}

/**重置 */
const onReset = () => {
  resetQuery()
  init()
}

/**添加*/
const onAdd = () => {
  editDialogRef.value.openDialog()
}

/**编辑弹窗 */
const editTableData = (row) => {
  editDialogRef.value.openDialog(row)
}

/**发布*/
const onRelease = (row) => {
  debugger
  //downloadUrl
  softwareData.loading = true;
   (row  as softwarePackageManagement_TableData).state = 1
  var RowData =  JSON.parse(JSON.stringify(row))
  var res =  new SoftwarePackageManagementApi().addData(RowData as softwarePackageManagement_TableData)
  softwareData.loading = false
}

/**下载*/
const onDownload = (row) => {
  softwareData.loading = true;
  var RowData =  JSON.parse(JSON.stringify(row))
  const params = RowData as softwarePackageManagement_TableData
  //const link = downloadLink.value;
  //const url = `http://localhost:8000/api/app/software/download-file`;
  //link.href = url;
  //link.click();
  const filename =  params.fileName?.toString();
  const { userInfos } = storeToRefs(useUserInfo());
  const accessToken = userInfos.value.token
  const token = `Bearer ${accessToken}`
  var myHeaders = new Headers();
myHeaders.append("Authorization", token);

const requestOptions: RequestInit = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow', // 此处使用枚举值 'follow'
};

  /* var res =  new SoftwarePackageManagementApi().DownloadFile(row as softwarePackageManagement_TableData) */
  const fileUrl = import.meta.env.VITE_API_URL +'/api/app/software/download-file?guid='+params.guid; // 替换为实际文件URL
                    fetch(fileUrl,requestOptions)
                        .then(response => response.blob())
                        .then(blob => {
                            const link = document.createElement('a');
                            link.href = URL.createObjectURL(blob);
                            link.download = filename;
                            link.click();
                            softwareData.loading = false
                        })
                        .catch(error => {
                            console.error('下载失败：', error);
                            softwareData.loading = false
                        });
 // var res =  new SoftwarePackageManagementApi().DownloadFile(RowData as softwarePackageManagement_TableData)
 
}

/**失效*/
const onFailure = (row) => {
  softwareData.loading = true;
   (row  as softwarePackageManagement_TableData).state = 2
  var RowData =  JSON.parse(JSON.stringify(row))
  var res =  new SoftwarePackageManagementApi().addData(RowData as softwarePackageManagement_TableData)
  softwareData.loading = false
}

/**下载记录*/
const onDownloadRecord = (id) => {
  downloadDialogRef.value.openDialog(id)
  //alert('下载记录')
}

/**页条数变化*/
const onSizeChange = () => {
  init()
}

/**页数变化*/
const onCurrentChange = () =>{
  init()
}

/**过滤数字的属性*/
const getProp = (val,row) => {
  if(val === 'softwareType') return softwareType.value.get(String(row[val])).name
  if(val === 'equipmentType') return equipmentType.value.get(String(row[val])).name
  if(val === 'state') return softwarePackageStatus.value.get(String(row[val])).name
  return row[val]
}

const getColor = (val,row) => {
  if(val === 'state') {
    const code = softwarePackageStatus.value.get(String(row[val])).code.split('_')
    return {color:code[1]}
  }
  return {}
}


</script>

<style scoped lang="scss">
.el-link{
  padding: 5px;
}
</style>
