<!-- 计量组织公共模板 -->
<script lang="ts" setup>
import { ElLoading, ElMessage } from 'element-plus'
import type { rowType, searchQueryType } from '../measureDept-interface'
import type { fileResType } from '@/views/measure/file/file-interface'
import { exportApi, getpDeptApi, listPageApi } from '@/api/measure/measureDept'
import { getDictByCode } from '@/api/system/dict'
import { printJSON } from '@/utils/printUtils'
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 $router = useRouter()
const $route = useRoute()
const { proxy } = getCurrentInstance() as any
const createTime = ref()
const searchQuery = reactive<searchQueryType>({
  organizeNo: '', // 组织编号
  organizeName: '', // 名称
  limit: 20,
  offset: 1,
  organizeType: '', // 类型
  createEndTime: '',
  createStartTime: '',
  director: '', // 负责人
  meterMajor: '', // 专业
  pDeptId: '', // 所属科室
  ids: [] as string[],
}) // 查询参数
watch(() => createTime.value, (newVal) => {
  if (newVal) {
    searchQuery.createStartTime = newVal[0]
    searchQuery.createEndTime = newVal[1]
  }
  else {
    searchQuery.createStartTime = ''
    searchQuery.createEndTime = ''
  }
})
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 list = ref<rowType[]>([]) // 表格数据
// 获取类型
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: '', // 创建时间
    createEndTime: '',
    createStartTime: '',
    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 as rowType[]).map(item => ({ ...item, createTime: item.createTime.split(' ')[0] }))
      total.value = res.data.total
      if (props.authority === 'gcz') {
        list.value.forEach(async (item) => {
          const res = await getpDeptApi({ deptId: item.deptId })
          item.pDeptName = res.data.pDeptName
        })
      }
    }
    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) => {
  $router.push({
    path: '/measureDept/detail',
    query: {
      ...row,
      title: `${props.name}-详情`,
      path: $route.path.split('/')[2],
    },
  })
  // dialogVisible.value = true
  // addRef.value.initDialog()
}
// 编辑
const update = (row: rowType) => {
  $router.push({
    path: '/measureDept/edit',
    query: {
      ...row,
      title: `${props.name}-编辑`,
      path: $route.path.split('/')[2],
    },
  })
  // dialogVisible.value = true
  // addRef.value.initDialog({
  //   ...row,
  //   title: `${props.name}-编辑`,
  // })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  createTime.value = ''
  searchQuery.organizeNo = '' // 组织编号
  searchQuery.organizeName = '' // 名称
  searchQuery.pDeptId = ''
  searchQuery.limit = 10
  searchQuery.offset = 1
  searchQuery.director = '' // 负责人
  searchQuery.meterMajor = '' // 专业
  getList()
}
// 表格被选中的行
const selectList = ref<rowType[]>([])
// 表格多选
const multiSelect = (row: rowType[]) => {
  selectList.value = row
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (selectList.value.length) {
    selectList.value.forEach((item) => {
      searchQuery.ids?.push(item.id as string)
    })
  }
  exportApi(searchQuery).then((res) => {
    exportFile(res.data, props.name)
    loading.close()
    searchQuery.ids = []
  }).catch((_) => {
    loading.close()
  })
}
// 打印
function printList() {
  const selectIds = selectList.value.map((item: rowType) => 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: rowType) => selectIds.includes(item.id))
    printJSON(printList, properties, props.name)
  }
  else {
    ElMessage('无可打印内容')
  }
}
// 传给子组件的刷新事件
const refreshDta = () => {
  getList()
}
onMounted(() => {
  getDepartmentList()
  getType().then((_) => {
    getList()
  })
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <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="所属科室" clearable>
            <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="createTime"
            type="datetimerange"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="创建开始时间"
            end-placeholder="创建结束时间"
            clearable
          />
          <!-- <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> -->
          <icon-button v-if="proxy.hasPerm(`/measure/measureDept/${authority}/export`)" icon="icon-export" title="导出" @click="exportExcelBtn" />
          <icon-button v-if="proxy.hasPerm(`/measure/measureDept/${authority}/print`)" icon="icon-print" title="打印" @click="printList" />
        </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="110">
              <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>
