<!-- 文件审批公共模板 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { DateModelType } from 'element-plus'
import type { TableRow } from './approve-interface'
import type { fileResType } from '@/views/measure/file/file-interface'
import { printJSON } from '@/utils/printUtils'
import { approvalCancel, approvalDelete, approvallistPageApi, approvallistPageDetailApi, deleteApi, exportFileApi, submitFile } 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'
import type { TableColumn } from '@/components/NormalTable/table_interface'
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  status: {
    type: String,
  },
  // approvalStatusMap: {
  //   type: Object,
  //   default: () => { return {} },
  // },
  // approvalStatusReserveMap: {
  //   type: Object,
  //   default: () => { return {} },
  // },
})
const { proxy } = getCurrentInstance() as any
const $route = useRoute()
const $router = useRouter()
const approvalStatus = ref('0')
// 审批状态字典
const approvalStatusMap = ref({}) as any // 审批状态字典{1：草稿箱}
const approvalStatusReserveMap = ref({}) as any // 审批状态字典{草稿箱: 1}
const activeTitle = ref('') // active对应的审批状态名字

const searchQuery = ref({
  fileNo: '', // 编号
  fileName: '', // 名称
  fileCode: '', // 文件号
  createUser: '', // 创建人
  createStartTime: '', // 创建开始时间
  createEndTime: '', // 创建结束时间
  approvalStatus: approvalStatus.value, // 审批状态
  limit: 20,
  offset: 1,
  fileType: '', // 文件类别
  formId: SCHEDULE.FILE_APPROVAL,
  ids: [] as string[],
}) // 查询参数
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref<TableColumn[]>([
  { text: '名称', value: 'fileName', align: 'center' },
  { text: '编号', value: 'fileNo', align: 'center', width: '160' },
  { text: '文件号', value: 'fileCode', align: 'center' },
  { text: '类别', value: 'fileTypeName', align: 'center' },
  { text: '创建人', value: 'createUser', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
  { text: '审批状态', value: 'approvalStatusName', align: 'center', width: '110' },
]) // 表格
const list = ref<TableRow[]>([]) // 表格数据
// 筛选时间段数据
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
// 时间变更
watch(timeRange, (val) => {
  if (val) {
    searchQuery.value.createStartTime = `${val[0]}`
    searchQuery.value.createEndTime = `${val[1]}`
  }
  else {
    searchQuery.value.createStartTime = ''
    searchQuery.value.createEndTime = ''
  }
})

// 获取字典
const getDict = () => {
  getDictByCode('approvalStatus').then((res) => {
    // 审批状态字典 {1：草稿箱}
    res.data.forEach((item: any) => {
      approvalStatusMap.value[`${item.value}`] = item.name
    })
    // 审批状态字典 {草稿箱: 1}
    res.data.forEach((item: any) => {
      approvalStatusReserveMap.value[item.name] = `${item.value}`
    })
  })
}
getDict()
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  approvallistPageApi(searchQuery.value).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows.map((item: TableRow) => {
        return {
          ...item,
          approvalStatus: approvalStatusMap.value[item.approvalStatus],
        }
      })
      total.value = res.data.total
    }
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}
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.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  getList()
}
// 详情
const detail = (row: TableRow) => {
  $router.push({
    name: 'approveDetail',
    query: {
      title: '详情',
      ...row,
    },
  })
}

const edit = (row: TableRow) => {
  $router.push({
    name: 'approveDetail',
    query: {
      title: '编辑',
      ...row,
    },
  })
}
// 删除
const remove = (row: TableRow) => {
  ElMessageBox.confirm(
    `确认删除${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      if (row.approvalStatusName == '待审批') {
        approvalDelete({ id: row.id, taskId: row.taskId }).then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getList()
          }
        })
      }
      else {
        deleteApi({ id: row.id }).then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getList()
          }
        })
      }
    })
}
// 取消
const cancel = (row: TableRow) => {
  const { processId } = row
  ElMessageBox.confirm(
    `确认取消${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      approvalCancel({
        comments: '',
        processInstanceId: processId,
      }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          getList()
        }
      })
    })
}

