<template>
  <div class="app-container">
    <!-- 商品管理 -->
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      size="default"
      label-width="0"
    >
      <!-- 表单搜索 -->
      <el-row>
        <el-col :span="6">
          <el-form-item prop="deviceName">
            <el-input
              v-model.trim="queryParams.deviceName"
              style="width: 100%"
              clearable
              placeholder="请输入装备名称"
            />
          </el-form-item>
        </el-col>

        <el-col :span="18">
          <el-form-item>
            <el-button class="primary-lease" type="primary" @click="queryTableList">
              查询
            </el-button>
            <el-button
              class="primary-lease"
              type="primary"
              @click="resetTableList"
            >
              重置
            </el-button>
            <el-button
              class="primary-lease"
              type="primary"
              @click="equipmentDeployment"
              v-if="!isView"
            >
              装备录入
            </el-button>
            <el-button
              class="primary-lease"
              type="primary"
              @click="onHandleSubmit"
              v-if="!isView"
            >
              提交申请
            </el-button>
            <el-button @click="onHandleBackList" class="primary-lease" type="primary">
              返回列表
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: auto"
      row-key="maId"
      show-overflow-tooltip
      :header-cell-style="{ background: '#00a288', color: '#fff' }"
    >
      <el-table-column label="序号" align="center" width="80" type="index"></el-table-column>
      <el-table-column align="center" label="装备名称">
        <template scope="{ row }">
          {{ `${row.deviceName}` }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="code" label="装备编号"/>
      <el-table-column align="center" prop="typeName" label="装备类目">
        <template scope="{ row }">
          <span>
            {{ row.firstName }} <span v-show="row.firstName">></span>
            {{ row.secondName }}<span v-show="row.secondName">></span>
            {{ row.thirdName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="typeName" label="装备型号"/>
      <el-table-column align="center" prop="nextCheckDate" label="下次检验日期">
        <template scope="{ row }">
          <span :style="{ backgroundColor: getUpdateTimeBgColor(row) }">{{
              row.nextCheckDate
            }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="装备状态">
        <template scope="{ row }">
          <el-tag v-if="row.maStatus == 0" size="small" type="info">草稿状态</el-tag>
          <el-tag v-if="row.maStatus == 1" size="small" type="warning">待上架</el-tag>
          <el-tag v-if="row.maStatus == 2" size="small" type="success">上架</el-tag>
          <el-tag v-if="row.maStatus == 3" size="small" type="danger">在租</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="操作"
        min-width="160px"
        align="center"
        v-if="!isView"
      >
        <template scope="{ row }">
          <el-button
            v-if="row.maStatus == 0 || row.maStatus == 1"
            size="small"
            type="primary"
            @click="editRowInfo(row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="row.maStatus == 0 || row.maStatus == 1"
            size="small"
            type="danger"
            @click="deleteRowInfo(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      @pagination="getList"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
    />


    <!-- 装备弹框 -->
    <el-dialog
      :visible.sync="dialogFormVisibleSettlein"
      :title="settleinTitle"
      width="80%"
      destroy-on-close
      :close-on-click-modal="false"
      :before-close="handleClose"
      @close="onDialogClose"
    >
      <el-row
        :gutter="20"
        class="mb8"
        style="display: flex; justify-content: flex-end; align-items: center"
      >
        <el-button type="primary" class="primary-lease" @click="closeDialogBtn">
          关闭
        </el-button>
        <el-button
          type="primary"
          class="primary-lease"
          @click="submitBtn"
          v-if="!disabledForm || isEditDisabled"
        >
          提交
        </el-button>
      </el-row>

      <TitleTip :titleText="`基本信息`"/>
      <el-form
        label-width="180px"
        ref="addAndEditFormRef"
        label-position="right"
        :model="addAndEditForm"
        :rules="equipRules"
        :disabled="disabledForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="装备名称：" prop="deviceName">
              <el-input
                autocomplete="off"
                maxlength="30"
                v-model="addAndEditForm.deviceName"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装备类目：" prop="deviceTypeList">
              <el-cascader
                v-model="addAndEditForm.deviceTypeList"
                :show-all-levels="true"
                :options="deviceTypeTree"
                :props="partTypeTreeProps"
                filterable
                clearable
                collapse-tags
                placeholder="请选择装备类目"
                ref="dialogTypeCascader"
                @change="dialogTypeChange"
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="装备单位：" prop="unitName">
              <el-input
                autocomplete="off"
                maxlength="20"
                v-model="addAndEditForm.unitName"
                clearable
                :disabled="isDisabled || isEditForm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装备品牌" prop="brand">
              <el-input
                v-model="addAndEditForm.brand"
                autocomplete="off"
                maxlength="20"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出厂日期：" prop="productionDate">
              <el-date-picker
                v-model="addAndEditForm.productionDate"
                placeholder="请选择出厂日期"
                value-format="YYYY-MM-DD"
                type="date"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁价格(天/元)：" prop="dayLeasePrice">
              <el-input
                @input="handlePriceInput"
                clearable
                maxlength="20"
                placeholder="请输入租赁价格"
                v-model="addAndEditForm.dayLeasePrice"
                :disabled="settleinTitle == '新增详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人：" prop="person">
              <el-input
                v-model="addAndEditForm.person"
                placeholder="请输入联系人"
                clearable
                maxlength="10"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话：" prop="personPhone">
              <el-input
                v-model="addAndEditForm.personPhone"
                placeholder="请输入联系电话"
                clearable
                maxlength="11"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上架数量：" prop="deviceCount">
              <el-input
                v-model="addAndEditForm.deviceCount"
                placeholder="请输入上架数量"
                type="number"
                clearable
                maxlength="10"
                :disabled="typeDisabled"
              />
            </el-form-item>
          </el-col>
          <!-- 临时录入使用 - start -->
          <el-col :span="12">
            <el-form-item label="原值：" prop="buyPrice">
              <el-input-number
                v-model="addAndEditForm.buyPrice"
                placeholder="请输入原值"
                clearable
                maxlength="20"
                :controls="false"
                align="left"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号：" prop="itemTypeModel">
              <el-input
                v-model="addAndEditForm.itemTypeModel"
                placeholder="请输入规格型号"
                clearable
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理方式：" prop="deviceType">
              <!-- 0 编码 1 数量 -->
              <el-select
                v-model="addAndEditForm.deviceType"
                placeholder="请选择管理方式"
                clearable
                style="width: 100%"
                :disabled="!isAdd"
              >
                <el-option label="编码" :value="0"/>
                <el-option label="数量" :value="1"/>
              </el-select>
              <span style="color: red"
              >说明：编码管理按一台一台管理，一台设备一个唯一编码，数量管理支持同规格型号批量录入，一般小型工器具。</span
              >
            </el-form-item>
          </el-col>
          <!-- 临时录入使用 - end -->
        </el-row>

        <!-- 9.15新增 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标准使用时间：" prop="expirationTime">
              <el-date-picker
                type="date"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                placeholder="请选择标准使用时间"
                v-model="addAndEditForm.expirationTime"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div>
          <el-row
            v-for="(item, index) in chunkedItems"
            :key="index"
            :model="item"
            class="dynamic-item"
            :gutter="20"
            style="display: flex; margin-top: 10px; justify-content: left"
          >
            <el-col v-for="(itemTemp, indexTemp) in item" :key="indexTemp" :span="12">
              <el-form-item :label="itemTemp.propertyName + '：'">
                <el-input
                  v-model="itemTemp.propertyValue"
                  placeholder="请输入"
                  maxlength="20"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div style="display: flex; align-items: center">
          <TitleTip :titleText="`装备证书信息`"/>
          <el-button
            size="mini"
            type="primary"
            @click="handleAddBack"
            style="margin-left: 20px; margin-top: 20px"
            :disabled="!addAndEditForm.deviceTypeList"
            v-if="settleinTitle == '新增装备'"
          >添加
          </el-button>
        </div>
      </el-form>

      <el-table :data="equipTableList" width="100%" height="450px" border>
        <el-table-column label="序号" type="index" width="55" align="center"/>
        <el-table-column
          prop="identifyCode"
          align="center"
          :show-overflow-tooltip="true"
          width="260"
        >
          <template #header>
            <div style="display: flex; flex-direction: column; align-items: center">
              <span>唯一标识符</span>
              <span style="font-size: 10px; color: #999">
                WHMY-DLSSJ-JSD5B-2025070101：<br/>
                公司简称首字母-设备名称首字母-设备型号-YYYYMMDD序号
              </span>
            </div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.identifyCode"
              style="width: 100%"
              placeholder="请输入唯一标识符"
              maxlength="20"
              :disabled="disabledForm"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column
          label="检修人"
          prop="checkMan"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.checkMan"
              controls-position="right"
              style="width: 100%"
              placeholder="请输入检修人"
              :disabled="disabledForm"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="检修时间"
          prop="checkDate"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.checkDate"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择"
              @change="changeDate(scope.row, scope.$index)"
              style="width: 100%"
              :disabled="disabledForm"
            ></el-date-picker>
          </template>
        </el-table-column>

        <el-table-column
          label="下次检测时间"
          prop="nextCheckDate"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.nextCheckDate"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择"
              style="width: 100%"
              @change="changeNextDate(scope.row)"
              :disabled="disabledForm"
            ></el-date-picker>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          width="100px"
          v-if="settleinTitle == '新增装备'"
        >
          <template #default="scope">
            <div
              style="
                width: 100%;
                height: 40px;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteBack(scope.$index)"
                v-show="scope.$index != 0"
              >删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 图片查看弹窗已移除 -->
  </div>
</template>

<script>
import { mapState } from 'vuex'
import TitleTip from '@/components/TitleTip/index.vue'
import {
  equipmentAddApiNew,
  equipmentEditApiNew,
  equipmentEditApi,
  removeDeviceApi,
  getDetailApi,
  updateUpDownApi,
  getCompanyListApi,
  getEquipmentTypeApi,
  getEquipmentAddIdApi,
  equipmentSubmitApiNew,
  equipmentDraftListApiNew
} from '@/api/EquipmentEntryApply/index'

export default {
  components: {
    TitleTip
  },
  props: {
    isView: {
      type: Boolean,
      default: false
    },
    orderIds: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      total: 0,
      // 查询参数
      queryParams: {
        deviceName: '',
        pageSize: 10,
        pageNum: 1,
        orderId: ''
      },
      // 设备类型树
      deviceTypeTree: [],
      partTypeTreeProps: {
        children: 'children',
        label: 'name'
      },
      // 表单相关
      dialogFormVisibleSettlein: false,
      settleinTitle: '',
      isAdd: true,
      isMaStatus: false,
      disabledForm: false,
      isEditDisabled: false,
      isViewForm: false,
      isEditForm: false,
      maId: '',
      warningDays: 0,
      companyDataList: [],
      // 装备表单数据
      addAndEditForm: {
        deviceName: '',
        deviceTypeList: [],
        deviceCount: 1,
        originaValue: '',
        itemTypeModel: '',
        deviceType: '',
        buyPrice: '',
        unitName: '',
        code: '',
        brand: '',
        typeId: '',
        companyId: '',
        productionDate: '',
        dayLeasePrice: '',
        person: '',
        personPhone: '',
        deviceWeight: '',
        checkDate: '',
        checkCycle: '',
        devInfoProperties: [],
        tableList: [],
        isZone: true,
        zoneId: '',
        expirationTime: '',
        orderId: ''
      },
      // 表单校验规则（已移除文件相关校验）
      equipRules: {
        originaValue: [
          { required: true, message: '请输入原值', trigger: 'blur' }
        ],
        buyPrice: [
          { required: true, message: '请输入原值', trigger: 'blur' }
        ],
        itemTypeModel: [
          { required: true, message: '请输入规格型号', trigger: 'blur' }
        ],
        deviceType: [
          { required: false, message: '请选择管理方式', trigger: 'change' }
        ],
        deviceName: [
          { required: true, message: '请输入装备名称', trigger: 'blur' }
        ],
        deviceTypeList: [
          { required: true, message: '请选择装备类目', trigger: 'change' }
        ],
        deviceCount: [
          { required: true, message: '请输入上架数量', trigger: 'blur' }
        ],
        unitName: [
          { required: true, message: '装备单位不可为空', trigger: 'blur' }
        ],
        brand: [
          { required: true, message: '请输入装备品牌', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入装备编号', trigger: 'change' }
        ],
        companyId: [
          { required: true, message: '请选择所属公司', trigger: 'change' }
        ],
        productionDate: [
          { required: true, message: '请选择出厂日期', trigger: 'change' }
        ],
        dayLeasePrice: [
          { required: true, message: '请输入日租金', trigger: 'blur' }
        ],
        expirationTime: [
          { required: true, trigger: 'change', message: '请选择标准使用时间' }
        ],
        person: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        checkDate: [
          { required: true, message: '校验日期不能为空', trigger: 'blur' }
        ],
        checkCycle: [
          { required: true, message: '校验周期不能为空', trigger: 'blur' }
        ],
        personPhone: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      // 其他状态
      countDisabled: false,
      dialogTypeCascader: null,
      isDisabled: false,
      typeDisabled: false,
      descriptionFormList: [
        {
          newId: Date.now()
        }
      ],
      descriptionFormRefList: [],
      descriptionRules: {
        identifyCode: [
          { required: true, message: '请填写装备唯一标识符', trigger: 'blur' }
        ]
      },
      propertyNames: [],
      options: [],
      orderId: '',
      chunkedItems: [],
      equipTableList: [
        {
          id: '',
          identifyCode: '',
          checkMan: '',
          checkDate: '',
          nextCheckDate: ''
        }
      ],
      headerInfo: {
        Authorization: 'Bearer ' + this.$store.state.token
      }
    }
  },
  computed: {
    ...mapState(['token'])
  },
  watch: {
    propertyNames: {
      handler(val) {
        this.chunkedItems = []
        for (let i = 0; i < val.length; i += 2) {
          this.chunkedItems.push(val.slice(i, i + 2))
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 获取列表数据
    async getList() {
      try {
        const res = await equipmentDraftListApiNew(this.queryParams)
        this.tableData = res.rows
        this.total = res.total
      } catch (error) {
        console.error('获取列表失败:', error)
      }
    },
    // 查询表格数据
    queryTableList() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置表格查询
    resetTableList() {
      this.$refs.queryFormRef.resetFields()
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 打开入驻弹框
    equipmentDeployment(row) {
      this.dialogFormVisibleSettlein = true
      this.isAdd = !row
      this.settleinTitle = row ? '装备编辑' : '新增装备'

      this.getTypeTreeData()

      if (row) {
        this.getDetailData(row)
        this.isEditForm = true
      } else {
        this.addAndEditForm = {
          deviceName: '',
          deviceTypeList: [],
          deviceCount: 1,
          originaValue: '',
          itemTypeModel: '',
          deviceType: '',
          buyPrice: '',
          unitName: '',
          code: '',
          brand: '',
          typeId: '',
          companyId: '',
          productionDate: '',
          dayLeasePrice: '',
          person: '',
          personPhone: '',
          deviceWeight: '',
          checkDate: '',
          checkCycle: '',
          devInfoProperties: [],
          tableList: [],
          isZone: true,
          zoneId: '',
          expirationTime: '',
          orderId: this.orderId || ''
        }
        this.equipTableList = [
          {
            id: '',
            identifyCode: '',
            checkMan: '',
            checkDate: '',
            nextCheckDate: ''
          }
        ]
        this.propertyNames = []
        this.isEditForm = false
      }
    },
    // 编辑按钮
    editRowInfo(row) {
      this.isAdd = false
      this.settleinTitle = '装备编辑'
      this.getDetailData(row)
      this.isMaStatus = true
      this.disabledForm = false
      this.isEditDisabled = true
      this.isViewForm = false
      this.isEditForm = true
    },
    // 查看按钮
    previewRowInfo(row) {
      this.isAdd = false
      this.settleinTitle = '装备详情'
      this.getDetailData(row)
      this.disabledForm = true
      this.isEditDisabled = false
      this.isViewForm = true
      this.isEditForm = false
    },
    // 删除按钮
    async deleteRowInfo(row) {
      ElMessageBox.confirm('是否确定删除？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeDeviceApi([row.maId])
        })
        .then(res => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            this.getList()
          }
        })
        .catch(() => {
        })
    },
    // 获取详情接口
    async getDetailData(row) {
      await this.getTypeTreeData()
      const { data: res } = await getDetailApi(row.maId)
      const {
        deviceName,
        deviceCount,
        originaValue,
        itemTypeModel,
        deviceType,
        buyPrice,
        unitName,
        code,
        brand,
        typeId,
        companyId,
        productionDate,
        dayLeasePrice,
        person,
        personPhone,
        deviceWeight,
        checkDate,
        checkCycle,
        devInfoProperties,
        tableList,
        maintenanceAlarmDay,
        isZone,
        zoneId,
        expirationTime
      } = res

      this.addAndEditForm = {
        ...this.addAndEditForm,
        deviceName,
        deviceCount,
        originaValue,
        itemTypeModel,
        deviceType,
        buyPrice,
        unitName,
        code,
        brand,
        typeId,
        companyId,
        productionDate,
        dayLeasePrice,
        person,
        personPhone,
        deviceWeight,
        checkDate,
        checkCycle,
        devInfoProperties,
        tableList,
        isZone,
        zoneId,
        expirationTime,
        maId: row.maId
      }

      this.descriptionFormList = [
        {
          newId: Date.now()
        }
      ]

      this.options = []
      this.addAndEditForm.deviceTypeList = this.getSelectId(this.deviceTypeTree, this.addAndEditForm.typeId)
      this.warningDays = this.addAndEditForm.maintenanceAlarmDay
      this.propertyNames = this.addAndEditForm.devInfoProperties || []

      this.equipTableList = []
      if (this.isEditForm) {
        if (this.addAndEditForm.tableList) {
          this.addAndEditForm.tableList.forEach(item => {
            this.equipTableList.push({
              id: item.id,
              identifyCode: item.identifyCode,
              checkMan: item.checkMan,
              checkDate: item.checkDate,
              nextCheckDate: item.nextCheckDate
            })
          })
        } else {
          this.equipTableList = [
            {
              id: '',
              identifyCode: '',
              checkMan: '',
              checkDate: '',
              nextCheckDate: ''
            }
          ]
        }
      } else {
        if (this.addAndEditForm.tableList) {
          this.addAndEditForm.tableList.forEach(item => {
            this.equipTableList.push({
              id: item.id,
              identifyCode: item.identifyCode,
              checkMan: item.checkMan,
              checkDate: item.checkDate,
              nextCheckDate: item.nextCheckDate
            })
          })
        } else {
          this.equipTableList = []
        }
      }

      this.dialogFormVisibleSettlein = true
    },
    // 获取选中的ID
    getSelectId(tree, id) {
      let result = []
      const findNode = (nodes, targetId) => {
        for (const node of nodes) {
          if (node.id === targetId) {
            result.unshift(node.id)
            return true
          }
          if (node.children && node.children.length > 0) {
            if (findNode(node.children, targetId)) {
              result.unshift(node.id)
              return true
            }
          }
        }
        return false
      }
      findNode(tree, id)
      return result
    },
    // 上下架（批量）
    handleUpdateUpDown(row, maStatus) {
      ElMessageBox.confirm('是否确定操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let maIds = []
          if (!row) {
            maIds = this.ids.map(item => item.maId)
          } else {
            maIds.push(row.maId)
          }
          if (maIds.length === 0) {
            ElMessage({ type: 'error', message: '请选择要操作的数据' })
            return
          }
          return updateUpDownApi({ maIds, maStatus })
        })
        .then(res => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: '操作成功'
            })
            this.getList()
          }
        })
        .catch(() => {
        })
    },
    // 获取所属公司下拉数据
    async getCompanyList() {
      const res = await getCompanyListApi()
      this.companyDataList = res.data
    },
    // 获取设备类型树
    async getTypeTreeData() {
      const res = await getEquipmentTypeApi()
      this.deviceTypeTree = res.data
    },
    // 装备类目-change
    async dialogTypeChange() {
      this.options = []
      const cascader = this.$refs.dialogTypeCascader
      const deviceTypeList = cascader.getCheckedNodes()

      if (deviceTypeList.length > 0) {
        this.warningDays = deviceTypeList[0].data.maintenanceAlarmDay

        if (deviceTypeList[0].data.deviceType === 0) {
          this.addAndEditForm.deviceCount = 1
          this.typeDisabled = true
        } else {
          this.addAndEditForm.deviceCount = 1
          this.typeDisabled = false
        }

        if (!deviceTypeList[0].data.maTypeProperties) {
          this.propertyNames = []
        } else {
          this.propertyNames = []
          deviceTypeList[0].data.maTypeProperties.forEach(item => {
            this.propertyNames.push({ propertyName: item.propertyName, propertyValue: '' })
            this.options.push({ label: item.propertyName, value: item.propertyName })
          })
        }

        this.isDisabled = true
        this.addAndEditForm.unitName = deviceTypeList[0].data.unitName
        this.addAndEditForm.dayLeasePrice = deviceTypeList[0].data.leasePrice
        this.$refs.addAndEditFormRef.clearValidate(['unitName', 'dayLeasePrice'])

        this.equipTableList = [
          {
            id: '',
            identifyCode: '',
            checkMan: '',
            checkDate: '',
            nextCheckDate: ''
          }
        ]
      }
    },
    // 价格输入处理
    handlePriceInput(v) {
      this.addAndEditForm.dayLeasePrice = v.replace(/[^\d.]/g, '')
    },
    // 弹框保存提交
    submitBtn() {
      this.submitFun(this.isEditForm ? 3 : 1)
    },
    // 提交函数
    submitFun(type) {
      this.$refs.addAndEditFormRef.validate(async valid => {
        if (valid) {
          let isDescription = false

          this.addAndEditForm.tableList = this.equipTableList

          if (type !== 2 && type !== 4) {
            for (let i = 0; i < this.addAndEditForm.tableList.length; i++) {
              const row = this.addAndEditForm.tableList[i]
              for (const key in row) {
                if (
                  row.hasOwnProperty(key) &&
                  (row[key] === null || row[key] === '' || (row[key] && row[key].length === 0)) &&
                  key !== 'id'
                ) {
                  let fieldName = ''
                  switch (key) {
                    case 'identifyCode':
                      fieldName = '唯一标识符'
                      break
                    case 'checkMan':
                      fieldName = '检修人'
                      break
                    case 'checkDate':
                      fieldName = '检修日期'
                      break
                    case 'nextCheckDate':
                      fieldName = '下次检修日期'
                      break
                    default:
                      fieldName = key
                  }
                  ElMessage({
                    type: 'error',
                    message: `第 ${i + 1} 行的 ${fieldName} 字段不能为空`
                  })
                  isDescription = true
                  return
                }
              }
            }
          }

          if (isDescription) return

          this.addAndEditForm.devInfoProperties = this.propertyNames
          if (this.addAndEditForm.deviceTypeList.length > 0) {
            this.addAndEditForm.typeId = this.addAndEditForm.deviceTypeList[this.addAndEditForm.deviceTypeList.length - 1]
          }

          let SEND_FUN_API = null
          if (type === 1) {
            SEND_FUN_API = equipmentAddApiNew
            this.addAndEditForm.maStatus = 1
            this.addAndEditForm.type = 1
          }
          if (type === 2) {
            SEND_FUN_API = equipmentAddApiNew
            this.addAndEditForm.maStatus = 0
            this.addAndEditForm.type = 2
          }
          if (type === 3) {
            SEND_FUN_API = equipmentEditApiNew
            this.addAndEditForm.maStatus = 1
            this.addAndEditForm.type = 3
          }
          if (type === 4) {
            SEND_FUN_API = equipmentEditApi
            this.addAndEditForm.maStatus = 0
            this.addAndEditForm.type = 4
          }

          try {
            if (!this.orderId) {
              const result = await getEquipmentAddIdApi()
              this.orderId = result.data.id
              this.addAndEditForm.orderId = this.orderId
              this.queryParams.orderId = this.orderId

              const res = await SEND_FUN_API(this.addAndEditForm)
              if (res.code === 200) {
                this.handleSuccessSubmit()
              }
            } else {
              this.addAndEditForm.orderId = this.orderId
              this.queryParams.orderId = this.orderId

              const res = await SEND_FUN_API(this.addAndEditForm)
              if (res.code === 200) {
                this.handleSuccessSubmit()
              }
            }
          } catch (error) {
            console.error('提交失败:', error)
          }
        } else {
          console.log('校验失败')
        }
      })
    },
    // 提交成功处理
    handleSuccessSubmit() {
      ElMessage({
        type: 'success',
        message: '保存成功',
        duration: 1000
      })
      this.propertyNames = []
      this.dialogFormVisibleSettlein = false
      this.getList()
    },
    // 保存草稿
    saveTemp() {
      this.submitFun(this.isMaStatus ? 4 : 2)
    },
    // 关闭按钮
    closeDialogBtn() {
      this.getTypeTreeData()
      this.dialogFormVisibleSettlein = false
    },
    // 关闭对话框
    handleClose(done) {
      done()
      this.propertyNames = []
      this.dialogFormVisibleSettlein = false
    },
    // 添加装备证书行
    handleAddBack() {
      const obj = {
        identifyCode: '',
        checkMan: '',
        checkDate: '',
        nextCheckDate: ''
      }
      this.equipTableList.push(obj)
    },
    // 删除行
    handleDeleteBack(index) {
      this.equipTableList.splice(index, 1)
    },
    // 日期变更
    changeDate(row, index) {
      const currentDate = new Date(row.checkDate)
      const nextYearDate = dayjs(currentDate).add(1, 'year').subtract(1, 'day').toDate()
      this.equipTableList[index].nextCheckDate = dayjs(nextYearDate).format('YYYY-MM-DD')
    },
    // 下次日期变更
    changeNextDate(row) {
      if (row.checkDate && row.nextCheckDate) {
        if (dayjs(row.checkDate).isAfter(row.nextCheckDate)) {
          ElMessage({
            type: 'error',
            message: '下次检修时间不能早于检修时间'
          })
          row.nextCheckDate = ''
        }
      }
    },
    // 获取更新时间背景色
    getUpdateTimeBgColor(row) {
      const checkDate = new Date()
      const nextCheckDate = new Date(row.nextCheckDate)

      const diffTime = Math.abs(nextCheckDate - checkDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      if (checkDate < nextCheckDate && diffDays <= 30) {
        return '#FFFFCC'
      } else if (checkDate > nextCheckDate) {
        return '#FFCCCC'
      }
      return ''
    },
    // 返回列表
    onHandleBackList() {
      this.$emit('backList')
    },
    // 提交申请
    async onHandleSubmit() {
      if (!this.queryParams.orderId) {
        ElMessage({
          message: '请先添加设备',
          type: 'error'
        })
        return
      }

      const res = await equipmentSubmitApiNew({ id: this.queryParams.orderId, status: 0 })
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交成功'
        })
        this.$emit('backList')
      }
    }
  },
  mounted() {
    this.getCompanyList()
    this.getTypeTreeData()

    if (this.orderIds) {
      this.queryParams.orderId = this.orderIds
      this.addAndEditForm.orderId = this.orderIds
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  // margin: 15px 0;
}

.title {
  margin: 10px;
  margin-left: 20px;
  display: flex;
  align-items: center;
}

.title-sign {
  display: inline-block;
  width: 4px;
  height: 16px;
  background: #00a288;
}

.title-text {
  font-weight: 700;
  margin-left: 10px;
}

.tipBox {
  color: red;
  font-size: 12px;
  margin-left: 20px;
}

:deep .el-form--inline .el-form-item {
  margin-right: 6px;
  width: 95%;
}

:deep .upload-tip .el-form-item__label {
  color: transparent;
}

.app-container-content {
  :deep .el-dialog {
    display: flex !important;
    flex-direction: column !important;
    margin: 0 !important;
    position: absolute !important;
    top: 5vh !important;
    left: 50% !important;
    transform: translate(-50%, 0%) !important;
    height: 90vh;

    .el-dialog__body {
      flex: 1;
      overflow-y: scroll !important;

      .el-table__header-wrapper .el-checkbox {
        display: none !important;
      }
    }

    .dialog-content {
      padding: 20px;
    }
  }
}

:deep .el-button--primary {
  background-color: #3cb4a6 !important;
  border-color: #3cb4a6 !important;
}

:deep .el-button--primary:hover,
:deep .el-button--primary:focus,
:deep .el-button--primary:active {
  background-color: #2fa18f !important;
  border-color: #2fa18f !important;
}

:deep .el-input-number .el-input__inner {
  text-align: left !important;
}
</style>
