<!-- 计量组织公共模板 -->
<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import type { rowType, searchQueryType } from '../measureDept-interface'
import addDialog from './addDialog.vue'
import type { fileResType } from '@/views/measure/file/file-interface'
import { exportApi, listPageApi } from '@/api/measure/measureDept'
import { getDictByCode } from '@/api/system/dict'
import { exportFile } from '@/utils/exportUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
const props = defineProps({
  name: {
    type: String,
    required: true,
  },
  authority: {
    type: String,
    required: true,
  },
})
const { proxy } = getCurrentInstance() as any
const searchQuery = reactive<searchQueryType>({
  organizeNo: '', // 组织编号
  organizeName: '', // 名称
  limit: 10,
  offset: 1,
  organizeType: '', // 类型
  createTime: '', // 创建时间
  director: '', // 负责人
  meterMajor: '', // 专业
  pDeptId: '', // 所属科室
}) // 查询参数
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
// 表格数据根据不同组织筛选
const columnsData = ref<{ name: string;columns: TableColumn[] }[]>([
  {
    name: '计量组织-部门',
    columns: [
      { text: '部门编号', value: 'organizeNo', align: 'center' },
      { text: '部门名称', value: 'organizeName', align: 'center' },
      { text: '负责人', value: 'director', align: 'center' },
      { text: '技术职务', value: 'technologyJobName', align: 'center' },
      { text: '行政职务', value: 'administrationJobName', align: 'center' },
      { text: '联系方式', value: 'phone', align: 'center' },
      { text: '创建日期', value: 'createTime', align: 'center' },
    ],
  },
  {
    name: '计量组织-科室',
    columns: [
      { text: '科室编号', value: 'organizeNo', align: 'center' },
      { text: '科室名称', value: 'organizeName', align: 'center' },
      { text: '专业', value: 'meterMajor', align: 'center' },
      { text: '负责人', value: 'director', align: 'center' },
      { text: '技术职务', value: 'technologyJobName', align: 'center' },
      { text: '行政职务', value: 'administrationJobName', align: 'center' },
      { text: '联系方式', value: 'phone', align: 'center' },
      { text: '创建日期', value: 'createTime', align: 'center' },
    ],
  },
  {
    name: '计量组织-工程组',
    columns: [
      { text: '工程组编号', value: 'organizeNo', align: 'center' },
      { text: '工程组名', value: 'organizeName', align: 'center' },
      { text: '计量专业', value: 'meterMajor', align: 'center' },
      { text: '负责人', value: 'director', align: 'center' },
      { text: '联系方式', value: 'phone', align: 'center' },
      { text: '所属科室', value: 'pDeptName', align: 'center' },
      { text: '科室负责人', value: '', align: 'center' },
      { text: '创建日期', value: 'createTime', align: 'center' },
    ],
  },
])
const columns = computed(() => {
  return columnsData.value.filter((item: { name: string;columns: TableColumn[] }) => item.name === props.name)[0].columns
})
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绑定的按钮了！') },
  standard: '',
  extarCss: '',
})
const list = ref([]) // 表格数据
const addRef = ref() // 编辑/详情/组件
const dialogVisible = ref<boolean>(false) // 添加组件的显示与隐藏
// 获取类型
const getType = async () => {
  const res = await getDictByCode('deptType')
  searchQuery.organizeType = res.data.filter((item: fileResType) => item.name === props.name)[0].value
}
const DepartmentList = ref()
// 获取科室/工程组信息
const getDepartmentList = () => {
  listPageApi({
    organizeNo: '',
    organizeName: '',
    limit: 99999,
    offset: 1,
    organizeType: '3',
    createTime: '', // 创建时间
    director: '', // 负责人
    meterMajor: '', // 专业
    pDeptId: '', // 所属科室
  }).then((res) => {
    DepartmentList.value = res.data.rows
  })
}
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  listPageApi(searchQuery).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows.map(item => ({ ...item, createTime: item.createTime.split(' ')[0] }))
      total.value = res.data.total
    }
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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: rowType) => {
  dialogVisible.value = true
  addRef.value.initDialog({
    ...row,
    title: `${props.name}-详情`,
  })
}
// 编辑
const update = (row: rowType) => {
  dialogVisible.value = true
  addRef.value.initDialog({
    ...row,
    title: `${props.name}-编辑`,
  })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  searchQuery.organizeNo = '' // 组织编号
  searchQuery.organizeName = '' // 名称
  searchQuery.limit = 10
  searchQuery.offset = 1
  searchQuery.createTime = '' // 创建时间
  searchQuery.director = '' // 负责人
  searchQuery.meterMajor = '' // 专业
  getList()
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  exportApi(searchQuery).then((res) => {
    exportFile(res.data, props.name)
    loading.close()
  }).catch((_) => {
    loading.close()
  })
}
// 传给子组件的刷新事件
const refreshDta = () => {
  getList()
  dialogVisible.value = false
}
onMounted(() => {
  getDepartmentList()
  getType().then((_) => {
    getList()
  })
})
</script>

<template>
  <div>
    <add-dialog v-show="dialogVisible" ref="addRef" @reset-data="refreshDta" />
    <!-- 布局 -->
    <app-container v-show="!dialogVisible">
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.organizeNo" :placeholder="`${props.name.split('-')[1]}编号`" clearable class="w-50 m-2 " />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.organizeName" :placeholder="`${props.name.split('-')[1]}名称`" clearable class="w-50 m-2 " />
        </search-item>
        <search-item>
          <el-input v-if="props.name.split('-')[1] !== '部门'" v-model="searchQuery.meterMajor" placeholder="专业" clearable class="w-50 m-2 " />
        </search-item>
        <search-item>
          <el-input v-if="props.name.split('-')[1] !== '部门'" v-model="searchQuery.director" placeholder="负责人" clearable class="w-50 m-2 " />
        </search-item>
        <search-item>
          <el-select v-if="props.name.split('-')[1] === '工程组'" v-model="searchQuery.pDeptId" placeholder="所属科室">
            <el-option v-for="item in DepartmentList" :key="item.deptId" :label="item.organizeName" :value="item.deptId" />
          </el-select>
        </search-item>
        <search-item>
          <el-date-picker
            v-if="props.name.split('-')[1] === '科室'"
            v-model="searchQuery.createTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="创建时间"
          />
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <el-button v-if="proxy.hasPerm(`/measure/measureDept/${authority}/export`)" type="primary" @click="exportExcelBtn">
            导出
          </el-button>
          <el-button v-if="proxy.hasPerm(`/measure/measureDept/${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="150">
              <template #default="{ row }">
                <el-button v-if="proxy.hasPerm(`/measure/measureDept/${authority}/update`)" size="small" type="primary" link @click="update(row)">
                  编辑
                </el-button>
                <el-button v-if="proxy.hasPerm(`/measure/measureDept/${authority}/detail`)" size="small" type="primary" link @click="detail(row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>

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

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

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

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