<!-- 设备台账公共模板 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { selectType } from '../standingBook-interface'
import addDialog from './templateAdd.vue'
import { getDictByCode } from '@/api/system/dict'
import { uploadApi } from '@/api/system/notice'
import comTreeSelect from '@/views/system/user/selecTree.vue'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  authority: {
    type: String,
    required: true,
  },
})
const { proxy } = getCurrentInstance() as any
const searchQuery = reactive({
  equipmentNo: '', // 设备编号
  equipmentName: '', // 名称
  mesureType: '', // 鉴定方式
  managerState: '', // 管理状态
  useDept: '', // 使用部门
  validDate: '', // 有效日期
  abc: '',
  limit: 10,
  offset: 1,
}) // 查询参数
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref([
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
  },
  {
    text: '名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
  },
  {
    text: 'ABC',
    value: 'abc',
    align: 'center',
  },
  {
    text: '检定方式',
    value: 'mesureTypeName',
    align: 'center',
  },
  {
    text: '管理状态',
    value: 'managerStateName',
    align: 'center',
  },
  {
    text: '使用部门',
    value: 'useDeptName',
    align: 'center',
  },
  {
    text: '使用人',
    value: 'usePersonName',
    align: 'center',
  },
  {
    text: '有效日期',
    value: 'validDate',
    align: 'center',
  },
  {
    text: '备注',
    value: 'remark',
    align: 'center',
  },
]) // 表格
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: props.name, // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewBeforeOpenCallback() { console.log('正在加载预览窗口！') }, // 预览窗口打开之前的callback
  previewOpenCallback() { console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
  beforeOpenCallback() { console.log('开始打印之前！') }, // 开始打印之前的callback
  openCallback() { console.log('执行打印了！') }, // 调用打印时的callback
  closeCallback() { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() { console.log('点击v-print绑定的按钮了！') },
  // url: 'http://localhost:8080/', // 打印指定的URL，确保同源策略相同
  // asyncUrl (reslove) {
  //   setTimeout(() => {
  //     reslove('http://localhost:8080/')
  //   }, 2000)
  // },
  standard: '',
  extarCss: '',
})
const list = ref([]) // 表格数据
const addRef = ref() // 添加/编辑/详情/组件
const dialogVisible = ref<boolean>(false) // 添加组件的显示与隐藏
const deptProps = reactive({
  parent: 'pid', value: 'id', label: 'name', children: 'children',
})
// 获取数据
const useDeptList = ref([])
const mesureTypeList = ref<selectType[]>([])
const managerStateList = ref<selectType[]>([])
const abcList = ref<selectType[]>([])
const fetchData = () => {
  // 获取使用部门
  getDeptTreeList().then((res) => {
    if (res.data) { // 将列表转树结构
      useDeptList.value = toTreeList(res.data, '0', true)
    }
  })
  // 获取检定方式
  getDictByCode('mesureType').then((response) => {
    mesureTypeList.value = response.data
  })
  // 获取管理状态
  getDictByCode('managerState').then((response) => {
    managerStateList.value = response.data
  })
  // 获取ABC
  getDictByCode('ABC').then((response) => {
    abcList.value = response.data
  })
}
// 获取数据列表
const getList = () => {
  // loadingTable.value = true
  // listPageApi(searchQuery).then((res) => {
  //   if (res.code === 200) {
  //     list.value = res.data.rows
  //     total.value = res.data.total
  //   }
  //   loadingTable.value = false
  // }).catch((_) => {
  //   loadingTable.value = false
  // })
  setTimeout(() => {
    list.value = [
      {
        equipmentNo: 123,
        equipmentName: 'test',
        modelNo: '001',
        usePersonName: '张三',
        validDate: '2022-12-12 00:00:00',
        useDeptName: '顶级',
      },
    ]
    total.value = 1
  }, 1000)
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 title = ref('')
const row = ref()
// 详情
const detail = (row) => {
  dialogVisible.value = true
  title.value = '详情'
  row.value = row
  // addRef.value.initDialog({
  //   title: '详情',
  //   name: props.name,
  // })
}
// 编辑
const update = (row) => {
  dialogVisible.value = true
  title.value = '编辑'
  row.value = row
  // addRef.value.initDialog({
  //   title: '编辑',
  //   name: props.name,
  // })
}
// 删除
const remove = (row) => {
  ElMessageBox.confirm(
    `确认删除${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      // deleteApi({ id: row.id as string }).then((res) => {
      //   if (res.code === 200) {
      //     ElMessage({
      //       type: 'success',
      //       message: '删除成功',
      //     })
      //     getList()
      //   }
      // })
    })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  // searchQuery.fileNo = ''
  getList()
}
// 模板下载
const templateDownload = () => {

}
// 新增
const add = () => {
  dialogVisible.value = true
  title.value = '新建'
  row.value = {}
}
// 标签识别
const identify = () => {

}
// 导出
const exportExcelBtn = () => {
  // const loading = ElLoading.service({
  //   lock: true,
  //   text: 'Loading',
  //   background: 'rgba(255, 255, 255, 0.8)',
  // })

  // exportFileApi({ ...searchQuery, limit: undefined, offset: undefined }).then((res) => {
  //   exportFile(res.data, props.name)
  //   loading.close()
  // }).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])
    uploadApi(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()
  fetchData()
})
</script>

<template>
  <div>
    <add-dialog v-if="dialogVisible" ref="addRef" :title="title" :name="props.name" :row="row" @reset-data="refreshDta" />
    <!-- 布局 -->
    <app-container v-show="!dialogVisible">
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.equipmentNo" placeholder="设备编号" clearable class="w-50 m-2 normal-input" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.equipmentName" placeholder="名称" clearable class="w-50 m-2 normal-input" />
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.mesureType" class="m-2 normal-select" placeholder="检定方式" clearable>
            <el-option
              v-for="item in mesureTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.managerState" class="m-2 normal-select" placeholder="管理状态" clearable>
            <el-option
              v-for="item in managerStateList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <com-tree-select
            v-model="searchQuery.useDept" :options="useDeptList" placeholder="使用部门"
            :tree-props="deptProps" style="width: 150px;"
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="searchQuery.validDate" type="datetime" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="有效日期"
            class="normal-date"
            style="width: 150px;"
          />
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.abc" class="m-2 normal-select" placeholder="ABC" clearable>
            <el-option
              v-for="item in abcList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </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 v-if="proxy.hasPerm(`/device/${$props.authority}/identify`)" type="primary" @click="identify">
            标签识别
          </el-button>
          <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/import`)" type="primary" @click="batchImport">
            批量导入
          </el-button>
          <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/mould`)" type="primary" @click="templateDownload">
            模板下载
          </el-button>
          <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/add`)" type="primary" @click="add">
            新建
          </el-button>
          <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/export`)" type="primary" @click="exportExcelBtn">
            导出
          </el-button>
          <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/print`)" 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"
          @change="changePage"
        >
          <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="200">
              <template #default="{ row }">
                <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/update`)" size="small" type="primary" link @click="update(row)">
                  编辑
                </el-button>
                <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/detail`)" size="small" type="primary" link @click="detail(row)">
                  详情
                </el-button>
                <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/delete`)" size="small" type="danger" link @click="remove(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>

<style lang="scss" scoped>
.normal-input {
  width: 154px !important;
}

.normal-date {
  width: 154px !important;
}

.normal-select {
  width: 154px !important;
}

:deep(.el-table__header) {
  background-color: #bbb;
}
</style>
