<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="recordDate">
        <el-date-picker v-model="queryParams.recordDate" 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="item in shiftOptions" :key="item.value" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="当班大队" prop="brigade">
        <el-select v-model="queryParams.brigade" placeholder="请选择当班大队" clearable style="width: 200px">
          <el-option v-for="item in brigadeOptions" :key="item.value" :label="item.label" :value="item.label" />
        </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="['runData:seizeData:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['runData:seizeData:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['runData:seizeData:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['runData:seizeData:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="seizeDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" prop="recordDate" />
      <el-table-column label="班次" align="center" prop="shift" />
      <el-table-column label="当班大队" align="center" prop="brigade" />
      
      <!-- T1区域数据 -->
      <el-table-column label="T1火种" align="center" prop="t1FireSource" />
      <el-table-column label="T1刀具" align="center" prop="t1Knife" />
      <el-table-column label="T1警械器具" align="center" prop="t1PoliceWeapon" />
      <el-table-column label="T1烟花爆竹" align="center" prop="t1Firework" />
      <el-table-column label="T1活体动物" align="center" prop="t1LiveAnimal" />
      <el-table-column label="T1腐蚀性物品" align="center" prop="t1Corrosive" />
      <el-table-column label="T1用假冒他" align="center" prop="t1FakeId" />
      <el-table-column label="T1爆炸装置" align="center" prop="t1Explosive" />
      <el-table-column label="T1工具" align="center" prop="t1Tool" />
      <el-table-column label="T1枪支弹药" align="center" prop="t1GunAmmo" />
      <el-table-column label="T1扫黄打非" align="center" prop="t1Illegal" />
      <el-table-column label="T1其他" align="center" prop="t1Other" />
      <el-table-column label="T1总数" align="center" prop="t1Total" />
      
      <!-- T2区域数据 -->
      <el-table-column label="T2火种" align="center" prop="t2FireSource" />
      <el-table-column label="T2刀具" align="center" prop="t2Knife" />
      <el-table-column label="T2警械器具" align="center" prop="t2PoliceWeapon" />
      <el-table-column label="T2烟花爆竹" align="center" prop="t2Firework" />
      <el-table-column label="T2活体动物" align="center" prop="t2LiveAnimal" />
      <el-table-column label="T2腐蚀性物品" align="center" prop="t2Corrosive" />
      <el-table-column label="T2用假冒他" align="center" prop="t2FakeId" />
      <el-table-column label="T2爆炸装置" align="center" prop="t2Explosive" />
      <el-table-column label="T2工具" align="center" prop="t2Tool" />
      <el-table-column label="T2枪支弹药" align="center" prop="t2GunAmmo" />
      <el-table-column label="T2扫黄打非" align="center" prop="t2Illegal" />
      <el-table-column label="T2其他" align="center" prop="t2Other" />
      <el-table-column label="T2总数" align="center" prop="t2Total" />
      
      <el-table-column label="T1总数+T2总数" align="center" prop="grandTotal" >
        
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">  
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['runData:seizeData:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['runData:seizeData: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>
      <el-form ref="seizeDataRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="日期" prop="recordDate">
              <el-date-picker v-model="form.recordDate" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD" 
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班次" prop="shift">
              <el-select v-model="form.shift" placeholder="请选择班次" filterable style="width: 100%">
                <el-option v-for="item in shiftOptions" :key="item.value" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当班大队" prop="brigade">
              <el-select v-model="form.brigade" placeholder="请选择当班大队" filterable style="width: 100%">
                <el-option v-for="item in brigadeOptions" :key="item.value" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- T1区域 -->
        <el-divider content-position="left">T1区域数据</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="T1火种" prop="t1FireSource">
              <el-input-number :precision="0" v-model="form.t1FireSource" :min="0" placeholder="请输入T1火种" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1刀具" prop="t1Knife">
              <el-input-number :precision="0" v-model="form.t1Knife" :min="0" placeholder="请输入T1刀具" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1警械器具" prop="t1PoliceWeapon">
              <el-input-number :precision="0" v-model="form.t1PoliceWeapon" :min="0" placeholder="请输入T1警械器具" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1烟花爆竹" prop="t1Firework">
              <el-input-number :precision="0" v-model="form.t1Firework" :min="0" placeholder="请输入T1烟花爆竹" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="T1活体动物" prop="t1LiveAnimal">
              <el-input-number :precision="0" v-model="form.t1LiveAnimal" :min="0" placeholder="请输入T1活体动物" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1腐蚀性物品" prop="t1Corrosive">
              <el-input-number :precision="0" v-model="form.t1Corrosive" :min="0" placeholder="请输入T1腐蚀性物品" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1用假冒他" prop="t1FakeId">
              <el-input-number :precision="0" v-model="form.t1FakeId" :min="0" placeholder="请输入T1用假冒他" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1爆炸装置" prop="t1Explosive">
              <el-input-number :precision="0" v-model="form.t1Explosive" :min="0" placeholder="请输入T1爆炸装置" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="T1工具" prop="t1Tool">
              <el-input-number :precision="0" v-model="form.t1Tool" :min="0" placeholder="请输入T1工具" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1枪支弹药" prop="t1GunAmmo">
              <el-input-number :precision="0" v-model="form.t1GunAmmo" :min="0" placeholder="请输入T1枪支弹药" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1扫黄打非" prop="t1Illegal">
              <el-input-number :precision="0" v-model="form.t1Illegal" :min="0" placeholder="请输入T1扫黄打非" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T1其他" prop="t1Other">
              <el-input-number :precision="0" v-model="form.t1Other" :min="0" placeholder="请输入T1其他" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- T2区域 -->
        <el-divider content-position="left">T2区域数据</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="T2火种" prop="t2FireSource">
              <el-input-number :precision="0" v-model="form.t2FireSource" :min="0" placeholder="请输入T2火种" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2刀具" prop="t2Knife">
              <el-input-number :precision="0" v-model="form.t2Knife" :min="0" placeholder="请输入T2刀具" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2警械器具" prop="t2PoliceWeapon">
              <el-input-number :precision="0" v-model="form.t2PoliceWeapon" :min="0" placeholder="请输入T2警械器具" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2烟花爆竹" prop="t2Firework">
              <el-input-number :precision="0" v-model="form.t2Firework" :min="0" placeholder="请输入T2烟花爆竹" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="T2活体动物" prop="t2LiveAnimal">
              <el-input-number :precision="0" v-model="form.t2LiveAnimal" :min="0" placeholder="请输入T2活体动物" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2腐蚀性物品" prop="t2Corrosive">
              <el-input-number :precision="0" v-model="form.t2Corrosive" :min="0" placeholder="请输入T2腐蚀性物品" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2用假冒他" prop="t2FakeId">
              <el-input-number :precision="0" v-model="form.t2FakeId" :min="0" placeholder="请输入T2用假冒他" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2爆炸装置" prop="t2Explosive">
              <el-input-number :precision="0" v-model="form.t2Explosive" :min="0" placeholder="请输入T2爆炸装置" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="T2工具" prop="t2Tool">
              <el-input-number :precision="0" v-model="form.t2Tool" :min="0" placeholder="请输入T2工具" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2枪支弹药" prop="t2GunAmmo">
              <el-input-number :precision="0" v-model="form.t2GunAmmo" :min="0" placeholder="请输入T2枪支弹药" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2扫黄打非" prop="t2Illegal">
              <el-input-number :precision="0" v-model="form.t2Illegal" :min="0" placeholder="请输入T2扫黄打非" style="width: 100%" @change="calculateTotals" />
            </el-form-item>
            <el-form-item label="T2其他" prop="t2Other">
              <el-input-number :precision="0" v-model="form.t2Other" :min="0" placeholder="请输入T2其他" style="width: 100%" @change="calculateTotals" />
            </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="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :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">
            <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 name="SeizeData">
import { listSeizeData, getSeizeData, delSeizeData, addSeizeData, updateSeizeData } from "@/api/runData/seizeData"
import { listDept } from '@/api/system/dept'
import { getToken } from '@/utils/auth'

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

const seizeDataList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 班次字典
const shiftOptions = shift

// 大队选项
const brigadeOptions = ref([])

// 导入参数
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的查获数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/item/hkSeizureStat/importData"
})

