<!-- 印章使用登记 -->
<script name="SealNoteList" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { DateModelType } from 'element-plus'
import type{ IListQuery, ISealNoteInfo } from './seal-note'
import NoteApprovalDialog from './noteApprovalDialog.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { deleteSealNoteDraft, deleteSealNoteRevoked, getSealNoteList } from '@/api/resource/seal'
import { getDictByCode } from '@/api/system/dict'
import type { IMenu } from '@/components/buttonBox/buttonBox'
import type { IDictType } from '@/commonInterface/resource-interface'

// 定义常量
const buttonBoxActive = 'sealNoteApproval' // 存储在sessionstorage里面的字段名，用于记录右上角buttonbox点击状态
const flowFormId = 'zyglyzsydj' // 资源管理 - 印章使用登记

const { proxy } = getCurrentInstance() as any
const router = useRouter()

// 选中的审批状态按钮
const active = ref('')
const menu = ref<IMenu[]>([]) // 审批状态按钮组合
const approvalStatusList = ref<String[]>([
  '全部', '已审批', '草稿箱', '待审批', '审批中', '已通过', '未通过', '已取消', '我的审批单',
])

// 弹窗子组件
const apprDial = ref()

// 查询条件
const searchQuery = ref<IListQuery>({
  sealName: '', // 印章名称
  sealType: '', // 印章类型
  applyDeptName: '',
  applyUserName: '',
  applyTimeStart: '', // 创建时间-起始
  applyTimeEnd: '', // 创建时间-结束
  approvalStatus: active.value, // 审批状态
  formId: flowFormId, // 表单id（流程定义对应的表单id，等价于业务id），此处为固定值
  offset: 1,
  limit: 20,
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '申请单编号', value: 'noteFormNo', align: 'center', width: '180' },
  { text: '印章名称', value: 'sealName', align: 'center' },
  { text: '印章类型', value: 'sealTypeName', align: 'center' },
  { text: '批准人', value: 'createUserName', align: 'center', width: '150' },
  { text: '申请部门', value: 'applyDeptName', align: 'center', width: '150' },
  { text: '申请人', value: 'applyUserName', align: 'center', width: '150' },
  { text: '申请时间', value: 'applyTime', align: 'center', width: '180' },
])
const sealNoteList = ref<Array<ISealNoteInfo>>([]) // 表格数据

const sealTypeDict = ref<Array<IDictType>>([])

