<!-- 状态管理公共列表组件 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import approve from './approvalActionDialog.vue'
import { getStatusList } from '@/api/device/stateManage'
import { getDictByCode } from '@/api/system/dict'
import { printJSON } from '@/utils/printUtils'
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
  type: { // 当前状态
    type: String,
    default: '',
  },
  applyType: { // 设备申请类型
    type: String,
    default: '',
  },
})
const $router = useRouter()
// import { exportFile } from '@/utils/exportUtils'
// const { proxy } = getCurrentInstance() as any
const searchQuery = reactive({
  applyNo: '', // 申请编号
  applyStatus: '', // 申请状态
  applyUnit: '', // 申请单位
  approvalStatus: '', // 审批状态
  createUser: '', // 创建人
  equipmentName: '', // 设备名称
  equipmentNo: '', // 设备编号
  ids: [] as string[],
  limit: 20,
  offset: 1,
}) // 查询参数
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref([
  {
    text: '申请编号',
    value: 'applyNo',
    align: 'center',
  },
  {
    text: '申请类型',
    value: 'applyTypeName',
    align: 'center',
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
  },
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
  },
  {
    text: '设备状态',
    value: 'managerStateName',
    align: 'center',
  },
  {
    text: '申请单位',
    value: 'applyUnit',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'applyPerson',
    align: 'center',
  },
  {
    text: `${props.name.substring(2, 4)}时间`,
    value: 'time',
    align: 'center',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
  },
]) // 表格
const list = ref() // 表格数据
const approveRef = ref()
const dialogVisible = ref<boolean>(false) // 添加组件的显示与隐藏
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  getDictByCode('managerState').then((response) => {
    if (response.code === 200) {
      console.log(response.data, 'response') // 状态

      // 根据闲置，封存，启封等状态获取不同的列表
      // 接口未写好
      getStatusList(searchQuery).then((res) => {
        if (res.code === 200) {
          list.value = res.data.rows
          total.value = res.data.total
        }
        loadingTable.value = false
      })
    }
  }).catch((_) => {
    loadingTable.value = false
  })

  // list.value = [
  //   {
  //     applyNo: 'sbxz20230103',
  //     applyTypeName: `${props.name.substring(2, 4)}申请`,
  //     equipmentNo: 'device20230103',
  //     equipmentName: '测试设备',
  //     modelNo: 'CL001',
  //     managerStateName: '在用',
  //     applyUnit: '徐州分中心',
  //     applyPerson: '超级管理员',
  //     time: '2023-1-3 13:47',
  //     approvalStatusName: '审批中',
  //   },
  // ]
  // total.value = 1
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.limit = val.size
  }
  if (val && val.page) {
    searchQuery.offset = val.page
  }
  getList()
}
// 详情
const detail = (row: any) => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'detail',
      id: row.id,
    },
    query: {
      title: '详情',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
// 编辑
const update = (row: any) => {
  // dialogVisible.value = true
  // addRef.value.initDialog({
  //   title: '编辑',
  //   ...row,
  // })
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'edit',
    },
    query: {
      title: '编辑',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
// 删除
const remove = (row: any) => {
  ElMessageBox.confirm(
    `确认删除${row.equipmentName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  // .then(() => {
  //   assetsDeleteApi({ id: row.id as string }).then((res) => {
  //     if (res.code === 200) {
  //       ElMessage({
  //         type: 'success',
  //         message: '删除成功',
  //       })
  //       getList()
  //     }
  //   })
  // })
}
// 同意
const agree = (row: any) => {
  console.log(approveRef.value)
  approveRef.value.initDialog({
    radio: '1',
  })
}
// 驳回
const reject = (row: any) => {
  approveRef.value.initDialog({
    radio: '3',
  })
}
// 拒绝
const refuse = (row: any) => {
  approveRef.value.initDialog(
    {
      radio: '2',
    },
  )
}
// 取消
const cancel = (rowrow: any) => {
  ElMessageBox.confirm(
    '确认取消吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  // searchQuery.equipmentCategory = ''
  getList()
}
// 模板下载
const templateDownload = () => {

}
// 标签识别
const identify = () => {

}
// 新增
const add = () => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
// 表格被选中的行
const selectList = ref([])
// 表格多选
const multiSelect = (row) => {
  selectList.value = row
}
// 打印
function printList() {
  const selectIds = selectList.value.map(item => item.id)
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (selectIds.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, props.name)
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter(item => selectIds.includes(item.id))
    printJSON(printList, properties, props.name)
  }
  else {
    ElMessage('无可打印内容')
  }
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })

  // listExportApi({ ...searchQuery, limit: undefined, offset: undefined }).then((res) => {
  // if (selectList.value.length) {
  //   selectList.value.forEach((item) => {
  //     searchQuery.ids?.push(item.id as string)
  //   })
  // }
  //   exportFile(res.data, '固定资产列表')
  //   loading.close()
  // searchQuery.ids = []
  // }).catch((_) => {
  //   loading.close()
  // })
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  // if (event.target.files[0].type === 'application/pdf') {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    // listImporttApi(fd).then((res) => {
    //   if (res.code === 200) {
    //     ElMessage.success('上传成功')
    //   }
    //   else {
    //     ElMessage.error(res.message)
    //   }
    // })
  }
//   }
//   else {
//     ElMessage.error('请上传pdf格式')
//   }
}
// 批量导入
const batchImport = () => {
  fileRef.value.click()
}
// 传给子组件的刷新事件
const refreshDta = () => {
  getList()
  dialogVisible.value = false
}
// onMounted(() => {
//   getList()
// })
watch(() => props.type, (newValue) => {
  if (newValue === '0') {
    searchQuery.approvalStatus = ''
  }
  else {
    searchQuery.approvalStatus = newValue
  }
  getList()
}, {
  immediate: true,
  deep: true,
})
// watch(() => props.applyType, (newVal) => {
//   searchQuery.applyStatus = newVal
//   getList()
// }, {
//   immediate: true,
//   deep: true,
// })
</script>

<template>
  <div>
    <!-- 审批操作组件 -->
    <approve ref="approveRef" @reset-data="refreshDta" />
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input placeholder="申请编号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input placeholder="设备编号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input placeholder="设备名称" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input placeholder="申请单位" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-select placeholder="申请状态" clearable>
            <!-- <el-option v-for="item in []" :key="item.id" :label="item.name" :value="item.id" /> -->
          </el-select>
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <input v-show="(searchQuery.limit === 0)" ref="fileRef" type="file" multiple @change="onFileChange">
          <!-- <el-button type="primary" @click="batchImport">
            批量导入
          </el-button>
          <el-button type="primary" @click="templateDownload">
            模板下载
          </el-button> -->
          <icon-button icon="icon-add" title="新建" @click="add" />
          <icon-button icon="icon-export" title="导出" @click="exportExcelBtn" />
          <icon-button icon="icon-print" title="打印" @click="printList" />
          <!-- <el-button type="primary" @click="add">
            新建
          </el-button>
          <el-button type="primary" @click="exportExcelBtn">
            导出
          </el-button>
          <el-button v-print="printObj" type="primary">
            打印
          </el-button> -->
        </template>
        <!-- 表格区域 -->
        <normal-table
          id="print"
          :data="list" :total="total" :columns="columns as any"
          :is-showmulti-select="true"
          :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
          :list-loading="loadingTable"
          :is-multi="true"
          @change="changePage" @multi-select="multiSelect"
        >
          <template #preColumns>
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                {{ (searchQuery.offset - 1) * searchQuery.limit + scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>
          <template #columns>
            <el-table-column label="操作" align="center" width="230" fixed="right">
              <template #default="{ row }">
                <!-- <el-button size="small" type="primary" link @click="update(row)">
                  编辑
                </el-button> -->
                <el-button size="small" type="primary" link @click="detail(row)">
                  查看
                </el-button>
                <el-button size="small" type="primary" link @click="agree(row)">
                  同意
                </el-button>
                <el-button size="small" type="primary" link @click="reject(row)">
                  驳回
                </el-button>
                <el-button size="small" type="primary" link @click="refuse(row)">
                  拒绝
                </el-button>
                <el-button size="small" type="primary" link @click="cancel(row)">
                  取消
                </el-button>
                <el-button size="small" type="danger" link @click="remove(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>
