<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="巡检时间" prop="inspectionTime">
        <el-input
          v-model="queryParams.inspectionTime"
          placeholder="请输入巡检时间"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="巡检对象" prop="inspectionObject">
        <el-input
          v-model="queryParams.inspectionObject"
          placeholder="地点/设备编号/Id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="巡检人" prop="responsiblePerson">
        <el-input
          v-model="queryParams.responsiblePerson"
          placeholder="请输入巡检人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:allocation:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:allocation:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:allocation:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="allocationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="巡检时间" align="center" prop="inspectionTime">
        <template slot-scope="scope">
          <div>
            每{{ scope.row.inspectionTimeInterval }}/{{
              scope.row.inspectionTimeUnit == 'time' ? '小时' : '天'
            }}进行巡检
          </div>
          <div
            v-if="scope.row.inspectionTimeUnit == 'time' && scope.row.inspectionTimePeriod"
            style="font-size: 12px; color: #999"
          >
            时间段：{{ scope.row.inspectionTimePeriod }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="巡检对象" align="center" prop="inspectionObjectName" />
      <el-table-column label="类型区分地点和设备(0地点1设备)" align="center" prop="inspectionType">
        <template slot-scope="scope">
          {{ scope.row.inspectionType == 0 ? '地点' : '设备' }}
        </template>
      </el-table-column>
      <el-table-column label="巡检人" align="center" prop="responsiblePersonName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :type="scope.row.status == 0 ? '开启' : '关闭'"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:allocation:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:allocation:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="巡检时间" prop="inspectionTimeInterval">
          <div class="yihang" style="display: flex; align-items: center">
            每<el-input type="number" v-model="form.inspectionTimeInterval" size="mini" style="width: 80px" />
            /
            <el-select v-model="form.inspectionTimeUnit" placeholder="选择天/小时" size="mini">
              <el-option label="小时" value="time"></el-option>
              <el-option label="天" value="day"></el-option> </el-select
            >进行巡检
          </div>
        </el-form-item>
        <el-form-item label="时间段" prop="inspectionTimePeriod" v-if="form.inspectionTimeUnit === 'time'">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-select v-model="timePeriodStart" placeholder="开始时间" size="mini" style="width: 120px">
              <el-option
                v-for="hour in hourOptions"
                :key="hour.value"
                :label="hour.label"
                :value="hour.value"
              ></el-option>
            </el-select>
            <span>到</span>
            <el-select v-model="timePeriodEnd" placeholder="结束时间" size="mini" style="width: 120px">
              <el-option
                v-for="hour in hourOptions"
                :key="hour.value"
                :label="hour.label"
                :value="hour.value"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="巡检类型" prop="inspectionType">
          <el-radio-group v-model="form.inspectionType" @change="handleChange" size="mini">
            <el-radio label="0">地点</el-radio>
            <el-radio label="1">设备</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType" v-if="form.inspectionType === '1'">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" clearable @change="getDeviceListByType">
            <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptId">
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择部门名称"
            @select="deptSelect"
          />
        </el-form-item>
        <el-form-item label="巡检对象" prop="inspectionObjectName">
          <el-select v-model="form.inspectionObject" placeholder="" size="mini">
            <el-option v-for="item in optionList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="巡检人" prop="responsiblePerson">
          <el-select v-model="form.responsiblePerson" filterable multiple placeholder="">
            <el-option
              v-for="item in perpOptionList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllocation,
  listAllocation,
  addAllocation,
  updateAllocation,
  delAllocation,
  getDeviceInfo,
  getAllPerson,
} from '@/api/patrol/dailyinspection.js'
import { listLog } from '@/api/patrol/patrolLocation'
import { listDept } from '@/api/system/dept'
import { listUser } from '@/api/system/user'
import { listDevice as deviceTypeList } from '@/api/device/deviceType'
import { listDevice } from '@/api/device/device'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Allocation',
  components: {
    Treeselect,
  },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      allocationList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inspectionTime: null,
        inspectionObject: null,
        inspectionType: null,
        responsiblePerson: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: '主键Id不能为空', trigger: 'blur' }],
        inspectionTime: [{ required: true, message: '巡检时间不能为空', trigger: 'blur' }],
        inspectionObject: [
          {
            required: true,
            message: '巡检对象包括地点和设备编号或Id不能为空',
            trigger: 'blur',
          },
        ],
        inspectionType: [
          {
            required: true,
            message: '类型区分地点和设备(0地点1设备)不能为空',
            trigger: 'change',
          },
        ],
        responsiblePerson: [{ required: true, message: '巡检人不能为空', trigger: 'blur' }],
        status: [
          {
            required: true,
            message: '状态(开启0关闭1)不能为空',
            trigger: 'blur',
          },
        ],
      },
      //巡检地点list
      locationList: [],
      deviceList: [],
      optionList: [],
      perpOptionList: [],
      // 时间段选择器的值
      timePeriodStart: null,
      timePeriodEnd: null,
      // 部门选项
      deptOptions: [],
      // 用户查询参数
      queryParamsUser: {
        pageNum: 1,
        pageSize: 100,
        deptId: null,
      },
      // 用户列表
      userList: [],
      // 设备类型列表
      deviceTypeList: [],
      // 小时选项列表（0-23点）
      hourOptions: [
        { label: '00:00', value: '00:00' },
        { label: '01:00', value: '01:00' },
        { label: '02:00', value: '02:00' },
        { label: '03:00', value: '03:00' },
        { label: '04:00', value: '04:00' },
        { label: '05:00', value: '05:00' },
        { label: '06:00', value: '06:00' },
        { label: '07:00', value: '07:00' },
        { label: '08:00', value: '08:00' },
        { label: '09:00', value: '09:00' },
        { label: '10:00', value: '10:00' },
        { label: '11:00', value: '11:00' },
        { label: '12:00', value: '12:00' },
        { label: '13:00', value: '13:00' },
        { label: '14:00', value: '14:00' },
        { label: '15:00', value: '15:00' },
        { label: '16:00', value: '16:00' },
        { label: '17:00', value: '17:00' },
        { label: '18:00', value: '18:00' },
        { label: '19:00', value: '19:00' },
        { label: '20:00', value: '20:00' },
        { label: '21:00', value: '21:00' },
        { label: '22:00', value: '22:00' },
        { label: '23:00', value: '23:00' },
      ],
    }
  },
  created() {
    this.getList()
    this.getDeviceTypeList()
    // 初始化时先加载所有地点和设备，用于默认选项
    this.getLocationByDept(null)
    getDeviceInfo().then(response => {
      this.deviceList = response.rows.map(item => {
        return {
          label: item.deviceName,
          value: item.id,
        }
      })
    })
    this.getAllPersonList()
  },
  methods: {
    /** 查询设备类型列表 */
    getDeviceTypeList() {
      deviceTypeList().then(response => {
        this.deviceTypeList = response.rows
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 根据设备类型查询部门和设备列表 */
    getDeviceListByType(val, isUpdate = false) {
      if (!isUpdate) {
        // 非修改模式时清空部门和相关选择
        this.deptOptions = []
        this.form.deptId = null
        this.form.inspectionObject = null
        this.form.responsiblePerson = []
      }

      if (!val) return

      const typeDeptIds = this.deviceTypeList.find(item => item.id === val)?.typeDeptIds
      // 如果有关联的部门ID，则进行查询
      if (typeDeptIds && typeDeptIds.length > 0) {
        // 创建所有 listDept 请求的 Promise 数组
        const deptPromises = typeDeptIds.map(deptId =>
          listDept({ deptId: deptId })
            .then(response => {
              // 处理并返回数据
              return this.handleTree(response.data, 'deptId')
            })
            .catch(error => {
              return [] // 返回空数组，避免 Promise.all 失败
            })
        )
        // 等待所有请求完成
        Promise.all(deptPromises)
          .then(deptData => {
            this.deptOptions = deptData.flat()
          })
          .catch(error => {
            console.error('获取部门数据失败:', error)
          })
      }

      // 根据设备类型查询设备列表
      listDevice({
        deviceType: val,
      }).then(response => {
        this.deviceList = response.rows.map(item => {
          return {
            label: item.deviceName,
            value: item.id,
          }
        })
        if (this.form.inspectionType == 1) {
          this.optionList = this.deviceList
        }
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      }
    },
    /** 部门选择事件 */
    deptSelect(val) {
      this.queryParamsUser.deptId = val.deptId
      this.form.responsiblePerson = []
      this.form.inspectionObject = null
      this.getUserList()

      // 根据巡检类型和部门获取对应的数据
      if (this.form.inspectionType == 0) {
        // 地点类型，根据部门获取地点
        this.getLocationByDept(val.deptId)
      }
    },
    /** 查询用户列表 */
    getUserList() {
      listUser(this.addDateRange(this.queryParamsUser)).then(response => {
        this.perpOptionList = response.rows.map(item => {
          return {
            label: item.nickName,
            value: item.userId,
          }
        })
      })
    },
    /** 获取全部巡检人 */
    getAllPersonList() {
      getAllPerson().then(response => {
        this.perpOptionList = response.rows.map(item => {
          return {
            label: item.nickName,
            value: item.userId,
          }
        })
      })
    },
    /** 根据部门获取地点 */
    getLocationByDept(deptId) {
      if (deptId) {
        listLog({ deptId: deptId }).then(response => {
          this.locationList = response.rows.map(item => {
            return {
              label: item.placeName,
              value: item.id,
            }
          })
          if (this.form.inspectionType == 0) {
            this.optionList = this.locationList
          }
        })
      } else {
        // 如果没有部门ID，获取所有地点
        listLog().then(response => {
          this.locationList = response.rows.map(item => {
            return {
              label: item.placeName,
              value: item.id,
            }
          })
          if (this.form.inspectionType == 0) {
            this.optionList = this.locationList
          }
        })
      }
    },
    /** 根据部门获取设备 */
    getDeviceByDept(deptId) {
      if (deptId) {
        getDeviceInfo({ deptId: deptId }).then(response => {
          this.deviceList = response.rows.map(item => {
            return {
              label: item.deviceName,
              value: item.id,
            }
          })
          if (this.form.inspectionType == 1) {
            this.optionList = this.deviceList
          }
        })
      } else {
        // 如果没有部门ID，获取所有设备
        getDeviceInfo().then(response => {
          this.deviceList = response.rows.map(item => {
            return {
              label: item.deviceName,
              value: item.id,
            }
          })
          if (this.form.inspectionType == 1) {
            this.optionList = this.deviceList
          }
        })
      }
    },
    //日常巡检任务开关
    handleStatusChange(row) {
      updateAllocation(row).then(response => {
        this.$modal.msgSuccess('修改成功')
        this.getList()
      })
    },

    // 切换巡检类型
    handleChange() {
      this.form.inspectionObject = null
      this.form.deviceType = null
      this.form.deptId = null
      this.form.responsiblePerson = []
      this.deptOptions = []
      this.queryParamsUser.deptId = null

      if (this.form.inspectionType == 0) {
        // 地点类型，显示所有部门和地点
        this.getDeptTree() // 获取所有部门
        this.getAllPersonList() // 获取全部巡检人
        this.getLocationByDept(null) // 获取所有地点
      } else {
        // 设备类型，部门选项会在选择设备类型后获取
        this.optionList = []
        this.perpOptionList = []
      }
    },

    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listAllocation(this.queryParams).then(response => {
        this.allocationList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inspectionTime: null,
        inspectionObject: null,
        inspectionType: null,
        responsiblePerson: null,
        status: '0',
        inspectionTimePeriod: null,
        deptId: null,
        deviceType: null,
      }
      this.timePeriodStart = null
      this.timePeriodEnd = null
      this.queryParamsUser.deptId = null
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加日常巡检'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAllocation(id).then(response => {
        this.form = response.data
        this.form.responsiblePerson = this.form.responsiblePersonArray.map(item => Number(item))
        this.form.inspectionObject = Number(this.form.inspectionObject)

        // 确保设备类型字段正确赋值
        if (this.form.deviceType) {
          this.form.deviceType = Number(this.form.deviceType)
        }

        // 确保部门ID正确赋值
        if (this.form.deptId) {
          this.form.deptId = Number(this.form.deptId)
        }

        // 处理时间段数据回显
        if (this.form.inspectionTimePeriod && this.form.inspectionTimePeriod.includes('-')) {
          const timePeriod = this.form.inspectionTimePeriod.split('-')
          this.timePeriodStart = timePeriod[0]
          this.timePeriodEnd = timePeriod[1]
        }

        // 根据巡检类型加载对应的数据
        if (this.form.inspectionType == 1) {
          // 设备类型
          if (this.form.deviceType) {
            // 先加载设备类型对应的部门列表，传入true表示是修改模式，不清空数据
            this.getDeviceListByType(this.form.deviceType, true)
            // 延迟处理其他数据，确保部门列表已加载
            setTimeout(() => {
              if (this.form.deptId) {
                this.queryParamsUser.deptId = this.form.deptId
                this.getUserList()
                this.getDeviceByDept(this.form.deptId)
              }
            }, 800) // 增加延迟时间确保数据加载完成
          } else {
            // 没有设备类型时，获取全部设备
            this.optionList = this.deviceList
            this.getAllPersonList()
          }
        } else {
          // 地点类型
          this.getDeptTree()
          // 延迟处理，确保部门树加载完成
          setTimeout(() => {
            if (this.form.deptId) {
              this.queryParamsUser.deptId = this.form.deptId
              this.getUserList()
              this.getLocationByDept(this.form.deptId)
            } else {
              this.getLocationByDept(null)
              this.getAllPersonList()
            }
          }, 500)
        }

        this.open = true
        this.title = '修改日常巡检'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 处理时间段数据
          if (this.form.inspectionTimeUnit === 'time' && this.timePeriodStart && this.timePeriodEnd) {
            this.form.inspectionTimePeriod = `${this.timePeriodStart}-${this.timePeriodEnd}`
          } else {
            this.form.inspectionTimePeriod = null
          }

          if (this.form.id != null) {
            updateAllocation(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addAllocation(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAllocation(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'business/allocation/export',
        {
          ...this.queryParams,
        },
        `allocation_${new Date().getTime()}.xlsx`
      )
    },
  },
}
</script>
<style scoped>
.yihang {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