const uploadRef = ref()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    recordDate: null,
    shift: null,
    brigade: null
  },
  rules: {
    recordDate: [
      { required: true, message: "日期不能为空", trigger: "blur" }
    ],
    shift: [
      { required: true, message: "班次不能为空", trigger: "blur" }
    ],
    brigade: [
      { required: true, message: "当班大队不能为空", trigger: "blur" }
    ],
    t1FireSource: [
      { type: "integer", message: "T1火种必须为整数", trigger: "blur" }
    ],
    t1Knife: [
      { type: "integer", message: "T1刀具必须为整数", trigger: "blur" }
    ],
    t1PoliceWeapon: [
      { type: "integer", message: "T1警械器具必须为整数", trigger: "blur" }
    ],
    t1Firework: [
      { type: "integer", message: "T1烟花爆竹必须为整数", trigger: "blur" }
    ],
    t1LiveAnimal: [
      { type: "integer", message: "T1活体动物必须为整数", trigger: "blur" }
    ],
    t1Corrosive: [
      { type: "integer", message: "T1腐蚀性物品必须为整数", trigger: "blur" }
    ],
    t1FakeId: [
      { type: "integer", message: "T1用假冒他必须为整数", trigger: "blur" }
    ],
    t1Explosive: [
      { type: "integer", message: "T1爆炸装置必须为整数", trigger: "blur" }
    ],
    t1Tool: [
      { type: "integer", message: "T1工具必须为整数", trigger: "blur" }
    ],
    t1GunAmmo: [
      { type: "integer", message: "T1枪支弹药必须为整数", trigger: "blur" }
    ],
    t1Illegal: [
      { type: "integer", message: "T1扫黄打非必须为整数", trigger: "blur" }
    ],
    t1Other: [
      { type: "integer", message: "T1其他必须为整数", trigger: "blur" }
    ],
    t2FireSource: [
      { type: "integer", message: "T2火种必须为整数", trigger: "blur" }
    ],
    t2Knife: [
      { type: "integer", message: "T2刀具必须为整数", trigger: "blur" }
    ],
    t2PoliceWeapon: [
      { type: "integer", message: "T2警械器具必须为整数", trigger: "blur" }
    ],
    t2Firework: [
      { type: "integer", message: "T2烟花爆竹必须为整数", trigger: "blur" }
    ],
    t2LiveAnimal: [
      { type: "integer", message: "T2活体动物必须为整数", trigger: "blur" }
    ],
    t2Corrosive: [
      { type: "integer", message: "T2腐蚀性物品必须为整数", trigger: "blur" }
    ],
    t2FakeId: [
      { type: "integer", message: "T2用假冒他必须为整数", trigger: "blur" }
    ],
    t2Explosive: [
      { type: "integer", message: "T2爆炸装置必须为整数", trigger: "blur" }
    ],
    t2Tool: [
      { type: "integer", message: "T2工具必须为整数", trigger: "blur" }
    ],
    t2GunAmmo: [
      { type: "integer", message: "T2枪支弹药必须为整数", trigger: "blur" }
    ],
    t2Illegal: [
      { type: "integer", message: "T2扫黄打非必须为整数", trigger: "blur" }
    ],
    t2Other: [
      { type: "integer", message: "T2其他必须为整数", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询查获数据列表 */
function getList() {
  loading.value = true
  listSeizeData(queryParams.value).then(response => {
    seizeDataList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    recordDate: null,
    shift: null,
    brigade: null,
    brigadeName: null,
    // T1区域数据
    t1FireSource: null,
    t1Knife: null,
    t1PoliceWeapon: null,
    t1Firework: null,
    t1LiveAnimal: null,
    t1Corrosive: null,
    t1FakeId: null,
    t1Explosive: null,
    t1Tool: null,
    t1GunAmmo: null,
    t1Illegal: null,
    t1Other: null,
    // T2区域数据
    t2FireSource: null,
    t2Knife: null,
    t2PoliceWeapon: null,
    t2Firework: null,
    t2LiveAnimal: null,
    t2Corrosive: null,
    t2FakeId: null,
    t2Explosive: null,
    t2Tool: null,
    t2GunAmmo: null,
    t2Illegal: null,
    t2Other: null
  }
  proxy.resetForm("seizeDataRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.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
  getSeizeData(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改查获数据"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["seizeDataRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSeizeData(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSeizeData(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除数据项？').then(function () {
    return delSeizeData(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  // 过滤掉值为null的参数，但保留分页参数
  const filteredParams = Object.fromEntries(
    Object.entries(queryParams.value).filter(([key, value]) => {
      // 保留分页参数
      if (key === 'pageNum' || key === 'pageSize') return true
      // 过滤掉其他为null的参数
      return value !== null
    })
  )
  
  proxy.download('/item/hkSeizureStat/export', filteredParams, `seizeData_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "查获数据导入"
  upload.open = true
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('/item/hkSeizureStat/importTemplate', {
  }, `查获数据导入模板_${new Date().getTime()}.xlsx`)
}

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

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  uploadRef.value.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() {
  uploadRef.value.submit()
}

getList()
getDeptList()

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
    }))
  })
}
</script>