<template>
  <view class="form-container">
    <!-- 表单标题 -->
    <view class="form-title">
      <text class="title-text">设备申请表</text>
      <view class="title-line"></view>
    </view>
    <!-- 表单内容 -->
    <uni-forms ref="form" :modelValue="form" :rules="rules" label-position="top" label-width="150" class="custom-form">
      <flow-note :taskForm="taskForm"></flow-note>
      <!-- 当前节点 -->
      <uni-forms-item label="当前节点" class="form-item" v-if="taskName">
        <uni-tag :inverted="true" type="primary" :text="taskName"></uni-tag>
      </uni-forms-item>

      <!-- 流程发起人 -->
      <uni-forms-item label="填报人" class="form-item">
        <b style="font-size:30rpx;">{{ applierUserName }}</b>
      </uni-forms-item>

      <!-- 填报日期 -->
      <uni-forms-item label="填报日期" class="form-item">
        <text>{{ form.applyDate }}</text>
      </uni-forms-item>

      <!-- 选择项目 -->
      <uni-forms-item label="选择项目" required class="form-item" name="projectId">
        <uv-button type="primary" @click="openProject = true" v-if="taskName == '设备申请'">+ 选择项目</uv-button>
        <ProjectPicker :visible.sync="openProject" :selected.sync="selectedProject" @confirm="handleConfirm" />
        <ProjectInfo :project="projectObj"></ProjectInfo>
      </uni-forms-item>

      <!-- 设备选择 -->
      <uni-forms-item label="申请设备" required class="form-item" name="devices"
        v-if="taskName != '安排设备' && taskName != '归还确认'">
        <uv-button type="primary" @click="openDevice = true" v-if="taskName == '设备申请'">+ 选择设备</uv-button>
        <device-picker :visible.sync="openDevice" :selected.sync="selectDevice" :multiple="!isReplaceMode"
          @confirm="handleDeviceConfirm"></device-picker>
        <view class="device-cards" v-if="deviceList.length > 0">
          <view class="device-card" v-for="(item, index) in deviceList" :key="index">
            <view class="card-header">
              <text class="card-title">{{ index + 1 }}. 出厂编号：{{ item.code }}</text>
            </view>
            <view class="card-content">
              <view class="card-row">
                <view class="card-item">
                  <text class="label">设备名称：</text>
                  <text class="value">{{ item.name }}</text>
                </view>
              </view>
              <view class="card-row">
                <view class="card-item">
                  <text class="label">设备品牌：</text>
                  <text class="value">{{ item.brand }}</text>
                </view>
                <view class="card-item">
                  <text class="label">存放地址：</text>
                  <text class="value">{{ item.place }}</text>
                </view>
              </view>
              <view class="card-row">
                <view class="card-item">
                  <text class="label">规格型号：</text>
                  <text class="value">{{ item.series }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </uni-forms-item>

      <!-- 申领事由 -->
      <uni-forms-item label="申领事由" required class="form-item" name="applyReason">
        <uv-textarea v-model="form.applyReason" placeholder="请输入申领事由" :disabled="taskName != '设备申请'"></uv-textarea>
      </uni-forms-item>

      <!-- 日期选择 -->
      <view class="date-range">
        <uni-forms-item label="使用日期" required class="form-item" name="dateRange">
          <uni-datetime-picker v-model="form.dateRange" type="daterange" rangeSeparator="至" :clearIcon="false"
            v-if="taskName == '设备申请'" @change="handleDateRangeChange" />
          <view class="date-display" v-else>
            <uni-icons type="calendar" size="16"></uni-icons>
            <text class="date-text">{{ form.beginDate }}</text>
            <text class="date-separator">至</text>
            <text class="date-text">{{ form.endDate }}</text>
          </view>
        </uni-forms-item>
        <uni-forms-item label="共计" class="form-item">
          <text>{{ form.days + '天' }}</text>
        </uni-forms-item>
      </view>

      <!-- 安排设备意见 -->
      <uni-forms-item label="拟发放设备" required class="form-item" v-if="taskName != '设备申请' && taskName != '归还确认'">
        <view class="device-cards" v-if="modifyDeviceList.length > 0">
          <view class="device-card" v-for="(item, index) in modifyDeviceList" :key="index">
            <view class="card-header">
              <text class="card-title">{{ index + 1 }}. 出厂编号：{{ item.code }}</text>
            </view>
            <view class="card-content">
              <view class="card-row">
                <view class="card-item">
                  <text class="label">设备名称：</text>
                  <text class="value">{{ item.name }}</text>
                </view>
              </view>
              <view class="card-row">
                <view class="card-item">
                  <text class="label">设备品牌：</text>
                  <text class="value">{{ item.brand }}</text>
                </view>
                <view class="card-item">
                  <text class="label">存放地址：</text>
                  <text class="value">{{ item.place }}</text>
                </view>
              </view>
              <view class="card-row">
                <view class="card-item">
                  <text class="label">规格型号：</text>
                  <text class="value">{{ item.series }}</text>
                </view>
              </view>
            </view>
            <view class="card-actions" v-if="taskName == '安排设备'">
              <uv-button type="primary" size="mini" @click="replaceRowData(item, index)">重新选择</uv-button>
              <uv-button type="error" size="mini" @click="deleteRowData(item, index)">删除</uv-button>
            </view>
          </view>
        </view>
        <uv-button type="primary" @click="addRowdata()" v-if="taskName == '安排设备'">新增设备</uv-button>
      </uni-forms-item>

      <!-- 安排设备意见 -->
      <uni-forms-item label="安排设备意见" required class="form-item" name="dispatchComment" v-if="taskName != '设备申请'">
        <uv-textarea v-model="form.dispatchComment" placeholder="请输入安排设备意见"
          :disabled="taskName != '安排设备'"></uv-textarea>
        <auditor :name="form.dispatcher ? form.dispatchUser.nickName : ''" :time="form.dispatchTime"></auditor>
      </uni-forms-item>

      <!-- 分管审核意见 -->
      <uni-forms-item label="分管审核意见" required name="managerComment" class="form-item"
        v-if="taskName != '设备申请' && taskName != '安排设备'">
        <uv-textarea v-model="form.managerComment" placeholder="请输入分管审核意见" :disabled="taskName != '分管审核'"></uv-textarea>
        <auditor :name="form.managerUser ? form.managerUser.nickName : ''" :time="form.managerTime"></auditor>
      </uni-forms-item>

      <!-- 归还确认 -->
      <uni-forms-item label="已归还设备" required class="form-item" v-if="taskName == '' || taskName == '归还确认'">
        <text style="color: #a69494;" v-if="taskName == '归还确认'">Tips：请点击卡片，切换归还状态</text>
        <view class="device-cards" v-if="returnDevicesList.length > 0">
          <view class="device-card" v-for="(item, index) in returnDevicesList" :key="index"
            :class="{ 'selected': isDeviceSelected(item.deviceId) }" @click="toggleDeviceSelection(item)">
            <view class="card-header">
              <text class="card-title">{{ index + 1 }}. 出厂编号：{{ item.code }}</text>
              <view class="return-tag" v-if="isDeviceSelected(item.deviceId)">
                <uni-tag type="success" text="已归还" size="small"></uni-tag>
              </view>
            </view>
            <view class="card-content">
              <view class="card-row">
                <view class="card-item">
                  <text class="label">设备名称：</text>
                  <text class="value">{{ item.name }}</text>
                </view>
              </view>
              <view class="card-row">
                <view class="card-item">
                  <text class="label">设备品牌：</text>
                  <text class="value">{{ item.brand }}</text>
                </view>
                <view class="card-item">
                  <text class="label">存放地址：</text>
                  <text class="value">{{ item.place }}</text>
                </view>
              </view>
              <view class="card-row">
                <view class="card-item">
                  <text class="label">规格型号：</text>
                  <text class="value">{{ item.series }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </uni-forms-item>

      <!-- 需维修设备 -->
      <uni-forms-item label="需维修设备" class="form-item" v-if="taskName == '' || taskName == '归还确认'">
        <uv-button type="primary" @click="openRepairDevice = true" v-if="taskName == '归还确认'">+ 选择需维修设备</uv-button>
        <repair-device-picker :visible.sync="openRepairDevice" :deviceList="modifyDeviceList"
          :selectedDevices.sync="form.repairDevices"></repair-device-picker>
        <view class="device-cards" v-if="repairDevicesList.length > 0">
          <view class="device-card repair-card" v-for="(item, index) in repairDevicesList" :key="index">
            <view class="card-header">
              <text class="card-title">{{ index + 1 }}. 出厂编号：{{ item.code }}</text>
              <view class="repair-tag">
                <uni-tag type="error" text="需维修" size="small"></uni-tag>
              </view>
            </view>
            <view class="card-content">
              <view class="card-row">
                <view class="card-item">
                  <text class="label">设备名称：</text>
                  <text class="value">{{ item.name }}</text>
                </view>
              </view>
              <view class="card-row">
                <view class="card-item">
                  <text class="label">设备品牌：</text>
                  <text class="value">{{ item.brand }}</text>
                </view>
                <view class="card-item">
                  <text class="label">存放地址：</text>
                  <text class="value">{{ item.place }}</text>
                </view>
              </view>
              <view class="card-row">
                <view class="card-item">
                  <text class="label">规格型号：</text>
                  <text class="value">{{ item.series }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-else>
          <uni-tag type="success" text="没有需维修的设备" size="small"></uni-tag>
        </view>
      </uni-forms-item>

      <!-- 备注 -->
      <uni-forms-item label="备注" class="form-item" v-if="taskName == '' || taskName == '归还确认'">
        <uv-textarea v-model="form.remark" placeholder="请输入备注" :disabled="taskName != '归还确认'"></uv-textarea>
      </uni-forms-item>

      <!-- 归还日期 -->
      <uni-forms-item label="归还日期" required name="returnDate" class="form-item"
        v-if="taskName == '' || taskName == '归还确认'">
        <uni-datetime-picker v-model="form.returnDate" type="date" :disabled="taskName != '归还确认'" />
      </uni-forms-item>

      <!-- 操作按钮 -->
      <view class="form-actions" v-if="taskName">
        <uv-button type="primary" @click="submit" v-if="taskName == '设备申请'">提交申请</uv-button>
        <template v-else>
          <uv-button style="margin-bottom: 5px;" type="warning" @click="saves">保存</uv-button>
          <uv-button type="primary" @click="completeApply">完成审批</uv-button>
        </template>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { parseTime } from "@/utils/common.js"
import { getDeviceApproval, submitDeviceApproval, modifyDeviceApproval } from '@/api/oa/device/deviceApproval'
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { getProject } from "@/api/oa/project/project";
import { getDevice } from "@/api/oa/device/device";
import { getUserByRole } from "@/api/system/role";
import { getUsersManageLeader } from '@/api/system/post.js'
import FlowNote from '@/pages/components/flowNote.vue';
import ProjectPicker from '@/pages/components/ProjectPicker.vue';
import ProjectInfo from '@/pages/components/ProjectInfo.vue';
import DevicePicker from "@/pages/components/DevicePicker.vue";
import Auditor from "@/pages/components/auditor.vue";
import RepairDevicePicker from "@/pages/components/RepairDevicePicker.vue";

export default {
  components: {
    FlowNote,
    ProjectPicker,
    ProjectInfo,
    DevicePicker,
    Auditor,
    RepairDevicePicker
  },
  props: {
    taskForm: Object,
    taskName: String,
    startUserName: String,
  },
  created() {
    this.applierUserName = this.startUserName;
    this.initForm();
  },
  data() {
    return {
      form: {
        user: {
          nickName: ''
        },
        dept: {
          deptName: ''
        },
        projectId: '',
        applyDate: '',
        applyReason: '',
        beginDate: '',
        endDate: '',
        dateRange: [],
        days: 0,
        dispatchComment: '',
        managerComment: '',
        devices: [],
        modifyDevices: [],
        returnDevices: [],
        repairDevices: [],
        remark: '',
        returnDate: ''
      },
      rules: {
        projectId: {
          rules: [{ required: true, errorMessage: '请选择项目' }]
        },
        devices: {
          rules: [{ required: true, errorMessage: '请选择设备' }]
        },
        applyReason: {
          rules: [{ required: true, errorMessage: '请输入申领事由' }]
        },
        dateRange: {
          rules: [{
            required: this.taskName === '设备申请',
            errorMessage: '请选择使用日期',
            validateFunction: (rule, value, data, callback) => {
              if (!value || value.length !== 2 || !value[0] || !value[1]) {
                callback('请选择使用日期');
              } else {
                callback();
              }
            }
          }]
        },
        dispatchComment: {
          rules: [{
            required: true,
            errorMessage: '请输入安排设备意见',
            validateFunction: (rule, value, data, callback) => {
              if (this.taskName === '安排设备' && !value) {
                callback('请输入安排设备意见');
              } else {
                callback();
              }
            }
          }]
        },
        managerComment: {
          rules: [{
            required: true,
            errorMessage: '请输入分管审核意见',
            validateFunction: (rule, value, data, callback) => {
              if (this.taskName === '分管审核' && !value) {
                callback('请输入分管审核意见');
              } else {
                callback();
              }
            }
          }]
        },
        returnDate: {
          rules: [{
            required: true,
            errorMessage: '请选择归还日期',
            validateFunction: (rule, value, data, callback) => {
              if (this.taskName === '归还确认' && !value) {
                callback('请选择归还日期');
              } else {
                callback();
              }
            }
          }]
        }
      },
      applierUserName: '',
      openProject: false,
      selectedProject: null,
      projectObj: {},
      openDevice: false,
      selectDevice: [],
      deviceList: [],
      modifyDeviceList: [],
      returnDevicesList: [],
      formTotal: 0,
      currentIndex: -1,
      isReplaceMode: false,
      openRepairDevice: false,
      repairDevicesList: []
    };
  },
  watch: {
    'form.repairDevices': {
      handler(newVal) {
        this.updateRepairDevicesList();
      },
      immediate: true
    }
  },
  methods: {
    async initForm() {
      try {
        const res = await getDeviceApproval(this.taskForm.formId);
        if (res.data) {
          this.formTotal = 1;
          this.form = res.data;
          this.applierUserName = res.data.applierUser.nickName;
          const project = await getProject(res.data.projectId);
          this.projectObj = project.data;
          // 初始化申请设备
          if (res.data.devices) {
            const deviceIds = res.data.devices.split(',').map(id => parseInt(id));
            this.form.devices = res.data.devices.split(',');
            this.deviceList = [];
            this.selectDevice = [];

            for (const id of deviceIds) {
              const response = await getDevice(id);
              if (response.data) {
                this.deviceList.push(response.data);
                this.selectDevice.push(response.data);
              }
            }
          } else {
            this.deviceList = [];
          }

          // 初始化拟发放设备列表
          if (res.data.modifyDevices) {
            const modifyDeviceIds = typeof res.data.modifyDevices === 'string'
              ? res.data.modifyDevices.split(',').map(id => parseInt(id))
              : Array.isArray(res.data.modifyDevices)
                ? res.data.modifyDevices.map(id => parseInt(id))
                : [];
            this.form.modifyDevices = res.data.modifyDevices.split(',');
            this.modifyDeviceList = [];

            for (const id of modifyDeviceIds) {
              const response = await getDevice(id);
              if (response.data) {
                this.modifyDeviceList.push(response.data);
              }
            }
          } else if (this.taskName === '安排设备') {
            this.modifyDeviceList = [...this.deviceList];
          } else {
            this.modifyDeviceList = [];
          }

          // 初始化归还设备列表
          if (res.data.returnDevices) {
            const returnDeviceIds = typeof res.data.returnDevices === 'string'
              ? res.data.returnDevices.split(',').map(id => parseInt(id))
              : Array.isArray(res.data.returnDevices)
                ? res.data.returnDevices.map(id => parseInt(id))
                : [];
            this.form.returnDevices = returnDeviceIds;

            // 获取所有拟发放的设备
            const modifyDeviceIds = typeof res.data.modifyDevices === 'string'
              ? res.data.modifyDevices.split(',').map(id => parseInt(id))
              : Array.isArray(res.data.modifyDevices)
                ? res.data.modifyDevices.map(id => parseInt(id))
                : [];

            this.returnDevicesList = [];
            for (const id of modifyDeviceIds) {
              const response = await getDevice(id);
              if (response.data) {
                this.returnDevicesList.push(response.data);
              }
            }
          } else if (this.taskName === '归还确认') {
            // 在归还确认节点，使用拟发放的设备列表
            this.returnDevicesList = [...this.modifyDeviceList];
            this.form.returnDevices = []; // 初始化空数组
          } else {
            this.returnDevicesList = [];
            this.form.returnDevices = []; // 初始化空数组
          }

          // 初始化维修设备列表
          if (res.data.repairDevices) {
            const repairDeviceIds = typeof res.data.repairDevices === 'string'
              ? res.data.repairDevices.split(',').map(id => parseInt(id))
              : Array.isArray(res.data.repairDevices)
                ? res.data.repairDevices.map(id => parseInt(id))
                : [];
            this.form.repairDevices = repairDeviceIds;
            this.updateRepairDevicesList();
          } else if (this.taskName === '归还确认') {
            this.form.repairDevices = [];
            this.repairDevicesList = [];
          }

          if (this.form.beginDate && this.form.endDate) {
            this.form.dateRange = [this.form.beginDate, this.form.endDate];
          }
        } else {
          this.form.applier = this.$store.getters.userId;
          this.form.applyDate = parseTime(new Date(), "{y}-{m}-{d}");
          let name = this.applierUserName.split('-');
          this.form.user.nickName = name[0];
          this.form.dept.deptName = name[1];
          this.formTotal = 0;
          this.form.returnDevices = []; // 初始化空数组
          this.form.repairDevices = []; // 初始化空数组
        }
      } catch (error) {
        console.error('初始化表单失败:', error);
        uni.showToast({
          title: '初始化表单失败',
          icon: 'error'
        });
      }
    },
    handleConfirm(project) {
      this.selectedProject = project;
      this.projectObj = project;
      this.form.projectId = project.projectId;
    },
    handleDeviceConfirm(devices) {
      if (this.taskName === '安排设备') {
        if (this.currentIndex >= 0) {
          // 替换指定位置的设备，确保只使用第一个选中的设备
          const selectedDevice = Array.isArray(devices) ? devices[0] : devices;
          this.modifyDeviceList.splice(this.currentIndex, 1, selectedDevice);
        } else {
          // 新增设备
          this.modifyDeviceList.push(...devices);
        }
        this.isReplaceMode = false;
      } else {
        this.deviceList = Array.isArray(devices) ? devices : [devices];
        this.form.devices = this.deviceList.map(item => item.deviceId);
      }
    },
    handleDateRangeChange(e) {
      if (Array.isArray(e) && e.length === 2) {
        const [start, end] = e;
        this.form.beginDate = start;
        this.form.endDate = end;
        this.form.dateRange = [start, end];
        this.calculateDay();
      }
    },
    calculateDay() {
      if (this.form.beginDate && this.form.endDate) {
        const begin = new Date(this.form.beginDate);
        const end = new Date(this.form.endDate);
        if (!isNaN(begin.getTime()) && !isNaN(end.getTime())) {
          this.form.days = Math.ceil((end - begin) / (1000 * 60 * 60 * 24)) + 1;
        }
      }
    },
    replaceRowData(row, index) {
      this.openDevice = true;
      this.currentIndex = index;
      this.isReplaceMode = true;
      // 在安排设备节点时，设置当前选中的设备
      if (this.taskName === '安排设备') {
        this.selectDevice = [row];
      }
    },
    deleteRowData(row, index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除该设备吗？',
        success: (res) => {
          if (res.confirm) {
            this.modifyDeviceList.splice(index, 1);
          }
        }
      });
    },
    addRowdata() {
      this.openDevice = true;
      this.currentIndex = -1;
      this.isReplaceMode = false;
      // 在安排设备节点时，清空已选设备
      if (this.taskName === '安排设备') {
        this.selectDevice = [];
      }
    },
    submit() {
      this.$refs.form.validate().then(() => {
        let submitData = {
          ...this.form,
          ...(this.form.formId ? {} : { formId: this.taskForm.formId }),
          ...(this.form.deviceApplyId ? {} : { deviceApplyId: this.taskForm.formId })
        };
        let jsonForm = JSON.stringify(submitData);
        submitDeviceApproval(jsonForm).then(res => {
          // 获取下一个流程节点
          this.getNextFlowNodeApproval().then(() => {
            uni.showToast({
              title: '提交成功',
              icon: 'success'
            });
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/message/index'
              })
            }, 500);
          })
        });
      });
    },
    saves() {
      try {
        this.$refs.form.validate().then(() => {
          let submitData = {
            ...this.form,
            ...(this.form.formId ? {} : { formId: this.taskForm.formId }),
            ...(this.form.deviceApplyId ? {} : { deviceApplyId: this.taskForm.formId })
          };
          // 在安排设备节点时，添加拟发放设备列表
          if (this.taskName === '安排设备') {
            submitData.modifyDevices = this.modifyDeviceList.map(item => item.deviceId);
          }
          let jsonForm = JSON.stringify(submitData);
          modifyDeviceApproval(jsonForm).then(res => {
            if (res.code === 200) {
              uni.showToast({
                title: '保存成功',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: res.msg || '保存失败',
                icon: 'error'
              });
            }
          })
        })
      } catch (error) {
        console.error('保存方法错误:', error);
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'error'
        });
      }
    },
    completeApply() {
      this.$refs.form.validate().then(() => {
        // 在归还确认节点时，检查所有设备是否都已归还
        if (this.taskName === '归还确认') {
          const allDevices = this.modifyDeviceList.map(item => item.deviceId);
          const returnedDevices = this.form.returnDevices || [];
          const unreturnedDevices = allDevices.filter(id => !returnedDevices.includes(id));

          if (unreturnedDevices.length > 0) {
            uni.showToast({
              title: '请确认所有设备都已归还',
              icon: 'none'
            });
            return;
          }
        }

        uni.showModal({
          title: '提示',
          content: '确定提交审批吗？',
          success: (res) => {
            if (res.confirm) {
              let submitData = {
                ...this.form,
                ...(this.form.formId ? {} : { formId: this.taskForm.formId }),
                ...(this.form.deviceApplyId ? {} : { deviceApplyId: this.taskForm.formId })
              };
              // 在安排设备节点时，添加拟发放设备列表
              if (this.taskName === '安排设备') {
                submitData.modifyDevices = this.modifyDeviceList.map(item => item.deviceId);
              }
              let jsonForm = JSON.stringify(submitData);
              modifyDeviceApproval(jsonForm).then(res => {
                // 获取下一个流程节点
                getNextFlowNode({ taskId: this.taskForm.taskId }).then(res => {
                  this.getNextFlowNodeApproval().then(() => {
                    uni.showToast({
                      title: '提交成功',
                      icon: 'success'
                    });
                    setTimeout(() => {
                      uni.switchTab({
                        url: '/pages/message/index'
                      });
                    }, 500);
                  });
                });
              });
            }
          }
        });
      });
    },
    // 获取下一个审批人
    getNextFlowNodeApproval() {
      return new Promise((resolve, reject) => {
        const handleComplete = (response) => {
          this.$modal.msgSuccess(response.msg);
          resolve();
        };

        const setApprovalAndComplete = (result) => {
          this.$set(this.taskForm.variables, "approval", result.data[0]);
          complete(this.taskForm).then(handleComplete).catch(reject);
        };

        switch (this.taskName) {
          case '设备申请':
          case '分管审核':
            getUserByRole({ roleId: 4 }).then(setApprovalAndComplete).catch(reject);
            break;

          case '安排设备':
            getUsersManageLeader({ userId: this.form.applier }).then(res => {
              const userIds = res.data.map(user => user.userId);
              this.$set(this.taskForm.variables, "approvalList", userIds);
              complete(this.taskForm).then(handleComplete).catch(reject);
            }).catch(reject);
            break;

          case '归还确认':
            this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？')
              .then(() => complete(this.taskForm).then(handleComplete).catch(reject))
              .catch(reject);
            break;
        }
      });
    },
    isDeviceSelected(deviceId) {
      return this.form.returnDevices && this.form.returnDevices.includes(deviceId);
    },
    toggleDeviceSelection(device) {
      if (this.taskName !== '归还确认') return;
      // 确保 returnDevices 是数组
      if (!Array.isArray(this.form.returnDevices)) {
        this.form.returnDevices = [];
      }
      const index = this.form.returnDevices.indexOf(device.deviceId);
      if (index === -1) {
        // 添加设备到已归还列表
        this.form.returnDevices.push(device.deviceId);
      } else {
        // 从已归还列表中移除设备
        this.form.returnDevices.splice(index, 1);
      }
    },
    updateRepairDevicesList() {
      // 如果 repairDevices 是字符串，转换为数组
      if (typeof this.form.repairDevices === 'string') {
        this.form.repairDevices = this.form.repairDevices.split(',').map(id => parseInt(id));
      } else if (!Array.isArray(this.form.repairDevices)) {
        this.form.repairDevices = [];
      }

      this.repairDevicesList = this.modifyDeviceList.filter(device =>
        this.form.repairDevices.includes(device.deviceId)
      );
    }
  }
}
</script>

