<script lang="ts" setup name="borrowApplyList">
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import approveAction from './approvalActionDialog.vue'
import { deleteApply, exportApply, getApplyList, submitApply } from '@/api/device/borrow'
import type{ searchType } from '@/views/device/borrow/borrow-interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
const props = defineProps({
  type: {
    type: String,
    required: true,
  },
})
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
const time = ref()
const searchQuery = reactive<searchType>({
  applyName: '', // 申请名称
  applyNo: '', // 申请编号
  applyPerson: '', // 	申请人
  applyUnit: '', // 	申请单位
  approvalStatus: '', // 	审批状态
  createUser: '', // 	创建人
  processResult: '', // 	处置结果
  time: '', // 	申请日期
  ids: [] as string[],
  limit: 20,
  offset: 1,
}) // 查询参数
watch(() => time.value, (newVal) => {
  if (newVal) {
    // searchQuery.noticeStartTime = newVal[0]
    // searchQuery.noticeEndTime = newVal[1]
  }
  else {
    // searchQuery.noticeStartTime = ''
    // searchQuery.noticeEndTime = ''
  }
})
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
// 全部状态的表格数据
const columns1 = ref([
  {
    text: '申请名称',
    value: 'applyName',
    align: 'center',
  },
  {
    text: '申请编号',
    value: 'applyNo',
    align: 'center',
  },
  {
    text: '文件号',
    value: 'fileNo',
    align: 'center',
  },
  {
    text: '类别',
    value: 'catergory',
    align: 'center',
  },
  {
    text: '创建人',
    value: 'createUser',
    align: 'center',
  },
  {
    text: '创建时间',
    value: 'createTime',
    width: '200',
    align: 'center',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
  },
])
// 其他状态的表格数据
const columns2 = ref([
  {
    text: '申请编号',
    value: 'applyNo',
    align: 'center',
  },
  {
    text: '申请名称',
    value: 'applyName',
    align: 'center',
  },
  {
    text: '申请部门',
    value: 'applyUnit',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'applyPerson',
    align: 'center',
  },
  {
    text: '申请时间',
    value: 'time',
    align: 'center',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
  },
])
const columns = computed(() => {
  // if (props.type !== '0') {
  //   return columns2.value
  // }
  // else {
  //   return columns1.value
  // }
  return columns2.value
})
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: '固定资产', // 打印配置页上方的标题
  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 getList = () => {
  loadingTable.value = true
  getApplyList(searchQuery).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows
      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) => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'detail',
    },
    query: {
      id: row.id,
      title: '详情',
      name: '设备借用申请',
      approvalStatus: props.type,
      approvalStatusName: row.approvalStatusName,
    },
  })
}
// 编辑
const update = (row) => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'edit',
    },
    query: {
      id: row.id,
      title: '编辑',
      name: '设备借用申请',
    },
  })
}
// 删除
const remove = (row) => {
  ElMessageBox.confirm(
    `确认删除${row.applyName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deleteApply({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getList()
        }
      })
    })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  searchQuery.applyName = ''
  searchQuery.applyNo = ''
  searchQuery.applyPerson = ''
  searchQuery.applyUnit = ''
  searchQuery.time = ''
  time.value = ''
  getList()
}
// 新增
const addBtn = () => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: '设备借用申请',
    },
  })
}
// 表格被选中的行
const selectList = ref([])
// 表格多选
const multiSelect = (row) => {
  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)
  //   })
  // }
  exportApply({ ...searchQuery, limit: undefined, offset: undefined }).then((res) => {
    exportFile(res.data, '设备借用申请')
    loading.close()
    // searchQuery.ids = []
  }).catch((_) => {
    loading.close()
  })
}
// 打印
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, '设备借用申请')
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter(item => selectIds.includes(item.id))
    printJSON(printList, properties, '设备借用申请')
  }
  else {
    ElMessage('无可打印内容')
  }
}
const approveRef = ref()
// 同意
const agree = (row: any) => {
  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 = (row: any) => {
  ElMessageBox.confirm(
    `确认取消${row.applyName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
}
// 提交
const submit = (row: any) => {
  ElMessageBox.confirm(
    `确认提交${row.applyName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    submitApply({ id: row.id }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交',
        })
        getList()
      }
    })
  })
}
const useDeptList = ref([])
onMounted(() => {
  getList()
  // 获取使用部门
  getDeptTreeList().then((res) => {
    if (res.data) { // 将列表转树结构
      useDeptList.value = toTreeList(res.data, '0', true)
    }
  })
})
watch(() => props.type, (newValue) => {
  if (newValue === '0') {
    searchQuery.approvalStatus = ''
  }
  else {
    searchQuery.approvalStatus = newValue
  }
  getList()
}, {
  immediate: true,
  deep: true,
})
// watch(() => searchQuery.time, (newVal) => {
//   console.log(newVal, 'time')
// })
</script>

<template>
  <div>
    <!-- 添加/编辑/查看 -->
    <app-container>
      <!-- 审批操作 -->
      <approve-action ref="approveRef" />
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.applyNo" placeholder="申请编号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.applyName" placeholder="申请名称" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <!-- <el-input v-model="searchQuery.applyUnit" placeholder="申请部门" clearable class="w-50 m-2" /> -->
          <dept-select v-model="searchQuery.applyUnit" placeholder="申请部门" :data="useDeptList" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.applyPerson" placeholder="申请人" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <!-- <el-input v-model="searchQuery.equipmentCategory" placeholder="设备类型" clearable class="w-50 m-2" /> -->
          <!-- <el-date-picker
            v-model="searchQuery.time" placeholder="申请日期" clearable class="w-50 m-2" type="daterange"
            start-placeholder="申请日期开始"
            end-placeholder="申请日期结束"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm"
          /> -->
          <el-date-picker
            v-model="time"
            type="datetimerange"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="申请开始时间"
            end-placeholder="申请结束时间"
            clearable
          />
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <icon-button icon="icon-add" title="新建" @click="addBtn" />
          <icon-button icon="icon-export" title="导出" @click="exportExcelBtn" />
          <icon-button 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 as number - 1) * (searchQuery.limit as number) + scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>
          <template #columns>
            <!-- 全部状态的操作栏 -->
            <el-table-column v-if="props.type === '0' || props.type === '2' || props.type === '3'" label="操作" align="center" width="230" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" link @click="detail(row)">
                  查看
                </el-button>
                <el-button size="small" type="primary" link :disabled="!(row.approvalStatusName === '审批中' || row.approvalStatusName === '待审批')" @click="agree(row)">
                  同意
                </el-button>
                <el-button size="small" type="primary" link :disabled="!(row.approvalStatusName === '审批中' || row.approvalStatusName === '待审批')" @click="reject(row)">
                  驳回
                </el-button>
                <el-button size="small" type="primary" link :disabled="!(row.approvalStatusName === '审批中' || row.approvalStatusName === '待审批')" @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>
            <!-- 草稿箱和已取消状态的操作栏 -->
            <el-table-column v-if="props.type === '1' || props.type === '6'" label="操作" align="center" width="170" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" link @click="detail(row)">
                  查看
                </el-button>
                <el-button size="small" type="primary" link @click="update(row)">
                  编辑
                </el-button>
                <el-button size="small" type="primary" link @click="submit(row)">
                  提交
                </el-button>
                <el-button size="small" type="danger" link @click="remove(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
            <!-- 未通过/已通过状态的操作栏 -->
            <el-table-column v-if="props.type === '4' || props.type === '5'" label="操作" align="center" width="90" fixed="right">
              <template #default="{ row }">
                <el-button 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>
// 样式
</style>
