<!-- 流程列表 -->
<script lang="ts" setup name="Process">
import { onMounted, reactive, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import type { IBusinessList, IlistQuery } from './process'
import { delProcessList, exportProcessList, getBusinessList, getProcessList, updateState } from '@/api/system/process'
import { exportFile } from '@/utils/exportUtils'
import { printJSON } from '@/utils/printUtils'
import { getDictByCode } from '@/api/system/dict'

const { proxy } = getCurrentInstance() as any
const businessList = ref<IBusinessList[]>([]) // 关联业务列表
const listQuery = reactive({
  deploymentId: '', // 流程部署id
  suspensionState: '', // 状态流程 1激活 2废止
  number: '', // 编号
  name: '', // 名称
  business: '', // 关联业务
  person: '', // 负责人
  beginTime: '', // 开始时间
  endTime: '', // 结束时间
  status: '', // 当前流程状态,
  offset: 1,
  limit: 20,
})

// 流程状态筛选参数
const searchStatus = [
  {
    value: 1,
    label: '激活',
  },
  {
    value: 2,
    label: '废止',
  },
]
// 表头
const columns = ref([
  { text: '流程编号', value: 'number' },
  { text: '流程名称', value: 'name' },
  { text: '关联业务', value: 'business' },
  { text: '当前流程状态', value: 'status' },
  { text: '流程负责人', value: 'person' },
  { text: '创建时间', value: 'time' },
  { text: '流程描述', value: 'describe' },
])
const list = ref([])
const total = ref(20)
const listLoading = ref(false)
const checkoutList = ref<string[]>([]) // 多选选中结果

// 获取流程列表
const fetchData = async (isNowPage: boolean) => {
  listLoading.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.offset = 1
  }
  const param = {
    category: '', // 流程分类
    deploymentStartTime: listQuery.beginTime, // 开始时间
    deploymentEndTime: listQuery.endTime, // 结束时间
    directorId: '', // 流程负责人id
    directorName: listQuery.person, // 流程负责人筛选字段
    flowKey: '', // 流程key
    formId: listQuery.business, // 配置表单id
    formName: '', // 配置表单名称
    id: listQuery.number, // 流程id
    name: listQuery.name, // 流程名称
    suspensionState: listQuery.suspensionState, // 流程状态
    offset: listQuery.offset,
    limit: listQuery.limit,
  }
  const response = await getProcessList(param)
  total.value = parseInt(response.data.total)
  list.value = response.data.rows.map((item: any) => {
    return {
      ...item,
      number: item.id,
      business: item.formName,
      person: item.directorName,
      time: item.deploymentTime,
      status: item.suspensionState === 1 ? '激活' : '废止',
      describe: item.formDesc,
    }
  })
  listLoading.value = false
}

fetchData(true)

// 查询数据
const search = () => {
  fetchData(false)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size: number; page: number }) => {
  if (val && val.size) {
    listQuery.limit = val.size
  }
  if (val && val.page) {
    listQuery.offset = val.page
  }
  fetchData(true)
}

// 重置
const reset = () => {
  listQuery.number = '' // 编号
  listQuery.name = '' // 名称
  listQuery.business = '' // 关联业务
  listQuery.person = '' // 负责人
  listQuery.beginTime = '' // 开始时间
  listQuery.endTime = '' // 结束时间
  listQuery.status = '' // 当前流程状态,
  listQuery.suspensionState = ''
  fetchData(true)
}

const $router = useRouter()
// 点击编辑/详情
const handleEdit = (row: IlistQuery, pageType: 'edit' | 'detail') => {
  $router.push({ path: `/process/${pageType}`, query: { rowData: JSON.stringify(row) } })
}
// 点击新建
const add = () => {
  $router.push({ path: '/process/add' })
}

// 废止
const abolish = (row: IlistQuery) => {
  const state = row.status === '激活' ? 2 : 1
  updateState(row.deploymentId, state).then((res) => {
    if (res.code === 200) {
      ElMessage.success('操作成功')
      fetchData(true)
    }
  })
}

