<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型">
          <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.typeName" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
      </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-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:device:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workOrderList" @selection-change="handleSelectionChange">
      <el-table-column label="维修单编号" align="center" prop="id" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="设备编码" align="center" prop="deviceNo" />
      <el-table-column label="巡检人" align="center" prop="inspectionUserName">
        <template slot-scope="scope">
          <span>{{ scope.row.inspectionUserName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备故障描述" align="center" prop="deviceErrorDetail" />
      <el-table-column label="故障日期" align="center" prop="erroDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.erroDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修状态" align="center" prop="orderStates">
        <template slot-scope="scope">
          <span>{{ selectDictLabels(orderStatesList, scope.row.orderStates) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修人" align="center" prop="maintainUserName">
        <template slot-scope="scope">
          <span>{{ scope.row.maintainUserName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修情况描述" align="center" prop="maintainDetail">
        <template slot-scope="scope">
          <span>{{ scope.row.maintainDetail || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修日期" align="center" prop="maintainDate" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.maintainDate ? parseTime(scope.row.maintainDate, '{y}-{m}-{d}') : '-' }}</span>
        </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"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workOrder:workOrder:edit']"
            v-if="scope.row.orderStates == 0"
            >派单</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['workOrder:workOrder:view']"
            v-if="false"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加工单派遣对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" @change="getDeviceName">
            <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.typeName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-select v-model="form._deviceName" placeholder="请选择设备名称" value-key="id" @change="getDeviceNo">
            <el-option v-for="item in deviceNameList" :key="item.id" :label="item.deviceName" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备编码" prop="deviceNo">
          <el-input v-model="form.deviceNo" disabled placeholder="自动获取设备编号" />
        </el-form-item>

        <el-form-item label="设备故障描述" prop="deviceErrorDetail">
          <el-input v-model="form.deviceErrorDetail" placeholder="请输入设备故障描述" />
        </el-form-item>
        <el-form-item label="设备故障图片" prop="deviceErrorPhotos">
          <FileUploadInspec
            :value="form.deviceErrorPhotos"
            @input="fileSuccess"
            @handleRemove="handleRemove"
            :fileType="['jpg', 'jpeg', 'png']"
          />
        </el-form-item>
        <el-form-item label="故障日期" prop="erroDate">
          <el-date-picker
            clearable
            v-model="form.erroDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择故障日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="维修截止日期" prop="maintainEndDate">
          <el-date-picker
            clearable
            v-model="form.maintainEndDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择维修截止日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="部门名称" prop="maintainDeptId">
          <treeselect
            v-model="form.maintainDeptId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择部门名称"
            @select="deptSelect"
          />
        </el-form-item>
        <el-form-item label="维修负责人" prop="maintainUserId">
          <el-select v-model="form.maintainUserId" placeholder="请选择维修负责人">
            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId">
            </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 { listWorkOrder, getWorkOrder, addWorkOrder, updateWorkOrder } from '@/api/repair/repairProject'
import { listDevice as listDeviceType } from '@/api/device/deviceType'
import { listDevice as listDeviceName, getDevice } from '@/api/device/device'
import { listUser } from '@/api/system/user'
import { listDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import FileUploadInspec from '@/components/FileUploadInspec'
export default {
  name: 'WorkOrder',
  components: { Treeselect, FileUploadInspec },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单派遣表格数据
      workOrderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,

      // 维修状态
      orderStatesList: [
        { label: '派单中', value: 0 },
        { label: '维修中', value: 1 },
        { label: '已完成', value: 2 },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        repairsId: null,
        deviceId: null,
        deviceNo: null,
        deviceName: null,
        inspectionUserId: null,
        deviceErrorDetail: null,
        deviceErrorPhotos: null,
        erroDate: null,
        orderStates: null,
        maintainUserId: null,
        maintainDetail: null,
        maintainEndDate: null,
        maintainDate: null,
        deviceType: null,
      },
      queryParamsUser: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      deviceTypeList: [],
      deviceNameList: [],
      deptOptions: [],
      userList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        repairsId: [{ required: true, message: '维修单编号不能为空', trigger: 'blur' }],
        deviceErrorPhotos: [{ required: true, message: '设备故障图片不能为空', trigger: 'blur' }],
        deviceErrorDetail: [{ required: true, message: '设备故障描述不能为空', trigger: 'blur' }],
        erroDate: [{ required: true, message: '故障日期不能为空', trigger: 'blur' }],
        maintainEndDate: [{ required: true, message: '维修截止日期不能为空', trigger: 'blur' }],
        maintainDeptId: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
        maintainUserId: [{ required: true, message: '维修负责人不能为空', trigger: 'blur' }],
        deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'blur' }],
        deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getList()
    listDeviceType().then(response => {
      this.deviceTypeList = response.rows
    })
  },
  computed: {
    // 获取当前登录用户ID
    getUserId() {
      return this.$store.state.user.id
    },
  },
  methods: {
    /** 查询工单派遣列表 */
    getList() {
      this.loading = true
      listWorkOrder(this.queryParams).then(response => {
        this.workOrderList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 处理分页事件 */
    handlePagination(data) {
      this.queryParams.pageNum = data.page
      this.queryParams.pageSize = data.limit
      this.getList()
    },
    // 设备名称
    getDeviceName(val) {
      this.form._deviceName = null
      this.getDeviceTypeDept(val)
      listDeviceName({ deviceType: val }).then(response => {
        this.deviceNameList = response.rows
      })
      this.form.deviceName = null
      this.form.deviceNo = null
      this.form.maintainDeptId = null
    },
    // 根据设备类型id获取部门列表
    getDeviceTypeDept(val) {
      // 清空部门
      this.deptOptions = []
      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)
          })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        repairsId: null,
        deviceId: null,
        deviceNo: null,
        deviceName: null,
        inspectionUserId: null,
        deviceErrorDetail: null,
        deviceErrorPhotos: null,
        erroDate: null,
        orderStates: null,
        maintainUserId: null,
        maintainDetail: null,
        maintainEndDate: null,
        maintainDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: 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) {
      // 判断如果没有maintainUserId，则使用当前登录用户的ID
      if (!row.maintainUserId) {
        row.maintainUserId = this.getUserId
      }
      updateWorkOrder(row).then(response => {
        this.$modal.msgSuccess('派单成功')
        this.getList()
      })
    },

    // 查看
    handleView(row) {
      const id = row.id || this.ids
      // listDept().then((response) => {
      //   this.deptOptions = this.handleTree(response.data, 'deptId')
      // })
      getWorkOrder(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '查看'
        console.log(this.form)
      })
    },
    /** 转换部门数据结构 */
    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.maintainUserId = null
      this.getUserList()
    },
    /** 查询用户列表 */
    getUserList() {
      listUser(this.addDateRange(this.queryParamsUser)).then(response => {
        this.userList = response.rows
      })
    },
    getDeviceNo(val) {
      this.form._deviceName = val
      this.form.deviceName = val.deviceName
      this.form.deviceNo = val.deviceNo
      this.form.deviceId = val.id
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form._deviceName) {
            delete this.form._deviceName
          }
          addWorkOrder(this.form).then(response => {
            this.$modal.msgSuccess('新增成功')
            this.open = false
            this.getList()
          })
        }
      })
    },

    // 文件上传回调
    fileSuccess(val) {
      this.form.deviceErrorPhotos = val
    },
    // 文件删除
    handleRemove(url) {
      this.form.deviceErrorPhotos = url
    },
  },
}
</script>