// 提交
const submit = (row: TableRow) => {
  const { id, processId } = row
  const postData = { id, formId: SCHEDULE.FILE_APPROVAL, ...row.approvalStatusName === '已取消' && { processId } }
  ElMessageBox.confirm(
    `确认提交${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      submitFile(postData).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '提交成功',
          })
          getList()
        }
      })
    })
}
// 搜索
const search = () => {
  getList()
}
// 审批结束回调
const approvalSuccess = () => {
  search()
}
const approvalDialog = ref()
// 审批操作
const approval = (type: string, processId: string) => {
  approvalDialog.value.initDialog(type, processId)
}
// 重置
const reset = () => {
  searchQuery.value = {
    fileNo: '', // 编号
    fileName: '', // 名称
    fileCode: '', // 文件号
    createUser: '', // 创建人
    createStartTime: '', // 创建开始时间
    createEndTime: '', // 创建结束时间
    approvalStatus: searchQuery.value.approvalStatus, // 审批状态
    limit: 20,
    offset: 1,
    fileType: '', // 文件类别
    formId: SCHEDULE.FILE_APPROVAL,
    ids: [] as string[],
  }
  timeRange.value = ['', '']
  getList()
}
// 表格被选中的行
const selectList = ref<TableRow[]>([])
// 表格多选
const multiSelect = (row: TableRow[]) => {
  selectList.value = row
}
// 打印
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 approvalStatusListTow = {
  '全部': '0',
  '草稿箱': '1',
  '待审批': '2',
  '审批中': '3',
  '已通过': '4',
  '未通过': '5',
  '已取消': '6',
  '非草稿': '7',
  '未通过-驳回': '8',
} as any
// watch(() => props.name, async (newVal) => {
//   await getDict()
//   console.log('===', approvalStatusReserveMap.value)

//   window.sessionStorage.setItem('approveFileMenu', newVal)
//   sessionStorage.setItem('approveFileMenu', newVal!)
//   approvalStatus.value = approvalStatusListTow[newVal]
//   searchQuery.value.approvalStatus = approvalStatus.value
//   $router.currentRoute.value.query.cacheActive = searchQuery.value.approvalStatus

//   getList()
//   // 缓存名称
// },
// { deep: true },
// )
onMounted(async () => {
  await getDict()
  const getApproveFileMenu = window.sessionStorage.getItem('approveFileMenu')
  if (getApproveFileMenu === undefined || getApproveFileMenu === 'undefined' || getApproveFileMenu === 'null' || getApproveFileMenu === null || getApproveFileMenu === '') {
    approvalStatus.value = '0' // 全部
  }
  else {
    approvalStatus.value = approvalStatusListTow[getApproveFileMenu!] as string
    searchQuery.value.approvalStatus = approvalStatus.value
  }
  if ($route.query.fromModule === 'workbench') {
    approvalStatus.value = '2' // 待审批
  }
  getFileType()
  getList()
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <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="timeRange"
            type="datetimerange"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="创建开始时间"
            end-placeholder="创建结束时间"
            clearable
            style="width: 360px;"
          />
        </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 v-if="proxy.hasPerm('/file/approve/print')" icon="icon-print" title="打印" @click="printList" />
        </template>
        <!-- 表格区域 -->
        <normal-table
          id="print" :data="list" :total="total" :columns="columns"
          :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" fixed="right" :width="(activeTitle === '全部') ? 150 : (activeTitle === '草稿箱' || activeTitle === '已取消') ? 150 : (activeTitle === '已通过' || activeTitle === '未通过' || activeTitle === '审批中') ? 100 : 150">
              <template #default="{ row }">
                <el-button size="small" type="primary" link @click="detail(row)">
                  查看
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.edit.if(row, '/file/approve/edit')"
                  size="small" type="primary" link @click="edit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.submit.if(row)"
                  size="small"
                  type="primary" link
                  @click="submit(row)"
                >
                  提交
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.agree.if(row, '/file/approve/agree')"
                  size="small"
                  type="primary" link :disabled="proxy.buttonPerm.agree.disabled(row)"
                  @click="approval('agree', row.taskId)"
                >
                  同意
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.reject.if(row, '/file/approve/reject')"
                  size="small"
                  type="primary" link
                  :disabled="proxy.buttonPerm.reject.disabled(row)"
                  @click="approval('reject', row.taskId)"
                >
                  驳回
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.refuse.if(row, '/file/approve/refuse')"
                  size="small" type="danger" link
                  :disabled="proxy.buttonPerm.refuse.disabled(row)"
                  @click="approval('refuse', row.taskId)"
                >
                  拒绝
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.cancel.if(row, '/file/approve/cancle')"
                  :disabled="proxy.buttonPerm.cancel.disabled(row)"
                  size="small" type="info"
                  link @click="cancel(row)"
                >
                  取消
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.delete.if(row, '/file/approve/delete')"
                  :disabled="proxy.buttonPerm.delete.disabled(row)" size="small" type="danger" 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>