// 删除
const del = (row: IlistQuery) => {
  ElMessageBox.confirm(
    `确认删除${row.name}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      delProcessList(row.deploymentId).then((res) => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          fetchData(true)
        }
      })
    })
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      deploymentId: '', // 流程部署id
      suspensionState: '', // 状态流程 1激活 2废止
      number: '', // 编号
      name: '', // 名称
      business: '', // 关联业务
      person: '', // 负责人
      beginTime: '', // 开始时间
      endTime: '', // 结束时间
      status: '', // 当前流程状态,
      ids: checkoutList.value,
    }
    exportProcessList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '流程管理列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}
// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '流程管理列表')
  }
  else if (checkoutList.value.length > 0) {
    // const printList = list.value.filter((item: any) => checkoutList.value.includes(item.id))
    const printList = checkoutList.value
    printJSON(printList, properties, '流程管理列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 多选选中
const selectionChange = (val: any) => {
  checkoutList.value = val
}

// 获取关联业务列表
const fetchBusinessList = () => {
  getBusinessList().then((res) => {
    businessList.value = res.data
  })
}

onMounted(() => {
  fetchBusinessList()
})
</script>

<template>
  <div class="process">
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input
            v-model.trim="listQuery.number"
            placeholder="流程编号"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.name"
            placeholder="流程名称"
            clearable
          />
        </search-item>
        <search-item>
          <el-select v-model="listQuery.business" placeholder="请选择关联业务" clearable>
            <el-option
              v-for="item in businessList"
              :key="item.formId"
              :label="item.formName"
              :value="item.formId"
            />
          </el-select>
        </search-item>

        <search-item>
          <el-select v-model="listQuery.suspensionState" placeholder="当前流程状态" clearable>
            <el-option
              v-for="item in searchStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.person"
            placeholder="流程负责人"
            clearable
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="listQuery.beginTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择开始时间"
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="listQuery.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择结束时间"
          />
        </search-item>
      </search-area>
      <!-- 查询结果Table显示 -->
      <table-container>
        <template #btns-right>
          <icon-button v-if="proxy.hasPerm('/sys/process/add')" icon="icon-add" title="新建" type="primary" @click="add" />
          <!-- <icon-button v-if="proxy.hasPerm('/sys/process/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" /> -->
          <icon-button icon="icon-print" title="打印" type="primary" @click="printList" />
        </template>

        <div class="table-area">
          <normal-table
            :data="list"
            :total="total"
            :columns="columns"
            :query="listQuery"
            is-showmulti-select
            :list-loading="listLoading"
            @change="changePage"
            @multiSelect="selectionChange"
          >
            <template #preColumns>
              <el-table-column label="序号" width="55" align="center">
                <template #default="scope">
                  {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
                </template>
              </el-table-column>
            </template>
            <template #columns>
              <el-table-column label="操作" width="160" align="center" fixed="right">
                <template #default="scope">
                  <el-button
                    v-if="proxy.hasPerm('/sys/process/edit')"
                    type="primary"
                    link
                    size="small"
                    class="table-text-button"
                    @click="handleEdit(scope.row, 'edit')"
                  >
                    编辑
                  </el-button>
                  <el-button type="primary" link size="small" class="table-text-button" @click="handleEdit(scope.row, 'detail')">
                    详情
                  </el-button>
                  <el-button type="primary" link size="small" class="table-text-button" @click="abolish(scope.row)">
                    {{ scope.row.suspensionState === 1 ? '废止' : '激活' }}
                  </el-button>
                  <el-button type="danger" link size="small" class="table-text-button" @click="del(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </template>
          </normal-table>
        </div>
      </table-container>
    </app-container>
  </div>
</template>

<style lang="scss" scoped>
.process {
  .table-area {
    background-color: #fff;
    padding: 10px;
    margin-top: 10px;
    border-radius: 7px;
  }
}
</style>

<style lang="scss">
  .list-login-log {
    .el-button + .el-button {
      margin-top: -10px;
    }
  }

  .el-message-box {
    overflow: auto;
  }
</style>