<style lang="scss" scoped>
.form-container {
  padding: 32rpx;
}

.form-title {
  text-align: center;
  margin-bottom: 32rpx;

  .title-text {
    font-size: 36rpx;
    font-weight: bold;
  }

  .title-line {
    height: 2rpx;
    background: #eee;
    margin-top: 16rpx;
  }
}

.date-range {
  // display: flex;
  flex-wrap: wrap;
  gap: 32rpx;
}

.date-text {
  margin: 0 10px;
  font-weight: bold;
}

.form-actions {
  justify-content: center;
  gap: 32rpx;
  margin-top: 32rpx;
}

::v-deep .uni-forms-item__label {
  font-weight: bold;
}

.device-cards {
  margin-top: 20rpx;
}

.device-card {
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;

  &.selected {
    border: 2rpx solid #67c23a;
    background-color: rgba(103, 194, 58, 0.05);
  }
}

.card-header {
  padding: 16rpx 20rpx;
  background: #f5f7fa;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.return-tag {
  margin-left: 10rpx;
}

.card-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-content {
  padding: 16rpx 20rpx;
}

.card-row {
  display: flex;
  margin-bottom: 12rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.card-item {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 26rpx;
  line-height: 1.4;
  padding: 0 10rpx;
  min-width: 0; // 防止内容溢出

  .label {
    color: #666;
    flex-shrink: 0;
    margin-right: 8rpx;
  }

  .value {
    color: #333;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.card-actions {
  padding: 16rpx 20rpx;
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  border-top: 1rpx solid #eee;
}

.device-card {
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;

  &.repair-card {
    border: 2rpx solid #f56c6c;
    background-color: rgba(245, 108, 108, 0.05);
  }
}

.card-header {
  padding: 16rpx 20rpx;
  background: #f5f7fa;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.repair-tag {
  margin-left: 10rpx;
}
</style>