const reset = () => {
  searchQuery.value = {
    sealName: '', // 印章名称
    sealType: '', // 印章类型
    applyDeptName: '',
    applyUserName: '',
    applyTimeStart: '', // 创建时间-起始
    applyTimeEnd: '', // 创建时间-结束
    approvalStatus: active.value, // 审批状态
    formId: flowFormId, // 表单id（流程定义对应的表单id，等价于业务id），此处为固定值
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  fetchData(true)
}

const searchList = () => {
  fetchData(true)
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getSealNoteList(searchQuery.value).then((response) => {
    if (response.code === 200) {
      sealNoteList.value = response.data.rows

      total.value = parseInt(response.data.total)
    }
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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
  }
  fetchData(true)
}

const addSealNote = () => {
  router.push({
    query: {
      type: 'create',
    },
    path: 'note/detail',
  })
}

const detail = (row: ISealNoteInfo) => {
  if (active.value === '1') {
    // 草稿箱 状态下的查看 可以编辑
    sessionStorage.setItem('sealNoteInfo', JSON.stringify(row))
    router.push({
      query: {
        type: 'update',
        id: row.id,
        status: active.value,
      },
      path: 'note/detail',
    })
  }
  else {
    sessionStorage.setItem('sealNoteInfo', JSON.stringify(row))
    router.push({
      query: {
        type: 'detail',
        id: row.id,
        status: active.value,
      },
      path: 'note/detail',
    })
  }
}

// 删除
const deleteSuggestById = (row: ISealNoteInfo) => {
  ElMessageBox.confirm(
    `确认删除使用登记表 ${row.noteFormNo} 吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    if (active.value === '0' || active.value === '1') {
      // 全部 及 草稿箱 中删除
      deleteSealNoteDraft({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success(`使用登记表 ${row.noteFormNo} 删除成功`)
          fetchData(true)
        }
        else {
          ElMessage.error(`使用登记表 ${row.noteFormNo} 删除失败：${res.message}`)
        }
      })
    }
    else if (active.value === '6') {
      // 已取消 中删除
      deleteSealNoteRevoked({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success(`使用登记表 ${row.noteFormNo} 删除成功`)
          fetchData(true)
        }
        else {
          ElMessage.error(`使用登记表 ${row.noteFormNo} 删除失败：${res.message}`)
        }
      })
    }
  })
}

// 审批按钮点击切换事件
const changeCurrentButton = (val: string) => {
  active.value = val // 此时的tab
  sessionStorage.setItem(buttonBoxActive, val) // 记录tab状态

  reset() // 刷新
}

// 流程审批-同意
const approvalAgreeHandler = (row: ISealNoteInfo) => {
  apprDial.value.initDialog('agree', row.id, row.taskId, '')
}

// 流程审批-拒绝
const approvalRefuseHandler = (row: ISealNoteInfo) => {
  apprDial.value.initDialog('refuse', row.id, row.taskId, '')
}

// 取消（撤回审批单）
const revokeApprById = (row: ISealNoteInfo) => {
  apprDial.value.initDialog('revoke', row.id, row.taskId, row.processId)
}

// 流程操作之后刷新
const afterApprovalHandler = () => {
  fetchData(true)
}

// 初始化流程审批状态按钮
const getApprovalStatusDict = async () => {
  await getDictByCode('approvalStatus').then((res) => {
    if (res.code === 200) {
      res.data.forEach((item: IDictType) => {
        if (approvalStatusList.value.includes(item.name)) {
          menu.value.push({
            name: item.name,
            id: `${item.value}`,
          })
        }
      })
    }
  })
}

// 获取印章类型
const getSealTypeDict = async () => {
  await getDictByCode('bizSealType').then((res: any) => {
    if (res.code === 200) {
      sealTypeDict.value = res.data
    }
  })
}

const getDict = async () => {
  await getApprovalStatusDict()
  await getSealTypeDict()
}

watch(dateRange, (val) => {
  if (val) {
    searchQuery.value.applyTimeStart = dayjs(val[0]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[0]).format('YYYY-MM-DD')
    searchQuery.value.applyTimeEnd = dayjs(val[1]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[1]).format('YYYY-MM-DD')
  }
  else {
    searchQuery.value.applyTimeStart = ''
    searchQuery.value.applyTimeEnd = ''
  }
})

onMounted(async () => {
  await getDict()
  if (sessionStorage.getItem(buttonBoxActive) !== undefined && sessionStorage.getItem(buttonBoxActive) !== null) {
    active.value = sessionStorage.getItem(buttonBoxActive)!
  }
  else {
    active.value = '0' // 全部
  }
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.sealName" placeholder="印章名称" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.sealType" placeholder="印章类型" clearable>
          <el-option v-for="item in sealTypeDict" :key="item.id" :value="item.value" :label="item.name" />
        </el-select>
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.applyDeptName" placeholder="申请部门" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.applyUserName" placeholder="申请人" clearable />
      </search-item>
      <search-item>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="申请时间（开始）" end-placeholder="申请时间（结束）" />
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container>
      <!-- 表头区域 -->
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/resource/seal/note/add') && active === '0'" icon="icon-add" title="新建" @click="addSealNote" />
      </template>

      <!-- 表格区域 -->
      <normal-table
        :data="sealNoteList" :total="total" :columns="columns"
        :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 fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button v-if="active === '0'" size="small" type="primary" link @click="detail(row)">
                查看
              </el-button>

              <el-button v-else size="small" type="primary" link @click="detail(row)">
                查看2
              </el-button>

              <el-button v-if="(active === '1' || active === '6') && proxy.hasPerm(`/resource/seal/note/delAppr`)" size="small" type="danger" link @click="deleteSuggestById(row)">
                删除
              </el-button>

              <template v-if="active === '2'">
                <el-button size="small" type="primary" link @click="approvalAgreeHandler(row)">
                  同意
                </el-button>
                <el-button size="small" type="danger" link @click="approvalRefuseHandler(row)">
                  拒绝
                </el-button>
              </template>
              <template v-if="active === '3'">
                <el-button size="small" type="info" link @click="revokeApprById(row)">
                  取消
                </el-button>
              </template>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>

    <!-- 审批单弹窗 -->
    <note-approval-dialog ref="apprDial" @on-success="afterApprovalHandler" />

    <!-- 右上角按钮集合 -->
    <button-box :active="active" :menu="menu" @change-current-button="changeCurrentButton" />
  </app-container>
</template>
