<!-- 委托书列表 -->
<script lang="ts" setup name="OrderList">
import type { Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IListQuery, IOrderList, dictType } from './orderList_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { uploadApi } from '@/api/system/notice'
import {
  backOrder,
  exportOrderList,
  getOrderList,
  receiveOrder,
} from '@/api/business/schedule/order'
import { getDictByCode } from '@/api/system/dict'

const { proxy } = getCurrentInstance() as any
const $router = useRouter()

// 查询条件
const listQuery: Ref<IListQuery> = ref({
  orderCode: '', // 委托书编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  deliverer: '', // 送样人
  isUrgent: 2, // 是否加急 2全部 1是 0否
  status: 0, // 接收状态
  offset: 1,
  limit: 20,
})
const isUrgentMap = ref<dictType[]>([]) // 是否加急
const statusMap = ref<dictType[]>([]) // 接收状态

const columns = ref<TableColumn[]>([
  { text: '委托书编号', value: 'orderCode', align: 'center', width: '180px' },
  { text: '委托方代码', value: 'customerNo', align: 'center', width: '160px' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '送样人', value: 'deliverer', align: 'center' },
  { text: '联系方式', value: 'customerPhone', align: 'center' },
  { text: '样品数量', value: 'sampleCount', align: 'center' },
  { text: '是否加急', value: 'isUrgent', align: 'center', width: '100px', filter: (row: IOrderList) => { return row.isUrgent == 1 ? '是' : '否' }, styleFilter: (row: IOrderList) => { return row.isUrgent == 1 ? 'color: red' : '' } },
  { text: '接收状态', value: 'statusName', align: 'center', width: '100px' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180px' },
  { text: '备注', value: 'remark', align: 'center' },
])

// 表格数据
const list = ref<IOrderList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])
// 文件上传input
const fileRef = ref()

// 获取字典值
function getDict() {
  // 是否加急
  getDictByCode('isUrgent').then((response) => {
    isUrgentMap.value = response.data.map((item: dictType) => {
      return {
        ...item,
        value: parseInt(item.value as string),
      }
    })
    // 在已有的字典的基础上增加一个全部0进去
    isUrgentMap.value.unshift({
      id: '',
      name: '全部',
      value: 2, // 是否加急全部后端定为2
    })
  })
  // 接收状态
  getDictByCode('orderStatus').then((response) => {
    statusMap.value = response.data.map((item: dictType) => {
      return {
        ...item,
        value: parseInt(item.value as string), // 后端需要int型，在此转换
      }
    })
    // 在已有的字典的基础上增加一个全部0进去
    statusMap.value.unshift({
      id: '',
      name: '全部',
      value: 0,
    })
    console.log(statusMap.value)
  })
}
getDict()

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getOrderList(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    orderCode: '', // 委托书编号
    customerNo: '', // 委托方代码
    customerName: '', // 委托方名称
    deliverer: '', // 送样人
    isUrgent: 2, // 是否加急
    status: 0, // 接收状态
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}

// 多选发生改变时
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 handleEdit = (row: IOrderList, type: string, title: string) => {
  ElMessageBox.confirm(
    `确认${title}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      if (type === 'receive') { // 接收
        receiveOrder({ id: row.id }).then(() => {
          ElMessage.success(`已${title}`)
          fetchData(true)
        })
      }
      else if (type === 'back') { // 退回
        backOrder({ id: row.id }).then(() => {
          ElMessage.success(`已${title}`)
          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 = {
      orderCode: '', // 委托书编号
      customerNo: '', // 委托方代码
      customerName: '', // 委托方名称
      deliverer: '', // 送样人
      isUrgent: 2, // 是否加急
      status: 0, // 接收状态
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    exportOrderList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '委托书列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

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

// 模板下载
const templateDownload = () => {}

// 上传文件/批量导入
const onFileChange = (event: any) => {
  // todo: 校验文件类型，调用上传接口
  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 uploadAll = () => {
  fileRef.value.click()
}

// 点击新建
const add = () => {
  $router.push('/schedule/order/add')
}

// 点击编辑详情
const goEdit = (row: IOrderList, pageType: 'edit' | 'detail') => {
  console.log(row)

  $router.push({
    path: `/schedule/order/${pageType}/${row.id}`,
    // query: {
    //   statusName: row.statusName,
    // },
  })
}

fetchData(true)
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.orderCode"
          placeholder="委托书编号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerNo"
          placeholder="委托方代码"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.deliverer"
          placeholder="送样人"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.isUrgent" placeholder="是否加急" style="width: 120px;" clearable>
          <el-option
            v-for="item in isUrgentMap"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model="listQuery.status" placeholder="接收状态" style="width: 120px;" clearable>
          <el-option
            v-for="item in statusMap"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/schedule/orderList/import')" icon="icon-import" title="批量导入" type="primary" @click="uploadAll" />
        <icon-button v-if="proxy.hasPerm('/schedule/orderList/import')" icon="icon-template" title="模板下载" type="primary" @click="templateDownload" />
        <icon-button v-if="proxy.hasPerm('/schedule/orderList/add')" icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button v-if="proxy.hasPerm('/schedule/orderList/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/schedule/orderList/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" fixed="right" width="170">
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/schedule/orderList/edit')"
                size="small"
                type="primary"
                link
                :disabled="row.statusName === '已取消'"
                @click="goEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click="goEdit(row, 'detail')"
              >
                详情
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/orderList/receive')"
                size="small"
                link
                type="primary"
                :disabled="row.statusName === '已取消' || row.statusName === '已接收'"
                @click="handleEdit(row, 'receive', '接收')"
              >
                接收
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/orderList/back')"
                size="small"
                link
                type="primary"
                :disabled="row.statusName === '已取消' || row.statusName === '已接收'"
                @click="handleEdit(row, 'back', '退回')"
              >
                退回
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
