<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, IlistType } from '../list_interface'
import ListPageAdd from './listPageAdd.vue'
import { getSoucreList, getSoucreListDelete } from '@/api/system/source'
import { getDeptTree } from '@/api/system/plan'
import { uploadApi } from '@/api/system/notice'
import { exportExcel } from '@/utils/exportXlsx'
const props = defineProps({
  name: {
    type: String,
    default: '全部',
  },
  buttoms: {
    type: Array,
    default: () => [],
  },
})
// 查询条件
const listQuery: Ref<IlistQuery> = ref({
  supplierNo: '', // 业务内容
  supplierName: '', // 溯源供方名称
  businessContent: '', // 溯源供方编号
  offset: 1,
  limit: 10,
})
// 控制是否显示新增页面
const show = ref(true)
// 表格数据
const list = ref([])
// 总数
const total = ref(20)
// 表头
const columns = ref([
  {
    text: '计划编号',
    value: 'supplierNo',
    width: '160',
  },
  {
    text: '培训名称',
    value: 'supplierName',
    width: '120',
  },
  {
    text: '培训对象',
    value: 'businessContent',
  },
  {
    text: '培训人数',
    value: 'briefName',
  },
  {
    text: '培训学时',
    value: 'director',
  },
  {
    text: '培训时间',
    value: 'mobile',
  },
  {
    text: '主管部门',
    value: 'companyCity',
  },
  {
    text: '实施单位',
    value: 'createTime',
    width: '120',
  },
  {
    text: '负责人',
    value: 'remark',
  },
  {
    text: '培训内容',
    value: 'remark',
  },
  {
    text: '创建时间',
    value: 'remark',
  },
  {
    text: '审批状态',
    value: 'remark',
  },
])

// 选中的内容
const checkoutList = ref([])
// 文件上传input
const fileRef = ref()
// 删除id
const deleteId = ref('')
// 详情id
const infoId = ref('0')
// 点击按钮
const buttonType = ref('')
// 主管部门下拉框
const options = ref<IOptions[]>([])
const loadingTable = ref(false)
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getSoucreList(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
}
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
  supplierName: string
}
// 点击编辑/详情
const handleEdit = (index: string, row: rowReturn, value: string) => {
  buttonType.value = value
  infoId.value = row.id
  show.value = false
}
// 获取到组织信息
const getDept = () => {
  const params = {
    roleId: '',
    deptType: '',
    tips: '',
  }
  getDeptTree(params).then((response) => {
    options.value = response.data
  })
}
getDept()
// 点击删除
const handleDelete = (index: string, row: rowReturn) => {
  ElMessageBox.confirm(
    `确认删除${row.supplierName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      getSoucreListDelete({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        }
      })
    })
}
// 点击搜索
const searchList = () => {
  fetchData(true)
}
const cancelEvent = () => {
  console.log('cancel!')
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    supplierNo: '', // 业务内容
    supplierName: '', // 溯源供方名称
    businessContent: '', // 溯源供方编号
    offset: 1,
    limit: 20,
  }
}
// 关闭编辑
const close = () => {
  show.value = true
  fetchData(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: IlistType, index: number) => ({ index: index + 1, supplierNo: item.supplierNo, supplierName: item.supplierName, businessContent: item.businessContent, briefName: item.briefName, director: item.director, mobile: item.mobile, companyCity: item.companyCity, createTime: item.createTime, remark: item.remark })),
      name: '溯源供方',
      titleArr: ['序号', '溯源供方编号', '溯源供方名称', '业务内容', '业务资质', '负责人', '联系方式', '地址', '创建时间', '备注'],
      sheetName: 'sheet1',
    })
  }
  else {
    exportExcel({
      json: checkoutList.value.map((item: IlistType, index: number) => ({ index: index + 1, supplierNo: item.supplierNo, supplierName: item.supplierName, businessContent: item.businessContent, briefName: item.briefName, director: item.director, mobile: item.mobile, companyCity: item.companyCity, createTime: item.createTime, remark: item.remark })),
      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 exportAll = () => {
  exportExcelBtn()
}
// 打印
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: '溯源供方编号模板', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})
</script>

<template>
  <div v-if="show">
    <app-container>
      <search-area
        :need-clear="true"
        @search="searchList" @clear="clearList"
      >
        <search-item>
          <el-date-picker
            v-model="listQuery.supplierNo"
            type="datetime"
            placeholder="培训时间"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD h:m:s"
            :disabled="buttonType === '详情'"
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="listQuery.supplierName"
            type="datetime"
            placeholder="创建时间"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD h:m:s"
            :disabled="buttonType === '详情'"
          />
        </search-item>
        <search-item>
          <el-select
            v-model="listQuery.deptId"
            clearable
            placeholder="主管部门"
            size="default"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.businessContent"
            placeholder="实施单位"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.businessContent"
            placeholder="负责人"
            clearable
          />
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <el-button type="primary" @click="exportAll">
            导出
          </el-button>
          <el-button v-print="printObj" type="primary">
            打印
          </el-button>
        </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 in buttoms"
                  :key="item"
                  size="small"
                  :type="item.type" link
                  @click="handleEdit(row.$index, row, item.name)"
                >
                  {{ item.name }}
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>

  <list-page-add
    v-else
    :info-id="infoId"
    :button-type="buttonType"
    @close="close"
  />
</template>

<style lang="scss" scoped>
.pagination {
  position: fixed;
  bottom: 0;
}
</style>
