<!-- 业务结算列表 -->
<script lang="ts" setup name="BusinessSettlementList">
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IList, IListQuery, dictType } from './businessSettlement-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 { delBusinessSettlementList, exportBusinessSettlementList, getBusinessSettlementList } from '@/api/finance/businessSettlement'
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
const isUrgentMap = ref<dictType[]>([]) // 是否加急

// 查询条件
const listQuery: Ref<IListQuery> = ref({
  orderCode: '', // 委托书编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  deliverer: '', // 送样人
  offset: 1,
  limit: 20,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading
// 表头
const columns = ref<TableColumn[]>([
  { text: '委托书编号', value: 'orderCode', align: 'center', width: '160px' },
  { text: '委托方代码', value: 'customerNo', align: 'center', width: '160px' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '送样人', value: 'deliverer', align: 'center' },
  { text: '联系方式', value: 'delivererTel', align: 'center' },
  { text: '样品数量', value: 'sampleCount', align: 'center' },
  { text: '是否加急', value: 'isUrgent', align: 'center', width: '90px', styleFilter: (row: IList) => { return row.isUrgent === '是' ? 'color: red' : '' } },
  { text: '委托单创建时间', value: 'createTime', align: 'center', width: '180px' },
  { text: '标价(元)', value: 'postedPrice', align: 'center' },
  { text: '建议折扣(%)', value: 'suggestedDiscount', align: 'center' },
  { text: '建议价格(元)', value: 'suggestedPrice', align: 'center' },
  { text: '附加费用(元)', value: 'extraCharge', align: 'center' },
  { text: '附加费用说明', value: 'extraChargeIllustration', align: 'center' },
  { text: '总计结算费用(元)', value: 'totalSettlement', align: 'center' },
])
const list = ref<IList[]>([]) // 表格数据
// 选中的内容
const checkoutList = ref<string[]>([])

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getBusinessSettlementList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: IList) => {
      return {
        ...item,
        suggestedPrice: item.suggestedPrice ? (item.suggestedPrice / 100).toFixed(2) : `${item.suggestedPrice}`,
        totalSettlement: item.totalSettlement ? (item.totalSettlement / 100).toFixed(2) : `${item.totalSettlement}`,
        extraCharge: item.extraCharge ? (item.extraCharge / 100).toFixed(2) : `${item.extraCharge}`,
        postedPrice: item.postedPrice ? (item.postedPrice / 100).toFixed(2) : `${item.postedPrice}`,
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}
// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const reset = () => {
  listQuery.value = {
    orderCode: '', // 委托书编号
    customerNo: '', // 委托方代码
    customerName: '', // 委托方名称
    deliverer: '', // 送样人
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}

// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 新建
const add = () => {
  $router.push({ path: '/businessSettlement/add' })
}
// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      orderCode: listQuery.value.orderCode, // 委托书编号
      customerNo: listQuery.value.customerNo, // 委托方代码
      customerName: listQuery.value.customerName, // 委托方名称
      deliverer: listQuery.value.deliverer, // 送样人
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    exportBusinessSettlementList(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: IList) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '业务结算列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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: IList, pageType: 'edit' | 'detail') => {
  $router.push({ path: `/businessSettlement/${pageType}/${row.id}` })
}
// 删除
const handledelete = (id: string) => {
  ElMessageBox.confirm(
    '确认删除吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      delBusinessSettlementList({ ids: [id] }).then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        fetchData(true)
      })
    })
}
// 获取字典值
const getDict = async () => {
  // 是否加急
  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
    })
  })
}

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

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <search-area :need-clear="true" @search="searchList" @clear="reset">
        <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.customerName"
            placeholder="委托方名称"
            class="short-input"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.deliverer"
            placeholder="送样人"
            class="short-input"
            clearable
          />
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <icon-button
            v-if="proxy.hasPerm('/finance/businessSettlement/list/add')" icon="icon-add" title="新建" type="primary"
            @click="add"
          />
          <icon-button
            v-if="proxy.hasPerm('/finance/businessSettlement/list/export')" icon="icon-export" title="导出" type="primary"
            @click="exportAll"
          />
          <icon-button
            v-if="proxy.hasPerm('/finance/businessSettlement/list/print')" icon="icon-print" title="打印" type="primary"
            @click="printList"
          />
        </template>
        <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="120">
              <template #default="{ row }">
                <el-button 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 size="small" link type="danger" @click="handledelete(row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>
