<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="请选择大队" filterable 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>
        <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="['dailyLuggageInspectionScheduleByTime:dailyLuggageInspectionScheduleByTime:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dailyLuggageInspectionScheduleByTime:dailyLuggageInspectionScheduleByTime:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['dailyLuggageInspectionScheduleByTime:dailyLuggageInspectionScheduleByTime:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['dailyLuggageInspectionScheduleByTime:dailyLuggageInspectionScheduleByTime:import']">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dailyLuggageInspectionScheduleByTimeList"
      @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="brigadeName" />
      <el-table-column label="时间段" align="center" prop="timePeriod" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="T1行检箱包数" align="center" prop="t1WalkBagCount" />
      <el-table-column label="T1行检查堵数" align="center" prop="t1WalkBlockedCount" />
      <el-table-column label="T2行检箱包数" align="center" prop="t2WalkBagCount" />
      <el-table-column label="T2行检查堵数" align="center" prop="t2WalkBlockedCount" />
      <el-table-column label="T1旅检箱包数" align="center" prop="t1TravelBagCount" />
      <el-table-column label="T1旅检查堵数" align="center" prop="t1TravelBlockedCount" />
      <el-table-column label="T2旅检箱包数" align="center" prop="t2TravelBagCount" />
      <el-table-column label="T2旅检查堵数" align="center" prop="t2TravelBlockedCount" />
      <el-table-column label="过检行李数" align="center" prop="totalLuggageCount" />
      <el-table-column label="时段查堵件数" align="center" prop="totalBlockedCount" />
      <el-table-column label="查堵万分率" align="center" prop="blockedRate" />
      <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="['dailyLuggageInspectionScheduleByTime:dailyLuggageInspectionScheduleByTime:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['dailyLuggageInspectionScheduleByTime:dailyLuggageInspectionScheduleByTime: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="dailyLuggageInspectionScheduleByTimeRef" :model="form" :rules="rules" label-width="250px">
        <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="brigadeId">
              <el-select v-model="form.brigadeId" placeholder="请选择当班大队" filterable 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="timePeriod">
              <el-select v-model="form.timePeriod" placeholder="请选择时间段" filterable style="width: 100%">
                <el-option v-for="dict in blocked_time_period" :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="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="T1行检箱包数" prop="t1WalkBagCount">
              <el-input-number v-model="form.t1WalkBagCount" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T1行检查堵数" prop="t1WalkBlockedCount">
              <el-input-number v-model="form.t1WalkBlockedCount" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="T2行检箱包数（国内+国际）" prop="t2WalkBagCount">
              <el-input-number v-model="form.t2WalkBagCount" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T2行检查堵数" prop="t2WalkBlockedCount">
              <el-input-number v-model="form.t2WalkBlockedCount" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="T1旅检箱包数（国内+国际+中转）" prop="t1TravelBagCount">
              <el-input-number v-model="form.t1TravelBagCount" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T1旅检查堵数" prop="t1TravelBlockedCount">
              <el-input-number v-model="form.t1TravelBlockedCount" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="T2旅检箱包数" prop="t2TravelBagCount">
              <el-input-number v-model="form.t2TravelBagCount" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T2旅检查堵数" prop="t2TravelBlockedCount">
              <el-input-number v-model="form.t2TravelBlockedCount" :min="0" :precision="0" 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 { listDailyLuggageInspectionScheduleByTime, getDailyLuggageInspectionScheduleByTime, delDailyLuggageInspectionScheduleByTime, addDailyLuggageInspectionScheduleByTime, updateDailyLuggageInspectionScheduleByTime, exportDailyLuggageInspectionScheduleByTime, downloadTemplate } from '@/api/blockingData/dailyLuggageInspectionScheduleByTime'
import { listDept } from '@/api/system/dept'
import { useDict } from '@/utils/dict'
import { getToken } from '@/utils/auth'
import { UploadFilled } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { blocked_time_period } = useDict('blocked_time_period')

const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const dailyLuggageInspectionScheduleByTimeList = 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/pieceDaily/importData'
})

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

const form = reactive({})

const rules = {
  statDate: [{ required: true, message: '统计日期不能为空', trigger: 'change' }],
  brigadeId: [{ required: true, message: '当班大队不能为空', trigger: 'change' }],
  timePeriod: [{ required: true, message: '时间段不能为空', trigger: 'change' }],
  t1WalkBagCount: [
    { required: true, message: 'T1行检箱包数不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ],
  t1WalkBlockedCount: [
    { required: true, message: 'T1行检查堵数不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ],
  t2WalkBagCount: [
    { required: true, message: 'T2行检箱包数不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ],
  t2WalkBlockedCount: [
    { required: true, message: 'T2行检查堵数不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ],
  t1TravelBagCount: [
    { required: true, message: 'T1旅检箱包数不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ],
  t1TravelBlockedCount: [
    { required: true, message: 'T1旅检查堵数不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ],
  t2TravelBagCount: [
    { required: true, message: 'T2旅检箱包数不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ],
  t2TravelBlockedCount: [
    { required: true, message: 'T2旅检查堵数不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ]
  // remark 不设置必填校验
}

const brigadeOptions = ref([])

function getList() {
  loading.value = true
  listDailyLuggageInspectionScheduleByTime(queryParams).then(response => {
    dailyLuggageInspectionScheduleByTimeList.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' && [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,
    brigadeId: null,
    timePeriod: null,
    remark: null,
    t1WalkBagCount: null,
    t1WalkBlockedCount: null,
    t2WalkBagCount: null,
    t2WalkBlockedCount: null,
    t1TravelBagCount: null,
    t1TravelBlockedCount: null,
    t2TravelBagCount: null,
    t2TravelBlockedCount: null,
    totalLuggageCount: 0,
    totalBlockedCount: 0,
    blockedRate: 0
  })
  proxy.resetForm('dailyLuggageInspectionScheduleByTimeRef')
}

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]
  getDailyLuggageInspectionScheduleByTime(id).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = '修改每日各时段查堵行李'
  })
}

function submitForm() {
  proxy.$refs.dailyLuggageInspectionScheduleByTimeRef.validate(valid => {
    if (valid) {
      // 获取brigadeName
      const selectedBrigade = brigadeOptions.value.find(item => item.value === form.brigadeId)
      if (selectedBrigade) {
        form.brigadeName = selectedBrigade.label
      }

      if (form.id != null) {
        updateDailyLuggageInspectionScheduleByTime(form).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          reset()
          getList()
        })
      } else {
        addDailyLuggageInspectionScheduleByTime(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 delDailyLuggageInspectionScheduleByTime(id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => { })
}

function handleExport() {
  proxy.download('/blocked/pieceDaily/export', {
    ...queryParams
  }, `每日各时段查堵行李_${new Date().getTime()}.xlsx`)
}

function handleImport() {
  upload.open = true
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('blocked/pieceDaily/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>
