<template>
<a-card title="OTA包管理" >
  <a-row style="width: 100%;" justify="space-between" >
    <a-col :span="16" >
      <a-row :gutter="[8, 8]" >
        <a-col>
          <a-input allowClear placeholder="请输入包名" style="width: 170px;" v-model:value="queryState.label" ></a-input>
        </a-col>
        <a-col>
          <a-input   placeholder="请输入版本" allowClear style="width: 170px;" v-model:value="queryState.version" ></a-input>
        </a-col>
        <a-col>
          <a-select style="width: 170px;" allowClear v-model:value="queryState.pkgType" placeholder="请选择包类型" >
          <a-select-option
              v-for="item in OtaController.pkgTypeList"
              :key="item.value"
              :value="item.value"
            >
              {{item.label}}
            </a-select-option>
        </a-select>
        </a-col>
        <a-col>
          <a-button type='primary' @click="getOtaPkgPage" > 搜索 </a-button>
        </a-col>
      </a-row>
    </a-col>
    <a-col :span="2" >
      <a-button type="primary" @click="openModal('add', {})">新增</a-button>
    </a-col>
  </a-row>

  <a-table
      style="margin-top: 10px;"
      :columns="columns"
      :data-source="state.dataSource"
      :loading="state.loading"
      :pagination="queryState"
      @change="changePage"
    >
      <template #bodyCell="{column, record}">
        <template v-if="column.key == 'pkgType'" >
          {{record.pkgType === PkgTypeEnum.FILE_URL ? '网络地址' : '压缩包' }}
        </template>
        <template v-if="column.key === 'action'">
            <a-space>
              <a-popconfirm
                  title="确实要删除吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="delOtaPkg(record.id)"
                >
                  <a href="#">删除</a>
              </a-popconfirm>
            </a-space>
        </template>
      </template>
    </a-table>
</a-card>

<modal-pro
  :label="modalTitle"
  :open="state.visible"
  @cancel="closeModal"
  @ok="ok"
>
<a-form  :labelCol="{span: 6}" :wrapperCol="{span: 14}" >
      <a-form-item label="包名" v-bind="validateInfos.label" >
        <a-input allowClear v-model:value="otaPkgState.label" />
      </a-form-item>
      <a-form-item label="版本" v-bind="validateInfos.version" >
        <a-input allowClear v-model:value="otaPkgState.version" />
      </a-form-item>
      <a-form-item label="类型" v-bind="validateInfos.pkgType"  >
        <a-select allowClear v-model:value="otaPkgState.pkgType" >
          <a-select-option
              v-for="item in OtaController.pkgTypeList"
              :key="item.value"
              :value="item.value"
            >
              {{item.label}}
            </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-if="otaPkgState.pkgType" label="包地址" v-bind="validateInfos.pkgUrl"  >
        <a-input v-if="otaPkgState.pkgType === PkgTypeEnum.FILE_URL" allowClear v-model:value="otaPkgState.pkgUrl" />
        <upload-pro
          :action="instance.defaults.baseURL + '/file'"
          @done="uploadDone"
          v-else-if="otaPkgState.pkgType === PkgTypeEnum.FILE_ZIP"
        >
        </upload-pro>
      </a-form-item>
</a-form>
</modal-pro>
</template>
<script lang='ts' setup >
import { OtaController } from '@/controller/iot'
import { reactive, onMounted, computed } from 'vue'
import { Form, UploadChangeParam, message } from 'ant-design-vue'
import { PkgTypeEnum } from '@/enum/common'
import { CommonController } from '@/controller'
import { instance } from '@/service/request'

const columns = [
  {
    title: '包名',
    dataIndex: 'label'
  },
  {
    title: '版本',
    dataIndex: 'version'
  },
  {
    title: '包类型',
    dataIndex: 'pkgType',
    key: 'pkgType'
  },
  {
    title: '包地址',
    dataIndex: 'pkgUrl'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

const modalTitle = computed(() => state.opraState === 'add' ? '新增ota包' : '编辑ota包')

const queryState = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
  label: '',
  version: '',
  pkgType: null
})

const state = reactive<{
  loading: boolean,
  dataSource: IOT.API.OTA.Detail[],
  visible: boolean
  opraState: 'add' | 'update'
}>({
  loading: false,
  dataSource: [],
  visible: false,
  opraState: 'add'
})

const otaPkgState = reactive({
  version: '',
  pkgType: '',
  pkgUrl: '',
  label: ''
})

let fileState = reactive({
  filePath: '', // 文件地址
  filename: '',
  fileUrl: ''
})

const useForm = Form.useForm

const { resetFields, validate, validateInfos } = useForm(otaPkgState, reactive({
  version: [{ required: true, message: '请填写版本号' }],
  pkgType: [{ required: true, message: '请选择包类型' }],
  pkgUrl: [{ required: true, message: '请填写包地址' }],
  label: [{ required: true, message: '请填写包名' }]
}))

const uploadDone = async (info: UploadChangeParam) => {
  if (fileState.filePath) {
    await CommonController.delOtaPkg(fileState.filePath, fileState.filename)
  }
  fileState = reactive(info.file.response.data)
  otaPkgState.pkgUrl = fileState.fileUrl
}

const changePage = ({ current }) => {
  queryState.page = current
  getOtaPkgPage()
}

// 关闭弹窗 同时因为没有确定创建ota包，所以如果是上传了压缩包，则需要删除压缩包
const closeModal = async () => {
  state.visible = false
  CommonController.delOtaPkg(fileState.filePath, fileState.filename)
}

const ok = () => {
  validate().then(async () => {
    await OtaController.add(otaPkgState)
    getOtaPkgPage()
    state.visible = false
  })
}

const openModal = (key: 'add' | 'update', record: IOT.API.OTA.Detail) => {
  state.visible = true
  resetFields(record)
}

const delOtaPkg = async (id: string) => {
  await OtaController.del(id)
  getOtaPkgPage()
}

const getOtaPkgPage = async () => {
  state.loading = true
  const { data } = await OtaController.page(queryState as IOT.API.OTA.QueryParams)
  state.dataSource = data
  state.loading = false
}

onMounted(() => {
  getOtaPkgPage()
})

</script>
<style lang='less' scoped >
</style>
