<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          type="daterange"
          value-format="yyyy-MM-dd"
          style="width: 240px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键词"
          clearable
          @keyup.enter.native="handleQuery"
          maxlength="20"
        />
      </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-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        <el-button type="warning" icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="deviceList" ref="multipleTable" row-key="maId">
      <el-table-column label="序号" align="center" width="80" type="index">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" prop="maName"  show-overflow-tooltip />
      <el-table-column label="规格型号" align="center" prop="maModel"  show-overflow-tooltip />
      <el-table-column label="设备编号" align="center" prop="maCode" />
      <el-table-column label="本次检验时间" align="center" prop="thisCheckTime" show-overflow-tooltip />
      <el-table-column label="下次检验时间" align="center" prop="nextCheckTime" show-overflow-tooltip />
      <el-table-column label="检修员" align="center" prop="repairMan" show-overflow-tooltip/>
      <el-table-column label="检验员" align="center" prop="checkMan" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</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="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceTypeId">
              <el-select
                v-model="form.deviceTypeId"
                placeholder="请选择设备类型"
                filterable
                @change="handleDeviceTypeChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in deviceTypeOptions"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceModelId">
              <el-select
                v-model="form.deviceModelId"
                placeholder="请选择设备型号"
                filterable
                style="width: 100%"
                :disabled="!form.deviceTypeId"
                :loading="modelLoading"
              >
              <el-option
                v-for="item in deviceModelOptions"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
              />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="deviceCode">
              <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="本次检验" prop="thisCheckTime">
              <el-date-picker
                v-model="form.thisCheckTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="thisCheckDateOptions"
                @change="handleThisCheckDateChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次检验">
              <el-input
                v-model="form.nextCheckTime"
                readonly
                class="next-check-date"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验员" prop="checkMan">
              <el-input v-model="form.checkMan" placeholder="请输入检验员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修员" prop="repairMan">
              <el-input v-model="form.repairMan" placeholder="请输入维修员姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检验结论" prop="result">
              <el-input
                type="textarea"
                :rows="3"
                v-model="form.result"
                placeholder="请输入检验结论"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </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>

    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <span class="download-template-link" @click="downloadTemplate">
            <i class="el-icon-download" v-if="!downloadLoading"></i>
            <i class="el-icon-loading" v-else style="color: #1890FF"></i>
            {{ downloadLoading ? '下载中...' : '下载模板' }}
          </span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addWsMaInfoData, delGadget,
  getDeviceType, getGadgetInfo, getGadgetList, updateGadgetInfo
} from '@/api/ma/device'
import {getToken} from "@/utils/auth";

