<script lang="ts" setup name="ListSource">
import { reactive, ref } from 'vue'
import type { PropType, Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IOptions, Ibuttons, IlistQuery } from '../../standard_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { getExportList, getOperateDelete, getUsersDept, getstandardEquipmentApplyList, submitStandardEquipmentApply } from '@/api/device/standard'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { submitApproval } from '@/api/approval'
const props = defineProps({
  name: {
    type: String,
    default: '', // 申请类型名字
  },
  schedule: {
    type: String,
    default: '', // 表单id
  },
  buttons: {
    type: Array as PropType<Ibuttons[]>,
    default: () => [], // 按钮数组
  },
  applyType: {
    type: String,
    default: '1', // 申请类型
  },
  approvalStatus: {
    type: String,
    default: '', // 审批状态 ‘’代表全部
  },
})
const emit = defineEmits(['setData']) // 关闭
// 查询条件
const listQuery: Ref<IlistQuery> = ref({
  applyNo: '', // 申请编号
  applyStatus: '', // 申请状态
  applyType: props.applyType, // 申请类型
  approvalStatus: props.approvalStatus, // 审批状态
  createUser: '', // 用户
  equipmentNo: '', // 设备编号
  organizeNo: '',
  formId: props.schedule, // 表单id
  standardName: '', // 标准名称
  standardNo: '', // 标准代码
  limit: 20, // 一页多少条
  offset: 1, // 第几页
})
// 初始化路由
const $router = useRouter()
// 控制是否显示新增页面
const show = ref(true)
// 表格数据。
const list = ref([])
// 总数
const total = ref(0)
// 表头
const columns = ref<TableColumn[]>([
  {
    text: '申请编号',
    value: 'applyNo',
    align: 'center',
  },
  {
    text: '申请类型',
    value: 'applyTypeName',
    width: '120',
    align: 'center',
  },
  {
    text: '标准代码',
    value: 'standardNo',
    align: 'center',
  },
  {
    text: '标准名称',
    value: 'standardName',
    align: 'center',
  },
  {
    text: '标准所在部门',
    value: 'constructionStandardUnitName',
    width: '110',
    align: 'center',
  },
  {
    text: '负责人',
    value: 'standardOwner',
    align: 'center',
  },
  {
    text: '申请部门',
    value: 'applyDept',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'createUser',
    align: 'center',
  },
  {
    text: '申请时间',
    value: 'createTime',
    align: 'center',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
  },
])
// 审批弹窗信息收集类型
interface applyListType {
  select: string
  epilog: string
  approval: string
  approvalTime: string
}
// 审批弹窗信息收集
const applyList = ref<applyListType>({
  select: '',
  epilog: '',
  approval: '',
  approvalTime: '',
})
const buttonArray = ref<string[]>([])
// 部门下拉框
const standardUsersDeptList = ref<IOptions[]>([])
// 导出id类型
interface ICheckoutList {
  id: string
}
// 选中的内容
const checkoutList = ref<ICheckoutList[]>([])
// 文件上传input
const fileRef = ref()
// 审批弹窗开关
const applyShow = ref(false)
const loadingTable = ref(false)
// 获取部门信息参数
const DeptParams = ref({
  createEndTime: '',
  createstartTime: '',
  director: '',
  meterMajor: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '3',
  pdeptId: null,
  offset: 1,
  limit: 999999,
})
// 获取部门信息
getUsersDept(DeptParams.value).then((res) => {
  standardUsersDeptList.value = res.data.rows
})
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getstandardEquipmentApplyList(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
fetchData(true)
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
// 点击删除和编辑的参数类型
interface rowReturn {
  id: string
  standardName: string
  standardOwner: string
  createTime: string
  taskId: string
  processId: string
}
// 点击删除
const handleDelete = (row: rowReturn) => {
  ElMessageBox.confirm(
    `确认删除${row.standardName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      getOperateDelete({ id: row.id as string, taskId: row.taskId }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        }
      })
    })
}
const approvalDialog = ref()
// 跳转到详情
const goDetail = (row: rowReturn) => {
  $router.push({
    name: 'standardListAdd',
    params: {
      type: 'detail',
    },
    query: {
      title: '详情',
      id: row.id,
      applyType: props.applyType,
      formId: props.schedule,
      processId: row.processId,
    },
  })
}
// 提交
const approvalSubmit = (row: rowReturn) => {
  ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    submitStandardEquipmentApply({ id: row.id, formId: props.schedule }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交成功',
        })
        fetchData(true)
      }
    })
  })
}
// 取消
const handleCancel = (row: rowReturn) => {
  const params = {
    taskId: row.taskId!,
    comments: '',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      submitApproval('revoke', params).then((res) => {
        ElMessage({
          type: 'success',
          message: '取消成功',
        })
        fetchData(true)
      })
    })
}
// 点击数据后的操作按钮
const clickBtn = (row: rowReturn, buttonType: string) => {
  switch (buttonType) {
    case '查看':
      goDetail(row)
      break
    case '提交':
      approvalSubmit(row)
      break
    case '编辑':
      $router.push({
        name: 'standardListAdd',
        params: {
          type: 'edit',
        },
        query: {
          title: '编辑',
          id: row.id,
          applyType: props.applyType,
          formId: props.schedule,
        },
      })
      break
    case '同意':
      approvalDialog.value.initDialog('agree', row.taskId)
      break
    case '驳回':
      approvalDialog.value.initDialog('reject', row.taskId)
      break
    case '拒绝':
      approvalDialog.value.initDialog('refuse', row.taskId)
      break
    case '取消':
      handleCancel(row)
      break
    case '删除':
      handleDelete(row)
      break
  }
}
// 审批弹窗关闭
const handleClose = () => {
  applyShow.value = false
}
// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    applyNo: '', // 申请编号
    applyStatus: '', // 申请状态
    applyType: props.applyType, // 申请类型
    approvalStatus: props.approvalStatus, // 审批状态
    createUser: '', // 用户
    equipmentNo: '', // 设备编号
    organizeNo: '',
    formId: props.schedule, // 表单id
    standardName: '', // 标准名称
    standardNo: '', // 标准代码
    limit: 20, // 一页多少条
    offset: 1, // 第几页
  }
  fetchData(true)
}
// 关闭编辑
const close = () => {
  show.value = true
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  getExportList(listQuery.value).then((res) => {
    const blob = new Blob([res.data])
    exportFile(blob, '标准装置申请列表.xlsx')
  })
  loading.close()
}
// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}
// 新建
const add = () => {
  $router.push({
    name: 'standardListAdd',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: props.name,
      applyType: props.applyType,
      formId: props.schedule,
    },
  })
}
// 导出
const exportAll = () => {
  exportExcelBtn()
}

// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item: TableColumn) => {
    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: ICheckoutList) => checkoutList.value.includes(item))
    printJSON(printList, properties, '标准装置申请列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
// 审批弹窗的提交
const applyListSubmit = () => {
  console.log(applyList.value)
  if (applyList.value.select == '') {
    return ElMessage.error('必须选择审批意见')
  }
  handleClose()
}
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.applyNo"
          placeholder="申请编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.equipmentNo"
          placeholder="设备编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.standardNo"
          placeholder="标准代码"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.standardName"
          placeholder="标准名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-select
          v-model.trim="listQuery.organizeNo"
          clearable
          placeholder="申请部门"
          size="default"
        >
          <el-option
            v-for="item in standardUsersDeptList"
            :key="item.id"
            :label="item.organizeName"
            :value="item.id"
          />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button icon="icon-print" title="打印" type="primary" @click="printList" />
      </template>
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery"
        :list-loading="loadingTable" is-showmulti-select @change="changePage" @multiSelect="handleSelectionChange"
      >
        <template #columns>
          <el-table-column label="操作" align="center" width="300">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="clickBtn(row, '查看')"
              >
                查看
              </el-button>
              <el-button
                v-if="approvalStatus === '' || approvalStatus === '2'"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if="approvalStatus === '' || approvalStatus === '2'"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '驳回')"
              >
                驳回
              </el-button>
              <el-button
                v-if="approvalStatus === '' || approvalStatus === '2'"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '拒绝')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="approvalStatus === '1' || approvalStatus === '6'"
                size="small"
                link
                type="primary"
                @click="clickBtn(row, '编辑')"
              >
                编辑
              </el-button>
              <el-button
                v-if="approvalStatus === '1' || approvalStatus === '6'"
                size="small"
                link
                type="primary"
                @click="clickBtn(row, '提交')"
              >
                提交
              </el-button>
              <!-- 是发起者且审批中可以取消 -->
              <el-button
                v-if="approvalStatus === '' || approvalStatus === '3'"
                size="small"
                link
                type="info"
                :disabled="row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '取消')"
              >
                取消
              </el-button>
              <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
              <el-button
                v-if="approvalStatus !== '4' && approvalStatus !== '5'"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                @click="clickBtn(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
  <!-- 审批弹窗 -->
  <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
</template>

