<script lang="ts" setup name="ListSource">
import { reactive, ref } from 'vue'
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IOptions, IlistQuery, IlistTypes } from '../../standard_interface'
import ListSourceAdd from './listPageAdd.vue'
import { getStandardLisdelete, getUsersDept, getstandardEquipmentApplyList } from '@/api/device/standard'
import { uploadApi } from '@/api/system/notice'
import { exportExcel } from '@/utils/exportXlsx'
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  buttoms: {
    type: Array,
    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: '',
  standardName: '',
  standardNo: '',
  limit: 20,
  offset: 1,
})
// 初始化路由
const $router = useRouter()
// 控制是否显示新增页面
const show = ref(true)
// 表格数据
const list = ref([])
// 总数
const total = ref(0)
// 表头
const columns = ref([
  {
    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[]>([])
// 选中的内容
const checkoutList = ref([])
// 文件上传input
const fileRef = ref()
// 审批弹窗开关
const applyShow = ref(false)
// 删除id
const deleteId = ref('')
// 详情id
const infoId = ref('0')
// 点击按钮
const buttonType = ref('')
const loadingTable = ref(false)
// 获取部门信息
getUsersDept({
  createTime: null,
  director: '',
  meterMajor: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '2',
  pdeptId: null,
  offset: 1,
  limit: 999999,
}).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
}
// 点击删除
const handleDelete = (row: rowReturn, type: string) => {
  ElMessageBox.confirm(
    `确认${type}${row.standardName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      if (type === '删除') {
        getStandardLisdelete({ id: row.id as string }).then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            fetchData(true)
          }
        })
      }
    })
}
// 点击编辑/详情
const handleEdit = (row: rowReturn, value: string) => {
  if (value === '查看') {
    $router.push({
      name: 'standardListAdd',
      params: {
        type: 'detail',
        id: row.id,
      },
    })
  }
  else if (value === '编辑') {
    $router.push({
      name: 'standardListAdd',
      params: {
        type: 'edit',
        id: row.id,
      },
    })
  }
  else if (value === '删除' || value === '取消' || value === '提交') {
    handleDelete(row, value)
  }
  else {
    if (value === '同意') {
      applyList.value.select = '1'
    }
    else if (value === '驳回') {
      applyList.value.select = '2'
    }
    else {
      applyList.value.select = '3'
    }
    applyList.value.approval = row.standardOwner
    applyList.value.approvalTime = row.createTime
    applyShow.value = true
  }
}
// 审批弹窗关闭
const handleClose = () => {
  applyShow.value = false
}
// 点击搜索
const searchList = () => {
  fetchData(true)
}
const cancelEvent = () => {
  console.log('cancel!')
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    applyNo: '',
    applyStatus: '',
    applyType: props.applyType,
    approvalStatus: props.approvalStatus,
    createUser: '',
    equipmentNo: '',
    organizeNo: '',
    standardName: '',
    standardNo: '',
    limit: 10,
    offset: 1,
  }
}
// 关闭编辑
const close = () => {
  show.value = true
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (checkoutList.value.length <= 0) {
    exportExcel({
      json: list.value.map((item: IlistTypes, index: number) => ({ index: index + 1, applyNo: item.applyNo, applyTypeName: item.applyTypeName, standardNo: item.standardNo, standardName: item.standardName, constructionStandardUnitName: item.constructionStandardUnitName, standardOwner: item.standardOwner, applyDept: item.applyDept, createUser: item.createUser, createTime: item.createTime, approvalStatusName: item.approvalStatusName })),
      name: '标准装置申请',
      titleArr: ['序号', '申请编号', '申请类型', '标准代码', '标准名称', '标准所在部门', '负责人', '申请部门', '申请人', '申请时间', '审批状态'],
      sheetName: 'sheet1',
    })
  }
  else {
    exportExcel({
      json: checkoutList.value.map((item: IlistTypes, index: number) => ({ index: index + 1, applyNo: item.applyNo, applyTypeName: item.applyTypeName, standardNo: item.standardNo, standardName: item.standardName, constructionStandardUnitName: item.constructionStandardUnitName, standardOwner: item.standardOwner, applyDept: item.applyDept, createUser: item.createUser, createTime: item.createTime, approvalStatusName: item.approvalStatusName })),
      name: '标准装置申请',
      titleArr: ['序号', '申请编号', '申请类型', '标准代码', '标准名称', '标准所在部门', '负责人', '申请部门', '申请人', '申请时间', '审批状态'],
      sheetName: 'sheet1',
    })
  }
  loading.close()
}
// 上传文件/批量导入
const onFileChange = (event: any) => {
  if (event.target.files[0].type === 'application/pdf') {
    if (event.target.files?.length !== 0) {
      // 创建formdata对象
      const fd = new FormData()
      fd.append('multipartFile', event.target.files[0])
      uploadApi(fd).then((res) => {
        if (res.code === 200) {
          ElMessage.success('上传成功')
        }
        else {
          ElMessage.error(res.message)
        }
      })
    }
  }
  else {
    ElMessage.error('请上传pdf格式')
  }
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 upload = () => {
  fileRef.value.click()
}
const uploadAll = () => {
  upload()
}
// 新建
const add = () => {
  $router.push({
    name: 'standardListAdd',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
const exportAll = () => {
  exportExcelBtn()
}
watch(() => show.value, (newVal) => {
// 变化后存储
  emit('setData', newVal)
},
{ deep: true, immediate: true })
// 打印
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: '溯源供方编号模板', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})
// 审批弹窗的提交
const applyListSubmit = () => {
  console.log(applyList.value)
  if (applyList.value.select == '') {
    return ElMessage.error('必须选择审批意见')
  }
  handleClose()
}
</script>

<template>
  <div v-if="show">
    <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 v-print="printObj" icon="icon-print" title="打印" type="primary" />
        </template>
        <input v-show="false" ref="fileRef" type="file" accept="pdf/*" @change="onFileChange">
        <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
                  v-for="(item, index) in buttoms"
                  :key="index"
                  size="small"
                  :type="item.type" link
                  @click="handleEdit(row, item.name)"
                >
                  {{ item.name }}
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
  <el-dialog
    v-model="applyShow"
    title="审批操作"
    width="50%"
    :before-close="handleClose"
  >
    <el-form
      ref="addPersonListForm"
      label-position="left"
      label-width="100px"
      :model="applyList"
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="审批意见:">
            <el-radio-group v-model="applyList.select" class="ml-4">
              <el-radio label="1" size="large">
                同意
              </el-radio>
              <el-radio label="2" size="large">
                驳回
              </el-radio>
              <el-radio label="3" size="large">
                拒绝
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="审批结论:">
            <el-input
              v-model="applyList.epilog"
              :rows="4"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="审批人:">
            <el-input
              v-model="applyList.approval"
              placeholder="审批人"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审批时间:">
            <el-input
              v-model="applyList.approvalTime"
              style="width: 100%;"
              placeholder="审批时间"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="applyListSubmit">
        提交
      </el-button>
      <el-button type="info" @click="handleClose">
        取消
      </el-button>
    </template>
  </el-dialog>
</template>

