<template>
  <div class="content" v-loading="Status.fullLoading">
    <div class="main">
      <div class         ="TopTool">
        <div class="button-row">
          <el-button type="primary" icon="Plus" @click.stop="ShowEdit(null, true, formRef)">新增维修</el-button>
          <el-button type="primary" plain icon="Download" @click.stop="ExportRecord()">导出</el-button>
          <el-button type="danger" plain icon="Delete" @click.stop="DropRecord()">批量删除</el-button>
        </div>

        <div class="rightSearch">
          <el-input :suffix-icon="'Search'" clearable v-model="advanceSearch.searchValue" class="responsive-input"
            placeholder="名称" @input="txtSearch">
          </el-input>

          <el-button style="margin-left: 10px" type="primary" @click.stop="ToggleAdvance()">高级筛选</el-button>
        </div>
      </div>
      <div class="advanceSearch" v-show="Status.ShowAdvanceSearch">
        <el-form :inline="true" :model="advanceSearch" class="demo-form-inline">
          <!-- <el-form-item label="设备名称">
            <el-input placeholder="请选择" v-model="selectedRow['deviceName']" :readonly="true" @click.stop="ShowDevice('Search', false)" /> 

            <el-select v-model="advanceSearch.deviceId" placeholder="选择设备" clearable filterable>
              <el-option v-for="item in deviceDist" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId" />
            </el-select>
          </el-form-item> -->

          <el-form-item label="维修人员">
            <el-input v-model="advanceSearch.repairPerson" placeholder="请输入人员名称" clearable />
          </el-form-item>

          <el-form-item label="维修部位">
            <el-input v-model="advanceSearch.repairPart" placeholder="请输入" clearable />
          </el-form-item>
          <!-- <el-form-item label="维修原因">
            <el-input v-model="advanceSearch.repairReason" placeholder="请输入" clearable />
          </el-form-item> -->
          <el-form-item label="维修时间">
            <el-date-picker v-model="advanceSearch.Date" type="daterange" format="YYYY-MM-DD" style="width: 240px"
              value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
              :size="'default'" />
            <div>
              <el-button style="margin-left: 5px" type="primary" @click.stop="Search()">查询</el-button>
              <el-button type="primary" @click.stop="Reset()">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div class="grid" v-loading="Status.loading">
        <el-table ref="grid" height="calc(100vh - 360px)" border :data="List" @selection-change="RowSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="设备名称" align="center" prop="deviceName" />
          <el-table-column label="维修时间" align="center" prop="repairTime" />
          <el-table-column label="损坏部位" align="center" prop="repairPart" />
          <el-table-column label="损坏原因" align="center" prop="repairReason" />
          <el-table-column label="维修人员" align="center" prop="repairPerson" />

          <el-table-column label="操作" align="center" fixed="right" width="280"
            class-name="small-padding fixed-width opt">
            <template #default="scope">
              <div class="center">
                <el-text class="mx-1" type="primary" @click.stop="ShowEdit(scope.row, true, formRef)">编辑</el-text>
                <el-text class="mx-1" type="primary" @click.stop="ShowEdit(scope.row, false)">详情</el-text>
                <el-text class="mx-1" type="danger" @click.stop="DropRecord([scope.row])">删除</el-text>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="pagin.total > 0" v-model:page="advanceSearch.pageNum" v-model:limit="advanceSearch.pageSize"
          :total="pagin.total" @pagination="getRecordList" />
      </div>
    </div>

    <!-- 新增、编辑弹出层 -->
    <el-dialog class="editPop" v-model="Status.ShowEditPop" :data-val="Status.ShowEditPop"
      :title="!cEdit.isEdit ? '维修详情' : cEdit.recordId ? '编辑维修' : '新增维修'" width="800" :draggable="true">
      <div class="form">
        <el-form :model="cEdit" ref="formRef" style="max-width: 750px" :rules="rules">
          <el-form-item label="设备名称" label-position="right" prop="deviceId">
            <!-- <el-input v-model="selectedRow['deviceName']" :readonly="true" @click.stop="ShowDevice('Edit', true)" placeholder="请选择设备" /> -->
            <el-select v-model="cEdit.deviceId" placeholder="选择设备" clearable :disabled="!cEdit.isEdit" filterable>
              <el-option v-for="item in deviceDist" :key="item.deviceId" :label="item.deviceName"
                :value="item.deviceId" /></el-select>
          </el-form-item>

          <el-form-item label="维修人员" label-position="right" prop="repairPerson">
            <el-input v-model="cEdit.repairPerson" :readonly="!cEdit.isEdit" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="维修时间" label-position="right" prop="repairTime">
            <el-date-picker v-model="cEdit.repairTime" :readonly="!cEdit.isEdit" type="datetime" placeholder="请选择时间"
              format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
          </el-form-item>
          <el-form-item label="维修部位" label-position="right" prop="repairPart">
            <el-input v-model="cEdit.repairPart" :readonly="!cEdit.isEdit" placeholder="请输入维修部位" />
          </el-form-item>
          <el-form-item label="维修原因" label-position="right" prop="repairReason">
            <el-input v-model="cEdit.repairReason" :readonly="!cEdit.isEdit" placeholder="请输入维修原因" />
          </el-form-item>

          <el-form-item label="损坏照片" label-position="right">
            <el-upload :disabled="!cEdit.isEdit" ref="beforeUploadRef" class="upload-demo" action=""
              :auto-upload="false" :on-change="handleFileChange1" :file-list="beforeFiles"
              accept=".jpg,.jpeg,.png,.gif.webp" :limit="9" list-type="picture-card"
              :class="{ 'hide-add-btn': !cEdit.isEdit }">
              <el-icon>
                <Plus />
              </el-icon>
              <template #file="{ file, index }">
                <!-- 图片预览区域 -->
                <div class="el-upload-list__item">
                  <!-- 图片缩略图 -->
                  <img :src="file.url" class="el-upload-list__item-thumbnail" />

                  <!-- 操作按钮组 -->
                  <div class="el-upload-list__item-actions" v-show="cEdit.isEdit">
                    <!-- 自定义删除按钮 -->
                    <span class="el-upload-list__item-delete" @click.stop="dropImg('before', file, index)">
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </div>
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="修复照片" label-position="right">
            <el-upload :disabled="!cEdit.isEdit" ref="afterUploadRef" class="upload-demo" action="" :auto-upload="false"
              :on-change="handleFileChange2" :file-list="afterFiles" accept=".jpg,.jpeg,.png,.gif.webp" :limit="9"
              list-type="picture-card" :class="{ 'hide-add-btn': !cEdit.isEdit }">
              <el-icon>
                <Plus />
              </el-icon>
              <template #file="{ file, index }">
                <!-- 图片预览区域 -->
                <div class="el-upload-list__item">
                  <!-- 图片缩略图 -->
                  <img :src="file.url" class="el-upload-list__item-thumbnail" />
                  <!-- 操作按钮组 -->
                  <div class="el-upload-list__item-actions" v-show="cEdit.isEdit">
                    <!-- 自定义删除按钮 -->
                    <span class="el-upload-list__item-delete" @click.stop="dropImg('after', file, index)">
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </div>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="center" style="margin-top: 10px">
            <el-button type="primary" @click="SaveFormData(formRef)"> 确定 </el-button>
            <el-button @click="CloseEdit()"> 取消 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 选择设备弹出层 -->
    <!-- <el-dialog v-model="Status.ShowCheckDevice" title="选择设备" width="90%" class="checkDeviceDialog" :draggable="true">
      <div class="deviceContnet">
        <div class="topSearch">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable />
            </el-form-item>
            <el-form-item label="设备MAC" prop="deviceMac">
              <el-input v-model="queryParams.deviceMac" placeholder="请输入设备MAC" clearable />
            </el-form-item>
            <el-form-item label="请输入设备IMEI" prop="deviceImei">
              <el-input v-model="queryParams.deviceImei" placeholder="请输入设备IMEI" clearable />
            </el-form-item>
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="queryParams.deviceType" placeholder="设备类型">
                <el-option v-for="item in deviceTypes" :key="item.value" :label="item.typeName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备状态" prop="deviceStatus">
              <el-select v-model="queryParams.deviceStatus" placeholder="设备状态" style="margin-left: 10px">
                <el-option label="正常" value="1" />
                <el-option label="失效" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </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>
        </div>
        <div class="gridContent">
          <el-table ref="deviceGrid" v-loading="Status.devLoading" border :data="deviceDist" height="250" @row-click="handleRadioChange">
        
            <el-table-column label="选择" width="80" align="center">
              <template #default="scope">
                <el-radio :model-value="selectedRowId" :label="scope.row.deviceId" @change="handleRadioChange(scope.row)" />
              </template>
            </el-table-column>

            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column prop="customerName" label="所属客户" />
            <el-table-column prop="devicePic" label="设备图片">
              <template #default="scope">
                <el-popover placement="right" trigger="click">
                  <template #reference>
                    <img
                      :src="scope.row.devicePic"
                      style="width: 40px; height: 40px; cursor: pointer; object-fit: contain"
                      class="hover:opacity-80 transition-opacity"
                    />
                  </template>
                  <img :src="scope.row.devicePic" style="max-width: 600px; max-height: 600px; object-fit: contain" />
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="deviceMac" label="设备MAC" />
            <el-table-column prop="bluetoothName" label="蓝牙名称" />
            <el-table-column prop="deviceImei" label="设备IMEI" />
            <el-table-column prop="typeName" label="设备类型" />
            <el-table-column prop="bindingStatus" label="绑定状态">
              <template #default="scope">
                <el-tag :type="scope.row.bindingStatus === 1 ? 'success' : 'info'">
                  {{ scope.row.bindingStatus === 1 ? '已绑定' : '未绑定' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="deviceStatus" label="设备状态">
              <template #default="scope">
                <el-tag :type="scope.row.deviceStatus == 1 ? 'success' : 'danger'">
                  {{ scope.row.deviceStatus == 1 ? '正常' : '失效' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
            <el-table-column prop="createTime" label="创建日期" width="160" />
            <el-table-column prop="createByName" label="创建人" />
          </el-table>
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getList"
          />
        </div>
      </div>
      <template #footer>
        <div class="center" >
          <el-button type="primary" @click="CheckDeviceOK()"> 确定 </el-button>
          <el-button @click="CloseDevice()"> 取消 </el-button>
        </div>
      </template>
    </el-dialog> -->

    <!-- 提示框 -->
    <el-dialog :width="300" :draggable="true" v-model="Status.confirm.Visible" :title="Status.confirm.title" width="500"
      center>
      <span>
        {{ Status.confirm.text }}
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="Status.confirm.OkCallback"> 确定 </el-button>
          <el-button v-show="Status.confirm.showCancel" @click="Status.confirm.cancelCallback">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import api from '@/api/equipmentManagement/repairRecords/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

var grid = ref(null);
var deviceGrid = ref(null);

//全局状态控制
var Status = reactive({
  fullLoading: false, //是否显示全屏loading
  loading: false, //是否显示表格区域loading
  confirm: {
    //弹出框的配置
    Visible: false,
    title: '',
    text: '',
    cancelCallback: null,
    OkCallback: null,
    showCancel: true
  },
  ShowEditPop: false, //是否显示编辑弹窗
  ShowAdvanceSearch: false, //是否显示高级筛选
  ShowCheckDevice: false, //是否显示选择设备的弹窗
  CheckDeviceType: 'Search'
});
//高级查询
var advanceSearch = reactive({
  'recordId': null,
  'deviceId': '',
  'searchValue': '',
  'search': '',
  'repairPart': '',
  'repairReason': '',
  'repairPerson': '',
  Date: [],
  pageNum: 1,
  pageSize: 10
});

//选择设备
var selectedRowId = ref('');
var selectedRow = ref({});
function handleRadioChange(row) {
  selectedRowId.value = row.deviceId;
  selectedRow.value = row;
}

//照片上传
var beforeFiles = ref([]);
var afterFiles = ref([]);

var beforeFile = ref([]);
var afterFile = ref([]);

var beforeUploadRef = ref(null);
var afterUploadRef = ref(null);

function clearUploadFiles() {
  beforeFiles.value = [];
  afterFiles.value = [];
  beforeFile.value = [];
  afterFile.value = [];
  beforeUploadRef.value?.clearFiles();
  afterUploadRef.value?.clearFiles();
}

//页码控件数据
var pagin = reactive({
  total: 0
});

//列表数据
var List = ref<any[]>(null);

//当前正在编辑的数据
var cEdit = reactive({
  recordId: null, //维修记录id
  deviceId: '', //设备id
  repairTime: '', //维修时间
  repairPart: '', //维修部位
  repairReason: '', //维修原因
  repairPerson: '', //维修人员
  isEdit: true,
  imageIds: []
});

var deviceTypes = reactive([]);

//重置搜索条件
function Reset() {
  let defVal = {
    'recordId': null,
    'deviceId': '',
    'searchValue': '',
    'search': '',
    'repairPart': '',
    'repairReason': '',
    'repairPerson': '',
    'Date': []
  };
  selectedRow.value.deviceName = '';
  let keys = Object.keys(defVal);
  keys.forEach(function (item, index, array) {
    advanceSearch[item] = defVal[item];
  });
  Search();
}
//查询
function Search() {
  advanceSearch.pageNum = 1;
  getRecordList();
}
//右上角的文本框输入后查询
let searchIntval = null;
function txtSearch() {
  clearTimeout(searchIntval);
  // 等待 500ms 无输入后执行查询
  searchIntval = setTimeout(() => {
    Search();
  }, 500);
}

//获取列表数据
function getRecordList() {
  showloading('loading');
  setTimeout(() => {
    api
      .getRepairList(advanceSearch)
      .then((res) => {
        if (res.code == 200) {
          List.value = res.rows;
          pagin.total = res.total;
        } else {
          alert(res.msg);
        }
      })
      .finally(hideloading);
  }, 0);
}

//删除
function DropRecord(arr = undefined) {
  if (arr === undefined) {
    arr = getSelectionRows(grid);
  }
  if (arr.length == 0) {
    alert('请选择需要删除的数据');
    return;
  }

  confirm(
    '您确认删除' + arr.length + '条记录吗?',
    () => {
      showloading('fullLoading');
      arr = arr.map((item) => item.recordId);
      api.dropRepir(arr).then((res) => {
        if (res && res.code == 200) {
          Search();
        }
        alert(res.msg);
      });
    },
    hideConfirm,
    '提示'
  );
}

//高级查询显示隐藏
function ToggleAdvance() {
  Status.ShowAdvanceSearch = !Status.ShowAdvanceSearch;
}

//显示编辑
function ShowEdit(item = undefined, isEdit = true, formEl = undefined) {
  // 先隐藏弹窗，避免提前渲染错误状态
  Status.ShowEditPop = true;
  let def = {
    recordId: null,
    deviceId: '',
    repairTime: '',
    repairPart: '',
    repairReason: '',
    repairPerson: '',
    imageIds: []
  };
  // 先重置表单和状态，避免残留
  ResetFormData();
  // 先赋值 isEdit 基础状态
  cEdit.isEdit = isEdit;
  let promise1 = new Promise((resolve, reject) => {
    if (item) {
      api
        .getRepirDetail(item.recordId)
        .then((res) => {
          if (res.code == 200) {
            resolve(res.data);
          } else {
            resolve(item);
          }
        })
        .catch((ex) => {
          resolve(item);
        });
    } else {
      resolve(item);
    }
  });

  promise1
    .then((res) => {
      item = res;
      if (!item) {
        // 新增场景，isEdit 保持 true
        cEdit.isEdit = isEdit;
        return;
      }
      let keys = Object.keys(cEdit);
      keys.forEach((key, i) => {
        if (item) {
          // 编辑/详情场景，赋值数据
          if (item[key] !== undefined) {
            cEdit[key] = item[key];
          } else {
            cEdit[key] = def[key];
          }
        } else {
          // 新增场景
          cEdit[key] = def[key];
        }
      });
      if (item.images && item.images.length) {
        // 处理图片逻辑（保持原有代码）
        beforeFiles.value = item.images
          .filter((v) => v.imageType == 'BEFORE')
          .map((v) => ({ name: v.imageId, url: v.imageUrl, id: v.imageId }));
        afterFiles.value = item.images
          .filter((v) => v.imageType == 'AFTER')
          .map((v) => ({ name: v.imageId, url: v.imageUrl, id: v.imageId }));
        if (formEl) formEl.validate();
      }
      if (item) {
        selectedRow.value['deviceName'] = item.deviceName;
      }
      // 确保 isEdit 最终赋值正确（覆盖异步过程中可能的异常）
      cEdit.isEdit = isEdit;
      // 所有状态赋值完成后，再显示弹窗
      Status.ShowEditPop = true;
    })
    .finally(() => {});
}

//关闭编辑弹窗
function CloseEdit() {
  Status.ShowEditPop = false;
  ResetFormData();
}

//显示选择设备的弹窗
function ShowDevice(type, isvalid) {
  if (isvalid && !cEdit.isEdit) {
    return;
  }
  Status.CheckDeviceType = type;
  Status.ShowCheckDevice = true;
  selectedRowId.value = '';
  if (total.value === 0) {
    handleQuery();
  }
}

//关闭选择设备
function CloseDevice() {
  Status.ShowCheckDevice = false;
}

//确认选择某个设备
function CheckDeviceOK() {
  if (Status.CheckDeviceType == 'Edit') {
    cEdit.deviceId = selectedRowId.value;
  } else {
    advanceSearch.deviceId = selectedRowId.value;
  }
  CloseDevice();
}

function ResetFormData() {
  cEdit.recordId = null; //维修记录id
  cEdit.deviceId = ''; //设备id
  cEdit.repairTime = ''; //维修时间
  cEdit.repairPart = ''; //维修部位
  cEdit.repairReason = ''; //维修原因
  cEdit.repairPerson = ''; //维修人员
  cEdit.imageIds = [];
  selectedRow.value = { deviceName: '', deviceId: '' };
  clearUploadFiles();
}

var dropImg = (type, file, index) => {
  let runDrop = () => {
    if (type == 'after') {
      afterFiles.value.splice(index, 1);
    }
    if (type == 'before') {
      beforeFiles.value.splice(index, 1);
    }
    if (file.id) {
      cEdit.imageIds.push(file.id);
    }
  };
  confirm('您确认删除此记录吗?', runDrop, hideConfirm, '提示');
};
//保存表单数据
function SaveFormData(formEl: FormInstance | undefined) {
  if (!cEdit.isEdit) {
    CloseEdit();
    return;
  }

  if (!formEl) return;

  let submit = () => {
    showloading('fullLoading');
    setTimeout(() => {
      let promise = null;

      let formData = new FormData();

      let keys = Object.keys(cEdit);
      for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        if (key == 'isEdit') {
          continue;
        }
        if (cEdit[key] === null || cEdit[key] === undefined) {
          continue;
        }
        formData.append(key, cEdit[key]);
      }

      // 添加第一个控件的文件
      if (beforeFile.value.length > 0) {
        for (let i = 0; i < beforeFile.value.length; i++) {
          let file = beforeFile.value[i];
          if (file && !file.id) {
            formData.append('beforeFile', file);
          }
        }
      }

      if (afterFile.value.length > 0) {
        // formData.append('afterFile', afterFile.value[0]);

        for (let i = 0; i < afterFile.value.length; i++) {
          let file = afterFile.value[i];
          if (file && !file.id) {
            formData.append('afterFile', file);
          }
        }
      }

      if (cEdit.recordId) {
        promise = api.updateRepair(formData);
      } else {
        promise = api.addRepir(formData);
      }

      promise
        .then((res) => {
          if (res.code == 200) {
            alert('操作成功');
            CloseEdit();
            Search();
          } else {
            alert(res.msg);
          }
        })
        .finally(() => {
          ResetFormData();
          hideloading();
        });
    }, 0);
  };
  formEl.validate((valid) => {
    if (valid) {
      submit();
    }
  });
}

//导出
function ExportRecord() {
  // showloading('fullLoading');
  proxy?.download('/equipment/repairRecords/export', advanceSearch, `维修记录_${new Date().getTime()}.xlsx`, 'post').finally(hideloading);
}

function RowSelectionChange(row) { }
//获取已选中的行
var getSelectionRows = (gridInstance) => {
  if (gridInstance.value) {
    // 检查ref是否已正确引用组件实例
    var selectedRows = gridInstance.value.getSelectionRows(); // 获取选中行数据数组
    return selectedRows;
  }
  return [];
};

const handleFileChange1 = (file, fileList) => {
  beforeFiles.value = fileList;
  beforeFile.value = fileList.map((f) => f.raw);
};

// 处理第二个上传控件的文件变化
const handleFileChange2 = (file, fileList) => {
  afterFiles.value = fileList;
  afterFile.value = fileList.map((f) => f.raw);
};

window.confirm = function (text, OK, cancel, title) {
  let Cfg = {
    Visible: true,
    title: title ? title : '提示',
    text: text ? text : '此操作不可逆，您确定这样做吗？',
    OkCallback: () => {
      Status.confirm.Visible = false;
      if (OK) {
        OK();
      }
    },
    showCancel: true,
    cancelCallback: () => {
      Status.confirm.Visible = false;
      if (cancel) {
        cancel();
      }
    }
  };

  Status.confirm = Cfg;
};

window.alert = function (text, OK, title) {
  let Cfg = {
    Visible: true,
    title: title ? title : '提示',
    text: text ? text : '不符合规则',
    OkCallback: () => {
      Status.confirm.Visible = false;
      if (OK) {
        OK();
      }
    },
    showCancel: false,
    cancelCallback: null
  };

  Status.confirm = Cfg;
};

var hideConfirm = function () {
  let Cfg = {
    Visible: false,
    title: '提示',
    text: '',
    cancelCallback: null,
    OkCallback: null
  };

  Status.confirm = Cfg;
};

var showloading = function (type) {
  if (!type) {
    type = 'loading';
  }
  let arr = ['fullLoading', 'loading', 'devLoading'];

  arr.forEach((key) => {
    if (key == type) {
      Status[key] = true;
    } else {
      Status[key] = false;
    }
  });
};

var closeLoading = function () {
  let arr = ['fullLoading', 'loading', 'devLoading'];

  arr.forEach((key) => {
    Status[key] = false;
  });
};
var hideloading = closeLoading;

onMounted(() => {
  Search();
  getList();
  api.getDeviceTypeAll((res) => {
    if (res.code == 200) {
      deviceTypes = res.data.map((item) => ({
        value: item.deviceTypeId,
        typeName: item.typeName
      }));
    }
  });
});

///设备相关
var queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  deviceName: '',
  deviceMac: '',
  deviceImei: '',
  deviceType: '',
  deviceStatus: ''
});
const total = ref(0);
const formRef = ref<ElFormInstance>();
const deviceDist = ref<any[]>();
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const getList = async () => {
  // showloading('devLoading');
  // const res = await deviceapi.deviceList(proxy?.addDateRange(queryParams.value, dateRange.value));
  // hideloading();
  // deviceDist.value = res.rows;
  // total.value = res.total;
  api.getDeviceAll().then((res) => {
    deviceDist.value = res.rows;
  });
};

/** 搜索按钮操作 */
// const handleQuery = () => {
//   queryParams.value.pageNum = 1;
//   getList();
// };
// /** 重置按钮操作 */
// const resetQuery = () => {
//   queryFormRef.value?.resetFields();
//   dateRange.value = ['', ''];
//   handleQuery();
// };

interface RuleForm {
  recordId: Number; //维修记录id
  createTime: string;
  updateTime: string;
  deviceId: string; //设备id
  repairTime: string; //维修时间
  repairPart: string; //维修部位
  repairReason: string; //维修原因
  repairPerson: string; //维修人员
}

const rules = reactive<FormRules<RuleForm>>({
  deviceId: [{ required: true, message: '请选择设备', trigger: 'change' }],
  repairTime: [{ required: true, message: '请选择维修时间', trigger: 'blur' }],
  repairPart: [{ required: true, message: '请填写维修部位', trigger: 'blur' }],
  repairReason: [{ required: true, message: '请填写维修原因', trigger: 'blur' }],
  repairPerson: [{ required: true, message: '请填写维修人员', trigger: 'blur' }]
});
</script>

<style lang="scss" scoped>
:deep .deviceContnet .el-radio__label {
  display: none !important;
}

.deviceContnet {
  position: relative;
  background-color: #ffffff;
  width: 100%;
  height: 100%;
}

.deviceContnet .topSearch {
  position: sticky;
  top: 0px;
  z-index: 9;
  background-color: #ffffff;
}

.deviceContnet .deviceGrid {
  height: calc(92% - 500px);
}

:deep .checkDeviceDialog {
  width: calc(calc(100% - 280px) * 0.9);
  height: 600px;
}

:deep .el-form--inline .el-form-item {
  margin-right: 15px !important;
}

:deep .el-dialog__body .form {}

:deep .el-dialog__body,
.dialog__body {
  position: relative;
  padding: 0px !important;
}

:deep .el-dialog__body .footerBtn {
  position: sticky;
  bottom: 0px;
  z-index: 9;
  background-color: #ffffff;
}

:deep .el-form-item__label {
  padding: 0px 5px 0px 0px !important;
}

.advanceSearch {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: center;
  align-items: center;
  justify-content: flex-start;
}

.TopTool .rightSearch {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  align-items: center;
  justify-content: space-between;
}

.TopTool .input-with-Search {
  max-width: 175px;
  margin-right: 15px;
}

.TopTool {
  width: 100%;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.main {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border-radius: 4px;
  box-shadow: 0px 0px 6px 0px #0022601a;
  background: #ffffff;
  box-sizing: border-box;
  padding: 12px 12px;
}

.fleft {
  float: left;
}

.fright {
  float: right;
}

.clear {
  clear: both;
}

.center {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  align-items: center;
  justify-content: center;
}

.displayNone {
  display: none !important;
}

input:focus {
  outline: none;
}

.H100 {
  height: 100%;
}

.content {
  width: 100%;
  min-height: calc(100vh - 84px);
  height: calc(100vh - 84px);
  background: rgba(247, 248, 252, 1);
  font-size: 16px;
  box-sizing: border-box;
  padding: 8px 20px;
  font-family: 'Microsoft YaHei';
}

.opt .mx-1 {
  margin-right: 10px;
  cursor: pointer;
}

:deep .el-dialog__footer,
.el-dialog__footer {
  padding-top: 0px !important;
}

:deep .demo-fit .el-avatar--square,
.demo-fit .el-avatar--square {
  margin-right: 10px;
}

:deep .el-upload-list--picture-card .el-upload-list__item .el-upload-list__item,
.el-upload-list--picture-card .el-upload-list__item .el-upload-list__item {
  margin: 0px;
}

// :deep .el-upload-list__item,.el-upload-list__item{
//   margin-right: 8px !important;
// }

:deep .hide-add-btn .el-upload.is-disabled,
.hide-add-btn .el-upload.is-disabled {
  display: none !important;
}
</style>
