<!-- 文件审批公共模板 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { fileResType } from '@/views/measure/file/file-interface'
import { printJSON } from '@/utils/printUtils'
import { approvallistPageApi, approvallistPageDetailApi } from '@/api/measure/file'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { getDictByCode } from '@/api/system/dict'
import { exportFile } from '@/utils/exportUtils'
import { SCHEDULE } from '@/utils/scheduleDict'
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
})
const $router = useRouter()
const approvalStatus = ref('0')
watch(() => props.name, (_) => {
  //  获取当前状态
  getDictByCode('approvalStatus').then((res) => {
    approvalStatus.value = res.data.filter((item: fileResType) => item.name === props.name)[0].value || '0'
  })
},
{
  deep: true,
  immediate: true,
})
const searchQuery = reactive({
  fileNo: '', // 编号
  fileName: '', // 名称
  fileCode: '', // 文件号
  createUser: '', // 创建人
  createTime: '', // 创建
  approvalStatus: approvalStatus.value, // 审批状态
  limit: 20,
  offset: 1,
  fileType: '', // 文件类别
  formId: SCHEDULE.FILE_APPROVAL,
  ids: [],
}) // 查询参数
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref([
  { text: '名称', value: 'fileName', align: 'center' },
  { text: '编号', value: 'fileNo', align: 'center' },
  { text: '文件号', value: 'fileCode', align: 'center' },
  { text: '类别', value: 'fileType', align: 'center' },
  { text: '创建人', value: 'create', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center' },
  { text: '审批状态', value: 'approvalStatusName', align: 'center' },
]) // 表格
const list = ref([]) // 表格数据
// 获取数据列表
const getList = () => {
  // loadingTable.value = true
  // approvallistPageApi(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 = [
    {
      approvalStatus: '1',
      approvalStatusName: '草稿箱',
      createUser: '张三',
      fileName: 'test',
      fileNo: '1234',
      fileCode: '1234',
      fileTypeName: '计量文件1',
      createTime: '2022-12-12 00:00:00',
      create: '张三3',
    },
    {
      approvalStatus: '3',
      approvalStatusName: '审批中',
      createUser: '张三',
      fileName: 'test',
      fileNo: '1234',
      fileCode: '1234',
      fileTypeName: '计量文件2',
      createTime: '2022-12-12 00:00:00',
      create: '张三2',
    },
    {
      approvalStatus: '5',
      approvalStatusName: '未通过',
      createUser: '张三',
      fileName: 'test',
      fileNo: '1234',
      fileCode: '1234',
      fileTypeName: '计量文件3',
      createTime: '2022-12-12 00:00:00',
      create: '张三1',
    },
  ] as any
  total.value = 1
}
const fileTypeList = ref<fileResType[]>([])
// 获取文件类别
const getFileType = () => {
  getDictByCode('fileType').then((res) => {
    fileTypeList.value = res.data
  })
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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: 'approveDetail',
    query: {
      title: '详情',
      ...row,
    },
  })
}
// 删除
const remove = (row) => {
  ElMessageBox.confirm(
    `确认删除${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      console.log('确认删除')
    })
}
// 取消
const cancel = (row) => {
  ElMessageBox.confirm(
    `确认取消${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      console.log('确认取消')
    })
}
// 搜索
const search = () => {
  getList()
}
// 审批结束回调
const approvalSuccess = () => {
  search()
}
const approvalDialog = ref()
// 审批操作
const approval = (type: string, taskId: string) => {
  approvalDialog.value.initDialog(type, taskId)
}
// 重置
const reset = () => {
  searchQuery.fileNo = ''
  searchQuery.fileName = ''
  searchQuery.fileCode = ''
  getList()
}
// 表格被选中的行
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)
    })
  }
  exportFileApi({ ...searchQuery, limit: undefined, offset: undefined }).then((res) => {
    exportFile(res.data, props.name)
    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, 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 isApproval = computed(() => {
  return (row) => {
    if (row.approvalStatusName === '审批中' || row.approvalStatusName === '待审批') {
      return true
    }
    else {
      return false
    }
  }
})
// 是否已通过或者未通过
const isPass = computed(() => {
  return (row) => {
    if (row.approvalStatusName === '已通过' || row.approvalStatusName === '未通过') {
      return true
    }
    else {
      return false
    }
  }
})
onMounted(() => {
  getFileType()
  getList()
})
</script>

<template>
  <div>
    <!-- <add-dialog v-show="dialogVisible" ref="addRef" @reset-data="refreshDta" /> -->
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.fileNo" placeholder="编号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.fileName" placeholder="名称" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.fileCode" placeholder="文件号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.fileType" class="m-2" placeholder="文件类别" clearable>
            <el-option
              v-for="item in fileTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-date-picker
            v-model="searchQuery.createTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="创建时间"
          />
          <!-- <el-date-picker
            v-model="searchQuery.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
          /> -->
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.createUser" placeholder="创建人" clearable class="w-50 m-2" />
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <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"
          :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
          :list-loading="loadingTable"
          :is-showmulti-select="true"
          :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="250">
              <template #default="{ row }">
                <el-button size="small" type="primary" link @click="detail(row)">
                  查看
                </el-button>
                <el-button size="small" type="primary" link :disabled="!isApproval(row)" @click="approval('agree', row.taskId)">
                  同意
                </el-button>
                <el-button size="small" type="primary" link :disabled="!isApproval(row)" @click="approval('reject', row.taskId)">
                  驳回
                </el-button>
                <el-button size="small" type="primary" link :disabled="!isApproval(row)" @click="approval('refuse', row.taskId)">
                  拒绝
                </el-button>
                <el-button size="small" type="primary" link :disabled="!isApproval(row)" @click="cancel(row)">
                  取消
                </el-button>
                <el-button size="small" type="danger" :disabled="isPass(row)" link @click="remove(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
      <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    </app-container>
  </div>
</template>

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

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

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

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