<script lang="ts" setup name="Process">
import { onMounted, reactive, ref } from 'vue'
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import type { IlistQuery } from './process'
import EditProcess from './editProcess.vue'
import DetailProcess from './detailProcess.vue'
import { delProcessList, getBusinessList, getProcessList, updateState } from '@/api/system/process'
import { exportExcel } from '@/utils/exportXlsx'

const { proxy } = getCurrentInstance() as any
const active = ref('main')
const businessList = ref([]) // 关联业务列表
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 businessDic = {
  FILE_APPROVAL: 'jlglwjsp', // 文件审批,
  TRAIN_APPROVAL: 'jlglpxjhsp', // 培训计划审批
  SUPPLIER_APPROVAL: 'jlglsygfsp', // 溯源供方审批
  STANDARD_CHANGE_APPROVAL: 'sbglbzzzghsq', // 标准装置更换申请
  STANDARD_PAUSE_APPROVAL: 'sbglbzzzghsq', // 标准装置暂停申请
  STANDARD_REVERT_APPROVAL: 'sbglbzzzghsq', // 标准装置撤销申请
  STANDARD_RESUME_APPROVAL: 'sbglbzzzghsq', // 标准装置恢复申请
  STANDARD_CHECK_APPROVAL: 'sbglbzzzfcsq', // 标准装置复查申请
  DEVICE_UNUSED_APPROVAL: 'sbglsbxzsq', // 设备闲置申请
  DEVICE_SEALED_APPROVAL: 'sbglsbfcsq', // 设备封存申请
  DEVICE_UNSEALED_APPROVAL: 'sbglsbqfsq', // 设备启封申请
  DEVICE_SCRAPPED_ROVAL: 'sbglsbbfsq', // 设备报废申请
  DEVICE_HANDLE_APPROVAL: 'sbglsbczsq', // 设备处置申请
  DEVICE_CONSUMING_APPROVAL: 'sbglsblysq', // 设备领用申请
  DEVICE_BORROW_APPROVAL: 'sbglsbjysq', // 设备借用申请
}
const columns = ref([
  {
    text: '流程编号',
    value: 'number',
    // width: 150,
  },
  {
    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 logTypeList = ref(null)
const listLoading = ref(false)
const dialogFormVisible = ref(false)
const dialogStatus = ref('')
const multiSelectData = ref([]) // 多选选中结果
// 获取流程列表
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 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) => {
  delProcessList(row.deploymentId).then((res) => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchData(true)
    }
  })
}
// 编辑页面点击关闭
const close = () => {
  active.value = 'main'
}
// 导出
const exportExcelBtn = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (multiSelectData.value.length <= 0) {
    const param = {
      category: '', // 流程分类
      deploymentTime: '', // 部署时间
      directorId: '', // 流程负责人id
      flowKey: '', // 流程key
      formId: '', // 配置表单id
      formName: '', // 配置表单名称
      id: '', // 流程id
      name: '', // 流程名称
      suspensionState: '', // 流程状态
      offset: 1,
      limit: 9999999,
    }
    const res = await getProcessList(param)
    if (res.code === 200) {
      exportExcel({
        json: res.data.rows.map((item: any, index: number) => ({
          index: index + 1,
          number: item.id,
          name: item.name,
          business: item.formName,
          status: item.suspensionState === 1 ? '激活' : '废止',
          person: item.directorName,
          time: item.deploymentTime,
          describe: item.formDesc,
        })),
        name: '流程管理列表',
        titleArr: ['序号', '流程编号', '流程名称', '关联业务', '当前流程状态', '流程负责人', '创建时间', '流程描述'],
        sheetName: 'sheet1',
      })
    }
    loading.close()
  }
  else {
    exportExcel({
      json: multiSelectData.value.map((item: IlistQuery, index: number) => (
        {
          index: index + 1,
          number: item.number,
          name: item.name,
          business: item.business,
          status: item.status,
          person: item.person,
          time: item.time,
          describe: item.describe,
        }
      )),
      name: '流程管理列表',
      titleArr: ['序号', '流程编号', '流程名称', '关联业务', '当前流程状态', '流程负责人', '创建时间', '流程描述'],
      sheetName: 'sheet1',
    })
    loading.close()
  }
}
// 打印
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 selectionChange = (val: any) => {
  multiSelectData.value = val
}

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

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

<template>
  <div class="process">
    <app-container>
      <!-- 主页面 -->
      <div v-if="active === 'main'">
        <!-- 筛选条件 -->
        <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-input
              v-model.trim="listQuery.business"
              placeholder="关联业务"
              clearable
            /> -->
            <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('/measure/price/export')" icon="icon-export" title="导出" type="primary" @click="exportExcelBtn" />
            <icon-button v-if="proxy.hasPerm('/measure/price/print')" v-print="printObj" icon="icon-print" title="打印" type="primary" />
          </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 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>
      </div>
    </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>

