<!-- 分包方档案列表 -->
<script lang="ts" setup name="subpackageRecordList">
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IListQuery } from './record-interface'
import type { IList } from '@/views/business/subpackage/approve/approve-interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import type { dictType } from '@/views/device/receive/receive'
import useTemplateDownload from '@/utils/useTemplateDownload'
import { batchImportSubpackageRecord, exportRecordList, getListPage } from '@/api/business/subpackage/record'
import { SCHEDULE } from '@/utils/scheduleDict'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
const { proxy } = getCurrentInstance() as any
const loadingTable = ref(false)
const $router = useRouter()
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  formId: SCHEDULE.BUSINESS_SUBPACKAGE_APPROVE, // 表单id
  outsourcerName: '', // 	公司名称
  businessSize: '', //	业务规模-字典code
  grade: '', // 	履约评级-字典code
  outsourcerNo: '', // 	分包方编号
  offset: 1,
  limit: 20,
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'subpackage-record', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('subpackage-record') || {
  formId: SCHEDULE.BUSINESS_SUBPACKAGE_APPROVE, // 表单id
  outsourcerName: '', // 	公司名称
  businessSize: '', //	业务规模-字典code
  grade: '', // 	履约评级-字典code
  outsourcerNo: '', // 	分包方编号
  offset: 1,
  limit: 20,
}
// 表头
const columns = ref<TableColumn[]>([
  { text: '分包方编号', value: 'outsourcerNo', align: 'center', width: '160px' },
  { text: '公司名称', value: 'outsourcerName', align: 'center' },
  { text: '公司规模', value: 'outsourcerSizeName', align: 'center', width: '110' },
  { text: '业务规模', value: 'businessSizeName', align: 'center', width: '130' },
  { text: '履约评级', value: 'gradeName', align: 'center', width: '90' },
  { text: '整体评价', value: 'evaluationName', align: 'center', width: '110' },
  { text: '业务内容', value: 'businessContent', align: 'center' },
  { text: '公司地址', value: 'fullAddress', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180px' },
  // { text: '备注', value: 'remark', align: 'center' },
])
const list = ref<IList[]>([]) // 表格数据
const total = ref(0) // 数据总条数
const checkoutList = ref<string[]>([]) // 选中的内容
const businessSizeList = ref<dictType[]>([]) // 业务规模列表
const gradeList = ref<dictType[]>([]) // 履约评级列表
const getDict = async () => {
  // 获取业务规模
  getDictByCode('businessSize').then((response) => {
    businessSizeList.value = response.data
  })
  // 获取履约评级
  getDictByCode('grade').then((response) => {
    gradeList.value = response.data
  })
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页，否则跳转第一页
  //   listQuery.value.offset = 1
  // }
  // 模拟数据
  getListPage(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: { addressProvinceName: string; addressCityName: string }) => {
      return {
        ...item,
        // fullAddress: (item.addressProvinceName === item.addressCityName) ? item.addressCityName : item.addressProvinceName + item.addressCityName,
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 clearList = () => {
  listQuery.value = {
    formId: SCHEDULE.BUSINESS_SUBPACKAGE_APPROVE, // 表单id
    outsourcerName: '', // 	公司名称
    businessSize: '', //	业务规模-字典code
    grade: '', // 	履约评级-字典code
    outsourcerNo: '', // 	分包方编号
    offset: 1,
    limit: 20,
  }
  fetchData()
}

// 搜索
const searchList = () => {
  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 = {
      formId: SCHEDULE.BUSINESS_SUBPACKAGE_APPROVE, // 表单id
      outsourcerName: listQuery.value.outsourcerName, // 	公司名称
      businessSize: listQuery.value.businessSize, //	业务规模-字典code
      grade: listQuery.value.grade, // 	履约评级-字典code
      outsourcerNo: listQuery.value.outsourcerNo, // 	分包方编号
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    exportRecordList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '分包方档案列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 打印
const 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: IList) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '分包方资格审批列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 点击详情
const goDetail = (row: IList, val: string) => {
  $router.push({
    path: `archives/${val}/${row.id}`,
  })
}

// -------------------------------------模板下载、批量导入-----------------------------------
// 模板下载
const templateDownload = () => {
  useTemplateDownload('分包方模块')
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  // 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])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    batchImportSubpackageRecord(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('导入成功')
        fetchData(true)
        loading.close()
        event.target.value = ''
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
//   }
//   else {
//     ElMessage.warning('请上传pdf格式')
//   }
}
// 批量导入
const batchImport = () => {
  fileRef.value.click()
}
// --------------------------------------------------------------------------------------------

onMounted(async () => {
  await getDict() // 获取字典
  fetchData(true)
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <search-area :need-clear="true" @search="searchList" @clear="clearList">
        <search-item>
          <el-input v-model.trim="listQuery.outsourcerNo" placeholder="分包方编号" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.outsourcerName" placeholder="公司名称" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-select v-model="listQuery.businessSize" style="width: 200px;" placeholder="业务规模" clearable>
            <el-option v-for="item in businessSizeList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item>
          <el-select v-model="listQuery.grade" style="width: 200px;" placeholder="履约评级" clearable>
            <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <icon-button v-if="proxy.hasPerm('/subpackage/archives/import')" icon="icon-import" title="批量导入" type="primary" @click="batchImport" />
          <icon-button v-if="proxy.hasPerm('/subpackage/archives/import')" icon="icon-template" title="模板下载" type="primary" @click="templateDownload" />
          <icon-button v-if="proxy.hasPerm('/subpackage/archives/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
          <icon-button v-if="proxy.hasPerm('/subpackage/archives/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
        </template>
        <input v-show="false" ref="fileRef" type="file" accept="*" @change="onFileChange">
        <normal-table
          :data="list" :total="total" :columns="columns" :query="listQuery" :list-loading="loadingTable"
          is-showmulti-select @change="changePage" @multi-select="handleSelectionChange"
        >
          <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="操作"
              align="center"
              fixed="right"
              :width="90"
            >
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="goDetail(row, 'detail')"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>
