<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="当班大队" prop="dutyBrigadeId">
        <el-select v-model="queryParams.dutyBrigadeId" 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="statDate">
        <el-date-picker clearable v-model="queryParams.statDate" 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 v-for="dict in shift" :key="dict.value" :label="dict.label" :value="dict.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="['blocked:rate:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['blocked:rate:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['blocked:rate:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['blocked:rate: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="statDate" />
      <el-table-column label="旅检国内区域平均速率（高峰期时段）" align="center" prop="travelInspectionDomesticAvgRatePeak"
        min-width="120" />
      <el-table-column label="当班大队" align="center" prop="dutyBrigadeName" />
      <el-table-column label="T1-A区速率（高峰期时段）" align="center" prop="t1AAreaRatePeak" />
      <el-table-column label="T1-B区速率（高峰期时段）" align="center" prop="t1BAreaRatePeak" />
      <el-table-column label="T2-国内速率（高峰期时段）" align="center" prop="t2DomesticRatePeak" />
      <el-table-column label="T2-国际速率（高峰期时段）" align="center" prop="t2InternationalRatePeak" />
      <el-table-column label="班次" align="center" prop="shift" min-width="100">
        <template #default="scope">
          {{ getDictLabel(shift, scope.row.shift) }}
        </template>
      </el-table-column>
      <el-table-column label="T2-中转（高峰期时段）" align="center" prop="t2TransferRatePeak" />
      <el-table-column label="国际及中转区域平均速率（高峰期时段）" align="center" prop="internationalTransferAvgRatePeak"
        min-width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="180">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['blocked:rate:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['blocked:rate: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="1000px" append-to-body @closed="reset" destroy-on-close>
      <el-form ref="rateListRef" :model="form" :rules="rules" label-width="280px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="日期" prop="statDate">
              <el-date-picker v-model="form.statDate" 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="dutyBrigadeId">
              <el-select v-model="form.dutyBrigadeId" 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 v-for="dict in shift" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="旅检国内区域平均速率（高峰期时段）" prop="travelInspectionDomesticAvgRatePeak">
              <el-input-number v-model="form.travelInspectionDomesticAvgRatePeak" :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="t1AAreaRatePeak">
              <el-input-number v-model="form.t1AAreaRatePeak" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T1-B区速率（高峰期时段）" prop="t1BAreaRatePeak">
              <el-input-number v-model="form.t1BAreaRatePeak" :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="t2DomesticRatePeak">
              <el-input-number v-model="form.t2DomesticRatePeak" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T2-国际速率（高峰期时段）" prop="t2InternationalRatePeak">
              <el-input-number v-model="form.t2InternationalRatePeak" :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="t2TransferRatePeak">
              <el-input-number v-model="form.t2TransferRatePeak" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国际及中转区域平均速率（高峰期时段）" prop="internationalTransferAvgRatePeak">
              <el-input-number v-model="form.internationalTransferAvgRatePeak" :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="upload.open" width="500px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = 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, downloadTemplate } from '@/api/blockingData/rateList'
import { listDept } from '@/api/system/dept'
import { getToken } from '@/utils/auth'
import { UploadFilled } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { shift } = proxy.useDict('shift')

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 upload = reactive({
  open: false,
  isUploading: false,
  headers: { Authorization: 'Bearer ' + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + '/blocked/rate/importData'
})

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

const form = reactive({})

const rules = {
  statDate: [{ required: true, message: '日期不能为空', trigger: 'change' }],
  dutyBrigadeId: [{ required: true, message: '当班大队不能为空', trigger: 'change' }],
  shift: [{ required: true, message: '班次不能为空', trigger: 'change' }],
  travelInspectionDomesticAvgRatePeak: [{ required: true, message: '旅检国内区域平均速率（高峰期时段）不能为空', trigger: 'change' }],
  t1AAreaRatePeak: [{ required: true, message: 'T1-A区速率（高峰期时段）不能为空', trigger: 'change' }],
  t1BAreaRatePeak: [{ required: true, message: 'T1-B区速率（高峰期时段）不能为空', trigger: 'change' }],
  t2DomesticRatePeak: [{ required: true, message: 'T2-国内速率（高峰期时段）不能为空', trigger: 'change' }],
  t2InternationalRatePeak: [{ required: true, message: 'T2-国际速率（高峰期时段）不能为空', trigger: 'change' }],
  t2TransferRatePeak: [{ required: true, message: 'T2-中转（高峰期时段）不能为空', trigger: 'change' }],
  internationalTransferAvgRatePeak: [{ 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
  })
}

const getDictLabel = (dictList, value) => {
  if (!dictList || !value) return ''
  const dict = dictList.find(item => item.value === value)
  return dict ? dict.label : value
}

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

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

function reset() {
  Object.assign(form, {
    id: null,
    statDate: null,
    dutyBrigadeId: null,
    shift: null,
    shiftDesc: null,
    travelInspectionDomesticAvgRatePeak: 0,
    t1AAreaRatePeak: 0,
    t1BAreaRatePeak: 0,
    t2DomesticRatePeak: 0,
    t2InternationalRatePeak: 0,
    t2TransferRatePeak: 0,
    internationalTransferAvgRatePeak: 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()
  // 设置默认当前日期
  form.statDate = new Date().toISOString().split('T')[0]
  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.shift) {
        const shiftItem = shift.value.find(item => item.value === form.shift)
        form.shiftDesc = shiftItem ? shiftItem.label : null
      }
      if (form.dutyBrigadeId) {
        const brigadeItem = brigadeOptions.value.find(item => item.value === form.dutyBrigadeId)
        form.dutyBrigadeName = brigadeItem ? brigadeItem.label : null
      }

      if (form.id != null) {
        updateRate(form).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          reset()
          getList()
        })
      } else {
        addRate(form).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          reset()
          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('blocked/rate/export', {
    ...queryParams
  }, `速率统计_${new Date().getTime()}.xlsx`)
}

function handleImport() {
  upload.open = true
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('/blocked/rate/importTemplate', {}, `速率统计模板${new Date().getTime()}.xlsx`)
}

/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs.uploadRef.handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs.uploadRef.submit()
}

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

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