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

// 查询条件
const listQuery: Ref<IListQuery> = ref({
  orderCode: '', // 委托书编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  deliverer: '', // 送样人
  orderTimeStart: '', //	委托日期开始
  orderTimeEnd: '', //	委托日期结束
  offset: 1,
  limit: 20,
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'businessSettlement', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('businessSettlement') || {
  orderCode: '', // 委托书编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  deliverer: '', // 送样人
  orderTimeStart: '', //	委托日期开始
  orderTimeEnd: '', //	委托日期结束
  offset: 1,
  limit: 20,
}
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
// 表头
const columns = ref<TableColumn[]>([
  { text: '业务结算单类型', value: 'orderTypeName', align: 'center', width: '160' },
  { text: '委托单编号', value: 'orderCode', align: 'center', width: '160' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '委托日期', value: 'orderTime', align: 'center', width: '120' },
  { text: '样品数量', value: 'sampleCount', align: 'center' },
  { text: '样品库房', value: 'sampleWarehouse', align: 'center', width: '100' },
  { text: '证书库房', value: 'certWarehouse', align: 'center', width: '100' },
  { text: '费用状态', value: 'feeStatus', align: 'center', width: '100' },
  { text: '是否到账', value: 'received', align: 'center', width: '100' },
  { text: '检测费(实)(元)', value: 'actualTestFee', align: 'center' },
  { text: '检测费(应)(元)', value: 'shouldTestFee', align: 'center' },
  { text: '实收合计/报价合计(元)', value: 'actualTotalFee', align: 'center' },
  { text: '到账金额(元)', value: 'receivedAmount', align: 'center' },
  { text: '开票金额(元)', value: 'invoiceAmount', align: 'center' },
])
const list = ref<IList[]>([]) // 表格数据
// 选中的内容
const checkoutIdList = ref<string[]>([])
const checkoutList = ref<string[]>([]) as any

// 数据查询
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,
        orderTime: item.orderTime ? dayjs(item.orderTime).format('YYYY-MM-DD') : item.orderTime,
        orderTypeName: item.orderType === '1' ? '检测项目结算单' : '合作机构结算单/校准费用结算单',
      }
    })
    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: '', // 送样人
    orderTimeStart: '', //	委托日期开始
    orderTimeEnd: '', //	委托日期结束
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  fetchData(true)
}

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

// 新建
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, // 送样人
      orderTimeStart: listQuery.value.orderTimeStart, //	委托日期开始
      orderTimeEnd: listQuery.value.orderTimeEnd, //	委托日期结束
      offset: 1,
      limit: 20,
      ids: checkoutIdList.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 (checkoutIdList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '业务结算列表')
  }
  else if (checkoutIdList.value.length > 0) {
    const printList = list.value.filter((item: IList) => checkoutIdList.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
    })
  })
}

// 时间变更
watch(timeRange, (val) => {
  if (val) {
    listQuery.value.orderTimeStart = `${val[0]}`
    listQuery.value.orderTimeEnd = `${val[1]}`
  }
  else {
    listQuery.value.orderTimeStart = ''
    listQuery.value.orderTimeEnd = ''
  }
})

// -------------------------------导出结算单-------------------------------------------------------
const showPopover = ref(false) // 是否展示popover
const exportSettlementDocType = ref('1') // 导出结算单的类型

// 点击图标
const exportSettlementDoc = () => {
  showPopover.value = true
}

/**
 * js检查数组中的属性值不能重复
 * @param list 要检查的数组
 * @param property key
 */
function useArrayDataUnique(list: any, prop: string) {
  return list.every((item: any) => item[prop] === list[0][prop])
}

// 点击确定
const confirm = () => {
  if (!checkoutIdList.value.length) {
    ElMessage.warning('请选中数据')
    return false
  }
  if (exportSettlementDocType.value === '4') { // 业务统计
    console.log(checkoutList.value)
    console.log(useArrayDataUnique(checkoutList.value, 'customerId'))

    if (checkoutList.value.length > 1 && !useArrayDataUnique(checkoutList.value, 'customerId')) {
      ElMessage.warning('只能导出同一委托方的数据')
      return false
    }
  }
  else {
    if (checkoutIdList.value.length > 1) {
      ElMessage.warning('最多可导出一条')
      return false
    }
    if ((checkoutList.value[0].orderType === '1' && exportSettlementDocType.value !== '1') || (checkoutList.value[0].orderType === '2' && exportSettlementDocType.value !== '2' && exportSettlementDocType.value !== '3')) {
      ElMessage.warning('请导出对应类型的业务结算单')
      return false
    }
  }

  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  showPopover.value = false // 关闭popover
  const exportTitle = exportSettlementDocType.value === '1' ? '检测项目结算单' : exportSettlementDocType.value === '2' ? '合作机构结算单' : exportSettlementDocType.value === '3' ? '校准费用结算单' : '业务统计'
  let params
  if (exportSettlementDocType.value === '4') { // 业务统计
    params = { ids: checkoutIdList.value, settlementType: exportSettlementDocType.value }
  }
  else {
    params = { id: checkoutIdList.value[0], settlementType: exportSettlementDocType.value }
  }
  getStream(params).then((res) => {
    exportFile(res.data, `${exportTitle}.xlsx`)
    loading.close()
  }).catch(() => {
    loading.close()
  })
}
// -----------------------------------------------------------------------------------------------

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

<template>
  <div class="finance-businessSettlement-list">
    <!-- 布局 -->
    <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-date-picker
            v-model="timeRange" type="daterange" range-separator="到" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" start-placeholder="委托日期(开始)" end-placeholder="委托日期(结束)" clearable
          />
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <el-popover
            v-if="proxy.hasPerm('/schedule/orderList/add')"
            :visible="showPopover"
            trigger="click"
            width="200"
          >
            <el-radio-group v-model="exportSettlementDocType">
              <el-radio label="1" size="large">
                检测项目结算单
              </el-radio>
              <el-radio label="2" size="large">
                合作机构结算单
              </el-radio>
              <el-radio label="3" size="large">
                校准费用结算单
              </el-radio>
              <el-radio label="4" size="large">
                业务统计
              </el-radio>
            </el-radio-group>
            <div style="text-align: right; margin: 0;margin-top: 16px;">
              <el-button size="small" type="info" @click="showPopover = false">
                取消
              </el-button>
              <el-button size="small" type="primary" @click="confirm">
                确定
              </el-button>
            </div>
            <template #reference>
              <icon-button
                v-if="proxy.hasPerm('/finance/businessSettlement/list/export')" icon="icon-export-settlementDoc" title="导出结算单" type="primary"
                @click="exportSettlementDoc"
              />
            </template>
          </el-popover>

          <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>

<style lang="scss">
.finance-businessSettlement-list {
  .el-radio__label {
    display: block !important;
  }
}
</style>

