<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="大队" prop="brigadeId">
        <el-select v-model="queryParams.brigadeId" placeholder="请选择大队" clearable style="width: 200px">
          <el-option v-for="item in brigadeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="date">
        <el-date-picker clearable v-model="queryParams.date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
          style="width: 200px" />
      </el-form-item>
      <el-form-item label="班次" prop="shift">
        <el-select v-model="queryParams.shift" placeholder="请选择班次" clearable style="width: 200px">
          <el-option label="白班" value="白班" />
          <el-option label="夜班" value="夜班" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['rateList:rateList:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['rateList:rateList:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['rateList:rateList:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['rateList:rateList:import']">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" prop="date" width="120" />
      <el-table-column label="旅检国内区域平均速率（高峰期时段）" align="center" prop="domesticAvgRate" width="220" />
      <el-table-column label="当班大队" align="center" prop="dutyBrigade" width="120" />
      <el-table-column label="T1-A速率（高峰期时段）" align="center" prop="t1ARate" width="180" />
      <el-table-column label="T1-B速率（高峰期时段）" align="center" prop="t1BRate" width="180" />
      <el-table-column label="T2国内速率（高峰期时段）" align="center" prop="t2DomesticRate" width="180" />
      <el-table-column label="T2国际速率（高峰期时段）" align="center" prop="t2InternationalRate" width="180" />
      <el-table-column label="班次" align="center" prop="shift" width="100" />
      <el-table-column label="T2中转（高峰期时段）" align="center" prop="t2TransferRate" width="160" />
      <el-table-column label="国际及中转区域平均速率（高峰期时段）" align="center" prop="internationalTransferAvgRate" width="240" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['rateList:rateList:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['rateList:rateList:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="rateListRef" :model="form" :rules="rules" label-width="240px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="日期" prop="date">
              <el-date-picker v-model="form.date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当班大队" prop="dutyBrigade">
              <el-select v-model="form.dutyBrigade" placeholder="请选择当班大队" style="width: 100%">
                <el-option v-for="item in brigadeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班次" prop="shift">
              <el-select v-model="form.shift" placeholder="请选择班次" style="width: 100%">
                <el-option label="白班" value="白班" />
                <el-option label="夜班" value="夜班" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="旅检国内区域平均速率（高峰期时段）" prop="domesticAvgRate">
              <el-input-number v-model="form.domesticAvgRate" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="T1-A速率（高峰期时段）" prop="t1ARate">
              <el-input-number v-model="form.t1ARate" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T1-B速率（高峰期时段）" prop="t1BRate">
              <el-input-number v-model="form.t1BRate" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="T2国内速率（高峰期时段）" prop="t2DomesticRate">
              <el-input-number v-model="form.t2DomesticRate" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T2国际速率（高峰期时段）" prop="t2InternationalRate">
              <el-input-number v-model="form.t2InternationalRate" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="T2中转（高峰期时段）" prop="t2TransferRate">
              <el-input-number v-model="form.t2TransferRate" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国际及中转区域平均速率（高峰期时段）" prop="internationalTransferAvgRate">
              <el-input-number v-model="form.internationalTransferAvgRate" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="导入" v-model="importOpen" width="500px" append-to-body>
      <el-upload ref="uploadRef" :auto-upload="false" :on-change="handleFileChange" :show-file-list="false"
        accept=".xlsx,.xls">
        <el-button type="primary">选取文件</el-button>
        <div class="el-upload__tip">只能上传xls/xlsx文件</div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitImport">确 定</el-button>
          <el-button @click="importOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { listRate, getRate, delRate, addRate, updateRate, exportRate } from '@/api/blockingData/rateList'
import { listDept } from '@/api/system/dept'

const { proxy } = getCurrentInstance()

const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const rateList = ref([])
const title = ref('')
const open = ref(false)
const importOpen = ref(false)
const importFile = ref(null)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  brigadeId: null,
  date: null,
  shift: null
})

const form = reactive({})

const rules = {
  date: [{ required: true, message: '日期不能为空', trigger: 'change' }],
  dutyBrigade: [{ required: true, message: '当班大队不能为空', trigger: 'change' }],
  shift: [{ required: true, message: '班次不能为空', trigger: 'change' }]
}

const brigadeOptions = ref([])

function getList() {
  loading.value = true
  listRate(queryParams).then(response => {
    rateList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function getDeptList() {
  listDept({}).then(response => {
    const deptList = response.data || []
    brigadeOptions.value = deptList.filter(item => item.deptType === 'BRIGADE').map(item => ({
      value: item.deptId,
      label: item.deptName
    }))
  })
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    id: null,
    date: null,
    dutyBrigade: null,
    shift: null,
    domesticAvgRate: 0,
    t1ARate: 0,
    t1BRate: 0,
    t2DomesticRate: 0,
    t2InternationalRate: 0,
    t2TransferRate: 0,
    internationalTransferAvgRate: 0
  }
  proxy.resetForm('rateListRef')
}

function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

function handleAdd() {
  reset()
  open.value = true
  title.value = '添加速率统计'
}

function handleUpdate(row) {
  reset()
  const id = row.id || ids.value[0]
  getRate(id).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = '修改速率统计'
  })
}

function submitForm() {
  proxy.$refs.rateListRef.validate(valid => {
    if (valid) {
      if (form.id != null) {
        updateRate(form).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addRate(form).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

function handleDelete(row) {
  const id = row.id || ids.value
  proxy.$modal.confirm('是否确认删除速率统计编号为"' + id + '"的数据项？').then(function () {
    return delRate(id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => { })
}

function handleExport() {
  proxy.download('rateList/export', {
    ...queryParams
  }, `速率统计_${new Date().getTime()}.xlsx`)
}

function handleImport() {
  importOpen.value = true
  importFile.value = null
}

function handleFileChange(file) {
  importFile.value = file.raw
}

function submitImport() {
  if (!importFile.value) {
    proxy.$modal.msgWarning('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  proxy.upload('rateList/importData', formData).then(response => {
    proxy.$modal.msgSuccess(response.msg)
    importOpen.value = false
    getList()
  })
}

onMounted(() => {
  getList()
  getDeptList()
})
</script>

<style lang="less" scoped>
.app-container {
  padding: 20px;
}

:deep(.el-table) {
  .el-table__header-wrapper {
    th {
      background-color: #303133;
      color: #ffffff;
      font-weight: 600;
    }
  }
}
</style>
