<script lang="ts" setup name="ListSource">
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import type { IlistQuery, IlistType, optionsType, priceForm } from './list_interface'
import ListPriceAdd from './priceAdd.vue'
import { exportPriceList, getDeletePrice, getPriceList, getTypeSelect, uploadPrice } from '@/api/system/price'
import { exportExcel } from '@/utils/exportXlsx'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
// 查询条件
const listQuery: Ref<IlistQuery> = ref({
  checkType: '', // 检校类型
  priceItem: '', // 项目
  priceName: '', // 价格名称
  priceNo: '', // 价格编号
  priceType: '', // 类别
  offset: 1, // 页码
  limit: 20, // 分页数量
})
// 控制是否显示新增页面
const show = ref(true)
// 表格数据
const list = ref([])
// 总数
const total = ref(0)
// 表头
const columns: Ref<TableColumn[]> = ref([])
columns.value = [
  { text: '价格编号', value: 'priceNo', width: '140', align: 'center' },
  { text: '价格名称', value: 'priceName', align: 'center' },
  { text: '检校类型', value: 'checkType', align: 'center' },
  { text: '类别', value: 'priceType', align: 'center' },
  { text: '项目', value: 'priceItem', align: 'center' },
  { text: '标准价格（元)', value: 'price', width: '120', align: 'center' },
  { text: '业务员折扣权限', value: 'operatorDiscountPermission', width: '125', align: 'center' },
  { text: '负责人折扣权限', value: 'directorDiscountPermission', width: '125', align: 'center' },
  { text: '依据标准', value: 'priceStandard', width: '90', align: 'center' },
  { text: '创建时间', value: 'createTime', width: '170', align: 'center' },
]

// 选中的内容
const checkoutList = ref<string[]>([])
// 文件上传input
const fileRef = ref()
// 删除id
const deleteId = ref('')
// 校验类型下拉框数组
const checkTypeOptions = ref<optionsType[]>([])
// 类别下拉框数组
const priceTypeOptions = ref<optionsType[]>([])
// 项目下拉框数组
const priceItemOptions = ref<optionsType[]>([])
// 确认框是否显示
const isPopconfirmShow = ref(false)

// 列表加载状态
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
  })
}
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 confirmEvent = () => {
  getDeletePrice({ id: deleteId.value }).then((res) => {
    if (res.code === 200) {
      isPopconfirmShow.value = false
      ElMessage.success('删除成功')
      fetchData(true)
    }
  })
}

// 获取下拉框数据
const getOptions = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'checkType') {
      checkTypeOptions.value = res.data
    }
    else if (code === 'priceType') {
      priceTypeOptions.value = res.data
    }
    else if (code === 'priceItem') {
      priceItemOptions.value = res.data
    }
  })
}
getOptions('checkType')
getOptions('priceType')
getOptions('priceItem')
// 点击重置
const clearList = () => {
  listQuery.value = {
    checkType: '',
    priceItem: '',
    priceName: '',
    priceNo: '',
    priceType: '',
    offset: 1,
    limit: 20,
  }
  fetchData()
}
const { proxy } = getCurrentInstance() as any
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      checkType: '',
      model: '',
      priceItem: '',
      priceName: '',
      priceNo: '',
      priceType: '',
    }
    exportPriceList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '价格列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  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])
      uploadPrice(fd).then((res) => {
        if (res.code === 200) {
          ElMessage.success('上传成功')
          fetchData(true)
        }
        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('/price/add')
}
const exportAll = () => {
  exportExcelBtn()
}
// 打印列表
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('无可打印内容')
  }
}
</script>

<template>
  <div>
    <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.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-select
            v-model.trim="listQuery.priceType"
            clearable
            placeholder="类别"
            size="default"
          >
            <el-option
              v-for="item in priceTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-select
            v-model.trim="listQuery.priceItem"
            clearable
            placeholder="项目"
            size="default"
          >
            <el-option
              v-for="item in priceItemOptions"
              :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('/measure/price/import')" icon="icon-import" title="批量导入" type="primary" />
          <icon-button v-if="proxy.hasPerm('/measure/price/mould')" icon="icon-template" title="模板下载" type="primary" />
          <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" @multiSelect="handleSelectionChange"
        >
          <template #columns>
            <el-table-column label="操作" align="center" width="120">
              <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>
    <el-dialog
      v-model="isPopconfirmShow"
      title="确认操作"
      width="30%"
    >
      <span>确定删除吗?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isPopconfirmShow = false">取消</el-button>
          <el-button type="primary" @click="confirmEvent">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

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