<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="reviewDate">
        <el-date-picker clearable v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" style="width: 300px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="被回查人" prop="reviewedUserId">
        <el-select v-model="queryParams.reviewedUserId" placeholder="请选择被回查人" clearable style="width: 200px">
          <el-option v-for="item in personOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="分管班组长" prop="teamLeaderId">
        <el-select v-model="queryParams.teamLeaderId" placeholder="请选择分管班组长" clearable style="width: 200px">
          <el-option v-for="item in teamLeaderOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="分管主管" prop="supervisorId">
        <el-select v-model="queryParams.supervisorId" placeholder="请选择分管主管" clearable style="width: 200px">
          <el-option v-for="item in supervisorOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="判别类型" prop="discriminationType">
        <el-select v-model="queryParams.discriminationType" placeholder="请选择判别类型" clearable style="width: 200px">
          <el-option v-for="item in discrimination_type" :key="item.value" :label="item.label" :value="item.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="['missedInspection:missedInspection:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['missedInspection:missedInspection:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['missedInspection:missedInspection:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['missedInspection:missedInspection:import']">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="missedInspectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="大队" align="center" prop="brigadeName" min-width="120" />
      <el-table-column label="区域" align="center" prop="areaName" min-width="120" />
      <el-table-column label="被回查人" align="center" prop="reviewedUserName" min-width="120" />
      <el-table-column label="回查日期" align="center" prop="reviewDate" min-width="120" />
      <el-table-column label="漏检时间" align="center" prop="missCheckTime" min-width="180" />
      <el-table-column label="漏检时间段" align="center" prop="missCheckTimePeriod" min-width="150" />
      <el-table-column label="上岗位置" align="center" prop="channelName" min-width="120" />
      <el-table-column label="分管主管" align="center" prop="supervisorName" min-width="120" />
      <el-table-column label="代管主管" align="center" prop="actingSupervisorName" min-width="120" />
      <el-table-column label="分管班组长" align="center" prop="teamLeaderName" min-width="120" />
      <el-table-column label="物品位置" align="center" prop="itemLocation" min-width="120" />
      <el-table-column label="简单/难" align="center" prop="difficultyLevel" min-width="100" />
      <el-table-column label="回查人" align="center" prop="reviewUserName" min-width="120" />
      <el-table-column label="判别类型" align="center" prop="discriminationType" min-width="100" />
      <el-table-column label="是否追回" align="center" prop="isRecovered" min-width="100">
        <template #default="scope">
          {{ scope.row.isRecovered == 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="开机年限" align="center" prop="machineOperatingYears" min-width="100" />
      <el-table-column label="证书级别" align="center" prop="certificateLevel" min-width="100" />
      <el-table-column label="人员性别" align="center" prop="gender" min-width="100" />
      <el-table-column label="漏检原因分类" align="center" prop="missCheckReasonCategory" min-width="220" />
      <el-table-column label="月考成绩" align="center" prop="monthlyAssessment" min-width="100" />
      <el-table-column label="本月自测有无漏检" align="center" prop="selfTestHasMissCheck" min-width="160">
        <template #default="scope">
            {{ scope.row.selfTestHasMissCheck ? '有' : '无' }}
        </template>
      </el-table-column>
      <el-table-column label="漏检物品" align="center" prop="missCheckItem" min-width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['missedInspection:missedInspection:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['missedInspection:missedInspection: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="missedInspectionRef" :model="form" :rules="rules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="大队" prop="brigadeId">
              <el-select v-model="form.brigadeId" 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-col :span="12">
            <el-form-item label="区域" prop="areaId">
              <el-select v-model="form.areaId" placeholder="请选择区域" style="width: 100%">
                <el-option v-for="item in areaOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="被回查人" prop="reviewedUserId">
              <el-select v-model="form.reviewedUserId" placeholder="请选择被回查人" style="width: 100%"
                @change="handleReviewedUserChange">
                <el-option v-for="item in personOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回查日期" prop="reviewDate">
              <el-date-picker v-model="form.reviewDate" type="date" placeholder="选择回查日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="漏检时间" prop="missCheckTime">
              <el-date-picker v-model="form.missCheckTime" type="datetime" placeholder="请选择漏检时间"
                value-format="YYYY-MM-DD HH:mm" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="漏检时间段" prop="missCheckTimePeriod">
              <el-select v-model="form.missCheckTimePeriod" placeholder="请选择漏检时间段" style="width: 100%">
                <el-option v-for="item in blocked_time_period" :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="channelId">
              <el-select v-model="form.channelId" placeholder="请选择上岗位置" style="width: 100%">
                <el-option v-for="item in channelOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="漏检物品" prop="missCheckItem">
              <el-tree-select
                v-model="form.missCheckItem"
                :data="missCheckItemOptions"
                :props="{ value: 'name', label: 'name', children: 'children' }"
                value-key="name"
                placeholder="请选择漏检物品"
                check-strictly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分管主管" prop="supervisorId">
              <el-select v-model="form.supervisorId" placeholder="请选择分管主管" style="width: 100%">
                <el-option v-for="item in supervisorOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代管主管" prop="actingSupervisorId">
              <el-select v-model="form.actingSupervisorId" placeholder="请选择代管主管" style="width: 100%">
                <el-option v-for="item in supervisorOptions" :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="teamLeaderId">
              <el-select v-model="form.teamLeaderId" placeholder="请选择分管班组长" style="width: 100%">
                <el-option v-for="item in teamLeaderOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物品位置" prop="itemLocation">
              <el-select v-model="form.itemLocation" placeholder="请选择物品位置" style="width: 100%">
                <el-option v-for="item in blocked_item_position" :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="difficultyLevel">
              <el-select v-model="form.difficultyLevel" 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="reviewUserId">
              <el-select v-model="form.reviewUserId" placeholder="请选择回查人" style="width: 100%">
                <el-option v-for="item in personOptions" :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="discriminationType">
              <el-select v-model="form.discriminationType" placeholder="请选择判别类型" style="width: 100%">
                <el-option v-for="item in discrimination_type" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否追回" prop="isRecovered">
              <el-select v-model="form.isRecovered" placeholder="请选择是否追回" style="width: 100%">
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开机年限" prop="machineOperatingYears">
              <el-select v-model="form.machineOperatingYears" placeholder="请选择开机年限" style="width: 100%">
                <el-option v-for="item in blocked_operating_years" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书级别" prop="certificateLevel">
              <el-input v-model="form.certificateLevel" placeholder="请输入证书级别" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="人员性别" prop="gender">
              <el-select v-model="form.gender" 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="missCheckReasonCategory">
              <el-select v-model="form.missCheckReasonCategory" placeholder="请选择漏检原因分类" style="width: 100%">
                <el-option v-for="item in blocked_miss_check_reason" :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="monthlyAssessment">
              <el-select v-model="form.monthlyAssessment" placeholder="请选择月考成绩" style="width: 100%">
                <el-option v-for="item in blocked_monthly_exam_result" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本月自测有无漏检" prop="selfTestHasMissCheck">
              <el-input-number v-model="form.selfTestHasMissCheck" :min="0" :max="2" :precision="0"
                placeholder="请输入0-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 { listPosition } from '@/api/system/position'
import { listMissedInspection, getMissedInspection, delMissedInspection, addMissedInspection, updateMissedInspection, exportMissedInspection, downloadTemplate } from '@/api/blockingData/missedInspection'
import { listDept } from '@/api/system/dept'
import { listUser, selectUserLeaderListByCondition } from '@/api/system/user'
import { listCategory } from '@/api/system/category'
import { useDict } from '@/utils/dict'
import { getToken } from '@/utils/auth'
import { UploadFilled } from '@element-plus/icons-vue'

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 missedInspectionList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 日期范围
const dateRange = ref([])
// 漏检物品树状选项
const missCheckItemOptions = ref([])

const upload = reactive({
  open: false,
  isUploading: false,
  headers: { Authorization: 'Bearer ' + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + '/blocked/missReview/importData'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  brigadeId: null,
  reviewDate: null,
  reviewedUserId: null,
  teamLeaderId: null,
  supervisorId: null,
  discriminationType: null
})

// 表单参数
const form = reactive({})

// 表单校验
const rules = {
  brigadeId: [{ required: true, message: '大队不能为空', trigger: 'change' }],
  areaId: [{ required: true, message: '区域不能为空', trigger: 'change' }],
  reviewedUserId: [{ required: true, message: '被回查人不能为空', trigger: 'change' }],
  reviewDate: [{ required: true, message: '回查日期不能为空', trigger: 'change' }],
  missCheckTime: [{ required: true, message: '漏检时间不能为空', trigger: 'change' }],
  missCheckTimePeriod: [{ required: true, message: '漏检时间段不能为空', trigger: 'change' }],
  channelId: [{ required: true, message: '上岗位置不能为空', trigger: 'change' }],
  missCheckItem: [{ required: true, message: '漏检物品不能为空', trigger: 'change' }],
  supervisorId: [{ required: true, message: '分管主管不能为空', trigger: 'change' }],
  teamLeaderId: [{ required: true, message: '分管班组长不能为空', trigger: 'change' }],
  itemLocation: [{ required: true, message: '物品位置不能为空', trigger: 'change' }],
  difficultyLevel: [{ required: true, message: '简单/难不能为空', trigger: 'change' }],
  reviewUserId: [{ required: true, message: '回查人不能为空', trigger: 'change' }],
  discriminationType: [{ required: true, message: '判别类型不能为空', trigger: 'change' }],
  isRecovered: [{ required: true, message: '是否追回不能为空', trigger: 'change' }],
  machineOperatingYears: [{ required: true, message: '开机年限不能为空', trigger: 'change' }],
  certificateLevel: [{ required: true, message: '证书级别不能为空', trigger: 'change' }],
  gender: [{ required: true, message: '人员性别不能为空', trigger: 'change' }],
  missCheckReasonCategory: [{ required: true, message: '漏检原因分类不能为空', trigger: 'change' }],
  monthlyAssessment: [{ required: true, message: '月考成绩不能为空', trigger: 'change' }],
  selfTestHasMissCheck: [
    { required: true, message: '本月自测有无漏检不能为空', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('本月自测有无漏检不能为空'))
        } else if (![0, 1, 2].includes(Number(value))) {
          callback(new Error('本月自测有无漏检只能输入0、1、2'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
  // actingSupervisorId 不设置必填校验
}

// 字典数据
const { discrimination_type, blocked_time_period, blocked_item_position, blocked_monthly_exam_result, blocked_operating_years, blocked_miss_check_reason } = useDict('discrimination_type', 'blocked_time_period', 'blocked_item_position', 'blocked_monthly_exam_result', 'blocked_operating_years', 'blocked_miss_check_reason')

// 大队选项
const brigadeOptions = ref([])
// 人员选项
const personOptions = ref([])
// 班组长选项
const teamLeaderOptions = ref([])
// 主管选项
const supervisorOptions = ref([])
// 区域选项
const areaOptions = ref([])
// 上岗位置选项
const channelOptions = ref([])

/** 获取职位列表 */
function getPositionList() {
  // 获取区域选项
  listPosition({ positionType: 'REGIONAL' }).then(response => {
    areaOptions.value = response.data || []
  })

  // 获取上岗位置选项
  listPosition({ positionType: 'TERMINL' }).then(response => {
    channelOptions.value = response.data || []
  })
}

/** 查询漏检列表 */
function getList() {
  loading.value = true
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.reviewDateStart = dateRange.value[0]
    queryParams.reviewDateEnd = dateRange.value[1]
  } else {
    queryParams.reviewDateStart = null
    queryParams.reviewDateEnd = null
  }
  listMissedInspection(queryParams).then(response => {
    missedInspectionList.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 getMissCheckItemOptions() {
  listCategory().then(response => {
    missCheckItemOptions.value = proxy.handleTree(response.data, "id", "parentId")
  })
}
function getTeamLeaderOptions() {
  selectUserLeaderListByCondition({ roleKeyList: ['banzuzhang'] }).then(response => {
    teamLeaderOptions.value = (response.data || []).map(item => ({
      value: item.userId,
      label: item.nickName
    }))
  })
}

/** 获取主管选项 */
function getSupervisorOptions() {
  selectUserLeaderListByCondition({ roleKeyList: ['kezhang'] }).then(response => {
    supervisorOptions.value = (response.data || []).map(item => ({
      value: item.userId,
      label: item.nickName
    }))
  })
}

/** 被回查人变更事件 */
function handleReviewedUserChange(userId) {
  if (userId) {
    //请求回查人班组长
    selectUserLeaderListByCondition({ userId: userId, roleKeyList: ['banzuzhang'] }).then(response => {
      if (response.data && response.data.length > 0) {
        const data = response.data[0]
        form.teamLeaderId = data.userId
      }
    })
    selectUserLeaderListByCondition({ userId: userId, roleKeyList: ['kezhang'] }).then(response => {
      if (response.data && response.data.length > 0) {
        const data = response.data[0]
        form.supervisorId = data.userId
      }
    })
  } else {
    form.supervisorId = null
    form.teamLeaderId = null
    form.certificateLevel = null
    form.gender = null
  }
}

/** 获取用户列表 */
function getUserList() {
  listUser({ pageNum: 1, pageSize: 1000 }).then(response => {
    personOptions.value = response.rows.map(item => ({
      value: item.userId,
      label: item.nickName
    }))
  })
}

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

// 表单重置
function reset() {
  Object.assign(form, {
    id: null,
    brigadeId: null,
    areaId: null,
    areaName: null,
    reviewedUserId: null,
    reviewDate: null,
    missCheckTime: null,
    missCheckTimePeriod: null,
    channelId: null,
    channelName: null,
    supervisorId: null,
    actingSupervisorId: null,
    teamLeaderId: null,
    itemLocation: null,
    difficultyLevel: null,
    reviewUserId: null,
    discriminationType: null,
    isRecovered: null,
    machineOperatingYears: null,
    certificateLevel: null,
    gender: null,
    missCheckReasonCategory: null,
    monthlyAssessment: null,
    selfTestHasMissCheck: null,
    missCheckItem: null
  })
  proxy.resetForm('missedInspectionRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  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.missCheckTime = new Date().toISOString().replace('T', ' ').substring(0, 16)
  // 设置默认当前日期
  form.reviewDate = new Date().toISOString().split('T')[0]
  open.value = true
  title.value = '添加漏检'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value[0]
  getMissedInspection(id).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = '修改漏检'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.missedInspectionRef.validate(valid => {
    if (valid) {
      // 处理大队ID和名称映射
      if (form.brigadeId) {
        const brigade = brigadeOptions.value.find(item => item.value === form.brigadeId)
        form.brigadeName = brigade ? brigade.label : null
      }

      // 处理区域ID和名称映射
      if (form.areaId) {
        
        const area = areaOptions.value.find(item => item.id === form.areaId)
        form.areaName = area ? area.name : null
      }

      // 处理被回查人ID和名称映射
      if (form.reviewedUserId) {
        const reviewedUser = personOptions.value.find(item => item.value === form.reviewedUserId)
        form.reviewedUserName = reviewedUser ? reviewedUser.label : null
      }

      // 处理上岗位置ID和名称映射
      if (form.channelId) {
        const channel = channelOptions.value.find(item => item.id === form.channelId)
        form.channelName = channel ? channel.name : null
      }

      // 处理分管主管ID和名称映射
      if (form.supervisorId) {
        const supervisor = supervisorOptions.value.find(item => item.value === form.supervisorId)
        form.supervisorName = supervisor ? supervisor.label : null
      }

      // 处理代管主管ID和名称映射
      if (form.actingSupervisorId) {
        
        const actingSupervisor = supervisorOptions.value.find(item => item.value === form.actingSupervisorId)
        form.actingSupervisorName = actingSupervisor ? actingSupervisor.label : null
      }

      // 处理分管班组长ID和名称映射
      if (form.teamLeaderId) {
        const teamLeader = teamLeaderOptions.value.find(item => item.value === form.teamLeaderId)
        form.teamLeaderName = teamLeader ? teamLeader.label : null
      }

      // 处理回查人ID和名称映射
      if (form.reviewUserId) {
        const reviewUser = personOptions.value.find(item => item.value === form.reviewUserId)
        form.reviewUserName = reviewUser ? reviewUser.label : null
      }

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

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/blocked/missReview/export', {
    ...queryParams
  }, `漏检_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  upload.open = true
}

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

  getPositionList()
  getTeamLeaderOptions()
  getSupervisorOptions()
  getMissCheckItemOptions()
})
</script>

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