<!-- 价格库列表 -->
<script lang="ts" setup name="PriceList">
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import type { IlistQuery, optionsType, priceForm } from './list_interface'
import { batchImportPrice, exportPriceList, getDeletePrice, getPriceList, getTypeSelect, uploadPrice } from '@/api/system/price'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import useTemplateDownload from '@/utils/useTemplateDownload'
import { exportFile } from '@/utils/exportUtils'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
// 查询条件
const listQuery = ref<IlistQuery>({
  checkType: '', // 检校类型
  priceItem: '', // 项目
  priceName: '', // 价格名称
  categoryName: '', // 类别名称
  itemName: '', // 项目名称
  priceNo: '', // 价格编号
  priceType: '', // 类别id
  offset: 1, // 页码
  limit: 20, // 分页数量
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'measure-price', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('measure-price') || {
  checkType: '', // 检校类型
  priceItem: '', // 项目
  priceName: '', // 价格名称
  categoryName: '', // 类别名称
  itemName: '', // 项目名称
  priceNo: '', // 价格编号
  priceType: '', // 类别id
  offset: 1, // 页码
  limit: 20, // 分页数量
}
// 表格数据
const list = ref([])
// 总数
const total = ref(0)
// 表头
const columns = ref<TableColumn[]>([{ text: '价格编号', value: 'priceNo', width: '140', align: 'center' },
  { text: '价格名称', value: 'priceName', align: 'center' },
  { text: '检校类型', value: 'checkTypeName', align: 'center' },
  { text: '类别', value: 'categoryName', align: 'center' },
  { text: '项目', value: 'itemName', align: 'center' },
  { text: '标准价格（元)', value: 'price', width: '120', align: 'center' },
  { text: '业务员折扣权限', value: 'operatorDiscountPermissionName', width: '100', align: 'center' },
  { text: '负责人折扣权限', value: 'directorDiscountPermissionName', width: '100', align: 'center' },
  { text: '依据标准', value: 'priceStandardName', width: '90', align: 'center' },
  { text: '创建时间', value: 'createTime', width: '170', align: 'center' },
])

// 选中的内容
const checkoutList = ref<string[]>([])
// 删除id
const deleteId = ref('')
// 校验类型下拉框数组
const checkTypeOptions = ref<optionsType[]>([])
const operatorDiscountPermissionMap = ref<optionsType[]>([]) // 业务折扣权限
const directorDiscountPermissionMap = ref<optionsType[]>([]) // 负责人折扣权限

// 列表加载状态
const loadingTable = ref(false)
// 查询列表
const fetchData = (isNowPage = false) => {
  // if (!isNowPage) {
  //   listQuery.value.offset = 1
  // }
  loadingTable.value = true
  getPriceList(listQuery.value).then((response) => {
    list.value = response.data.records
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
onMounted(() => {
  fetchData(true)
})
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

const $router = useRouter()
// 点击编辑/详情
const handleEdit = (row: priceForm, pageType: 'edit' | 'detail') => {
  $router.push(`/price/${pageType}/${row.id}`)
}
// 点击删除
const handleDelete = (row: priceForm) => {
  console.log(row)
  ElMessageBox.confirm(
    `确认删除${row.priceName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      getDeletePrice({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        }
      })
    })
}
// 点击搜索
const searchList = () => {
  fetchData()
}

// 获取下拉框数据
const getOptions = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'checkType') { // 校验类型
      checkTypeOptions.value = res.data
    }
    if (code === 'operatorDiscountPermission') { // 业务折扣权限
      operatorDiscountPermissionMap.value = res.data
    }
    if (code === 'directorDiscountPermission') { // 负责人折扣权限
      directorDiscountPermissionMap.value = res.data
    }
  })
}
getOptions('checkType')
// 点击重置
const clearList = () => {
  listQuery.value = {
    checkType: '', // 检校类型
    priceItem: '', // 项目
    categoryName: '', // 类别名称
    itemName: '', // 项目名称
    priceName: '', // 价格名称
    priceNo: '', // 价格编号
    priceType: '', // 类别id
    offset: 1, // 页码
    limit: 20, // 分页数量
  }
  fetchData()
}
const { proxy } = getCurrentInstance() as any
// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      checkType: listQuery.value.checkType, // 检校类型
      priceItem: listQuery.value.priceItem, // 项目
      priceName: listQuery.value.priceName, // 价格名称
      categoryName: listQuery.value.categoryName, // 类别名称
      itemName: listQuery.value.itemName, // 项目名称
      priceNo: listQuery.value.priceNo, // 价格编号
      priceType: listQuery.value.priceType, // 类别id
      ids: checkoutList.value,
    }
    exportPriceList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '价格列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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('/price/add')
}

// 打印列表
function 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: { id: string }) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '价格列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// -------------------------------------模板下载、批量导入-----------------------------------
// 模板下载
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)',
    })
    batchImportPrice(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()
}
// --------------------------------------------------------------------------------------------
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.priceNo"
          placeholder="价格编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.priceName"
          placeholder="价格名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-select
          v-model.trim="listQuery.checkType"
          clearable
          placeholder="检校类型"
          size="default"
        >
          <el-option
            v-for="item in checkTypeOptions"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.priceType"
          placeholder="请输入类别名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.priceItem"
          placeholder="请输入项目名称"
          clearable
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/measure/price/import')" icon="icon-import" title="批量导入" type="primary" @click="batchImport" />
        <icon-button v-if="proxy.hasPerm('/measure/price/mould')" icon="icon-template" title="模板下载" type="primary" @click="templateDownload" />
        <icon-button v-if="proxy.hasPerm('/measure/price/add')" icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button v-if="proxy.hasPerm('/measure/price/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/measure/price/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
      </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" @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" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/measure/price/edit')"
                size="small"
                type="primary"
                link
                @click="handleEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'detail')"
              >
                详情
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/measure/price/delete')"
                size="small"
                link
                type="danger"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss" scoped>
:deep .search-item {
  width: 11.5vw !important;
}
</style>