export default {
  name: 'Device',
  dicts: ['ma_machine_status'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      showHouse: false,
      // 总条数
      total: 0,
      totalTwo: 0,
      // 表格数据
      deviceList: [],
      maxLength: 100,//已选列表上限，防止数据过多请求报错
      dateRange:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined,
        startTime: '',
        endTime: ''
      },
      // 查询参数
      queryTeam: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        sex: undefined,
        teamId: undefined
      },
      // 模板下载加载状态
      downloadLoading: false,
      uploadUrlTemp:null,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/material/wsMaInfo/importData"
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        id:null,
        deviceTypeId: null,
        deviceModelId: null,
        deviceCode: '',
        thisCheckTime: '',
        nextCheckTime: '',
        checkMan: '',
        repairMan: '',
        phone: '',
        result: ''
      },
      modelLoading: false,
      // 表单校验
      rules: {
        deviceTypeId: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        deviceModelId: [
          { required: true, message: "设备型号不能为空", trigger: "change" }
        ],
        deviceCode: [
          { required: true, message: "设备编码不能为空", trigger: "blur" }
        ],
        thisCheckTime: [
          { required: true, message: "本次检验日期不能为空", trigger: "change" }
        ],
        checkMan: [
          { required: true, message: "检验员不能为空", trigger: "blur" }
        ],
        repairMan: [
          { required: true, message: "维修员不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        result: [
          { required: true, message: "检验结论不能为空", trigger: "blur" }
        ]
      },
      // 设备类型选项
      deviceTypeOptions: [],
      // 设备型号选项
      deviceModelOptions: [],
      // 本次检验日期选项
      thisCheckDateOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      }

    }
  },
  created() {
    this.getList()
    this.getDeviceTypeOptions();
    this.uploadUrlTemp=window.location.origin+"/aaa.xlsx";
    // this.uploadUrlTemp=window.location.origin+"/aaa.xlsx";
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      this.queryParams.startTime= this.dateRange ? this.dateRange[0] : ''
      this.queryParams.endTime= this.dateRange ? this.dateRange[1] : ''
      getGadgetList(this.queryParams).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取设备类型选项 */
    async getDeviceTypeOptions() {
      try {
        const response = await getDeviceType({ level: 3, skipPermission: 1 });
        this.deviceTypeOptions = response.data || [];
      } catch (error) {
        console.error('获取设备类型失败:', error);
        this.deviceTypeOptions = [];
      }
    },
    /** 设备类型变化时获取设备型号 */
    async handleDeviceTypeChange(value) {
      this.form.deviceModelId = null;
      if (value) {
        this.modelLoading = true;
        try {
          const response = await getDeviceType({ typeId: value });
          this.deviceModelOptions = response.data || [];
        } catch (error) {
          console.error('获取设备型号失败:', error);
          this.deviceModelOptions = [];
        } finally {
          this.modelLoading = false;
        }
      } else {
        this.deviceModelOptions = [];
      }
    },
    /** 本次检验日期变化时计算下次检验日期 */
    handleThisCheckDateChange(date) {
      if (date) {
        const thisDate = new Date(date);
        const nextDate = new Date(thisDate);
        nextDate.setFullYear(nextDate.getFullYear() + 1);
        nextDate.setDate(nextDate.getDate() - 1);

        // 格式化日期为yyyy-MM-dd
        const year = nextDate.getFullYear();
        const month = (nextDate.getMonth() + 1).toString().padStart(2, '0');
        const day = nextDate.getDate().toString().padStart(2, '0');

        this.form.nextCheckTime = `${year}-${month}-${day}`;
      } else {
        this.form.nextCheckTime = '';
      }
    },

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

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.keyWord = null
      this.dateRange=[]
      this.handleQuery()
    },
    handleExport() {
      const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}${month}${day}_${hours}${minutes}${seconds}`;
      };

      const currentTime = formatTime(new Date());
      this.download(
        "/material/wsMaInfo/exportGadgetList",
        {keyWord: this.queryParams.keyWord,startTime: this.dateRange && this.dateRange[0],endTime: this.dateRange && this.dateRange[1]},
        `领料出库报表_${currentTime}.xlsx`
      );
    },
    handleImport() {
      this.upload.title = "小工具编码信息导入";
      this.upload.open = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小工具信息";
    },
    /** 编辑按钮操作 */
    async handleEdit(row) {
      this.reset();
      try {
        const response = await getGadgetInfo(row.id);
        this.form = { ...response.data,deviceCode: response.data.maCode};

        // 先设置设备类型ID
        this.form.deviceTypeId =response.data.deviceTypeId;

        // 加载设备类型选项（如果尚未加载）
        if (this.deviceTypeOptions.length === 0) {
          await this.getDeviceTypeOptions();
        }

        // 加载设备型号选项
        await this.handleDeviceTypeChange(this.form.deviceTypeId);

        // 设置设备型号ID - 确保选项已加载
        this.form.deviceModelId =response.data.deviceModelId;

        this.open = true;
        this.title = "修改小工具信息";
      } catch (error) {
        console.error('获取设备信息失败:', error);
        this.$message.error('获取设备信息失败');
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除设备编号为"' + row.maCode + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const loading = this.$loading({ text: '删除中...' })
        try {
          const res = await delGadget({ id: row.id})
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        } catch (error) {
          console.log('删除失败', error)
        } finally {
          loading.close()
        }
      })
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const data = { ...this.form };
          // 获取设备类型名称
          const deviceType = this.deviceTypeOptions.find(item => item.typeId === data.deviceTypeId);
          if (deviceType) {
            data.maName = deviceType.typeName; // 添加设备类型名称
          }

          // 获取设备型号名称
          const deviceModel = this.deviceModelOptions.find(item => item.typeId === data.deviceModelId);
          if (deviceModel) {
            data.maModel = deviceModel.typeName; // 添加设备型号名称
          }
          const params = {
            id: this.form.id,
            maName: data.maName,
            maModel:data.maModel,
            modelId:this.form.deviceModelId,
            maCode:this.form.deviceCode,
            thisCheckTime:this.form.thisCheckTime,
            nextCheckTime:this.form.nextCheckTime,
            repairMan: this.form.repairMan,
            checkMan: this.form.checkMan,
            phone: this.form.phone,
            result:this.form.result,
          }
          if (this.form.id) {
            // 这里替换为您的实际API调用
            updateGadgetInfo(params).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 这里替换为您的实际API调用
            addWsMaInfoData(params).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        maId: null,
        deviceTypeId: null,
        deviceModelId: null,
        deviceCode: '',
        thisCheckTime: '',
        nextCheckTime: '',
        checkMan: '',
        repairMan: '',
        phone: '',
        conclusion: ''
      };
      this.deviceModelOptions = [];
      this.resetForm("form");
    },
    /** 下载模板方法 */
    async downloadTemplate() {
      this.downloadLoading = true;
      try {
        // 使用统一的下载方法，确保路径正确
        await this.download("/material/wsMaInfo/downLoad", {}, "机具检验标识信息导入模板.xlsx");
        this.$message.success("模板下载成功");
      } catch (error) {
        console.error("模板下载失败:", error);
        this.$message.error("模板下载失败，请稍后重试");
      } finally {
        this.downloadLoading = false;
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
}
</script>
<style lang="scss" scoped>
.download-template-link {
  color: #409EFF;
  cursor: pointer;
  margin-left: 10px;
  display: inline-flex;
  align-items: center;

  &:hover {
    color: #66b1ff;
    text-decoration: underline;
  }

  i {
    margin-right: 4px;
  }
}
.app-container {
  padding: 20px;
}
.el-form-item {
  margin-bottom: 22px;
}
.el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 100%;
}
.next-check-date {
  background-color: #f5f7fa;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
