<template>
  <div class="device-ledger-panel">
    <div class="device-ledger-panel__header">
      <div class="device-ledger-panel__title">{{ dialogTitle }}</div>
      <el-button text @click="closeForm">
        <Icon icon="ep:close" />
      </el-button>
    </div>
    <div
      class="device-ledger-dialog"
      v-loading="formLoading || fileUploading"
      :element-loading-text="t('common.loading')"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="110px">
        <el-row :gutter="16">
          <!-- <el-col :span="24">
          <el-form-item label="璧勪骇缂栧彿" prop="id">
            <el-input v-model="formData.id" placeholder="绯荤粺鑷姩鐢熸垚" disabled />
          </el-form-item>
        </el-col> -->
          <el-col :span="8">
            <el-form-item :label="t('EquipmentManagement.EquipmentLedger.images')" prop="images">
              <UploadImg style="height: 100px" v-model="formData.images" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.deviceCode')"
              prop="deviceCode"
            >
              <el-row :gutter="20" style="width: 100%">
                <el-col :xs="18" :sm="18" :md="16" :lg="14" :xl="10">
                  <el-input
                    v-model="formData.deviceCode"
                    :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceCode')"
                    :disabled="Boolean(formData.isCode) || formType === 'update'"
                  />
                </el-col>
                <el-col :xs="24" :sm="6" :md="4" :lg="3" :xl="2">
                  <div>
                    <el-switch
                      v-model="formData.isCode"
                      :disabled="formType === 'update'"
                      @change="handleCodeAutoChange"
                    />
                  </div>
                </el-col>
              </el-row>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  :label="t('EquipmentManagement.EquipmentLedger.deviceName')"
                  prop="deviceName"
                  required
                >
                  <el-input
                    v-model="formData.deviceName"
                    :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceName')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="t('EquipmentManagement.EquipmentLedger.deviceType')"
                  prop="deviceType"
                  required
                >
                  <el-tree-select
                    v-model="formData.deviceType"
                    :data="deviceTypeTree"
                    :props="treeSelectProps"
                    check-strictly
                    default-expand-all
                    value-key="id"
                    :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceType')"
                    class="!w-full"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  :label="t('EquipmentManagement.EquipmentLedger.deviceSpec')"
                  prop="deviceSpec"
                >
                  <el-input
                    v-model="formData.deviceSpec"
                    :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceSpec')"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="isScheduledEnabled" :span="12">
                <el-form-item
                  :label="t('EquipmentManagement.EquipmentLedger.ratedCapacity')"
                  prop="ratedCapacity"
                  :required="isScheduledEnabled"
                >
                  <el-input-number
                    v-model="formData.ratedCapacity"
                    :min="0"
                    :precision="0"
                    controls-position="right"
                    class="!w-full"
                    :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderRatedCapacity')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.factoryEntryDate')"
              prop="factoryEntryDate"
            >
              <el-date-picker
                v-model="formData.factoryEntryDate"
                type="date"
                value-format="YYYY-MM-DD"
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderFactoryEntryDate')"
                class="!w-full"
              />
            </el-form-item>
          </el-col>
          <!--        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceModel')" prop="deviceModel">
            <el-input v-model="formData.deviceModel" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceModel')" />
          </el-form-item>
        </el-col>-->

          <!-- <el-col :span="12">
          <el-form-item label="渚涘簲鍟? prop="supplier">
            <el-input v-model="formData.supplier" placeholder="璇疯緭鍏ヤ緵搴斿晢" /> -->
          <!--
        <el-select v-model="formData.supplier" placeholder="璇烽€夋嫨渚涘簲鍟? clearable filterable class="!w-full">
          <el-option v-for="item in supplierOptions" :key="item" :label="item" :value="item" />
        </el-select>
        -->
          <!-- </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="鎵€灞炶溅闂? prop="workshop">
          <el-input v-model="formData.workshop" placeholder="璇疯緭鍏ユ墍灞炶溅闂? /> -->
          <!--
        <el-tree-select
          v-model="formData.workshop"
          :data="deptTree"
          :props="treeSelectProps"
          check-strictly
          default-expand-all
          value-key="id"
          placeholder="璇烽€夋嫨鎵€灞炶溅闂?
          class="!w-full"
        />
        -->
          <!-- </el-form-item>
      </el-col> -->

          <el-col :span="8">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.outgoingTime')"
              prop="outgoingTime"
            >
              <el-date-picker
                v-model="formData.outgoingTime"
                type="date"
                value-format="YYYY-MM-DD"
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderOutgoingTime')"
                class="!w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.isSchedueld')"
              prop="isScheduled"
            >
              <el-switch
                v-model="formData.isScheduled"
                :active-value="1"
                :inactive-value="0"
                :active-text="t('EquipmentManagement.EquipmentLedger.yes')"
                :inactive-text="t('EquipmentManagement.EquipmentLedger.no')"
                inline-prompt
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.deviceBrand')"
              prop="deviceBrand"
            >
              <el-input
                v-model="formData.deviceBrand"
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceBrand')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="t('EquipmentManagement.EquipmentLedger.sn')" prop="sn">
              <el-input
                v-model="formData.sn"
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderSn')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.deviceLocation')"
              prop="deviceLocation"
            >
              <el-input
                v-model="formData.deviceLocation"
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceLocation')"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
          <el-form-item label="鎵€灞炵郴缁熺粍缁? prop="systemOrg">
            <el-input v-model="formData.systemOrg" placeholder="璇疯緭鍏ユ墍灞炵郴缁熺粍缁? /> -->
          <!--
        <el-tree-select
          v-model="formData.systemOrg"
          :data="deptTree"
          :props="treeSelectProps"
          check-strictly
          default-expand-all
          value-key="id"
          placeholder="璇烽€夋嫨閮ㄩ棬"
          class="!w-full"
        />
        -->
          <!-- </el-form-item>
      </el-col> -->

          <el-col :span="12">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.deviceManagerName')"
              prop="deviceManagerIds"
            >
              <el-select
                v-model="formData.deviceManagerIds"
                multiple
                filterable
                clearable
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceManagerIds')"
                class="!w-full"
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="t('EquipmentManagement.EquipmentLedger.dvName')" prop="dvId">
              <el-input
                :model-value="iotDeviceDisplay"
                readonly
                clearable
                class="device-ledger-selection-input"
                :placeholder="t('EquipmentManagement.EquipmentLedger.dvId')"
                @clear="clearIotDevice"
                @click="openIotDeviceDialog"
              >
                <template #append>
                  <el-button @click.stop="openIotDeviceDialog">
                    <Icon icon="ep:search" />
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.criticalComponent')"
              prop="componentIds"
            >
              <el-input
                :model-value="criticalComponentDisplay"
                readonly
                clearable
                class="device-ledger-selection-input"
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderComponentIds')"
                @clear="clearCriticalComponent"
                @click="openCriticalComponentDialog"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item
              :label="t('EquipmentManagement.EquipmentLedger.sparePart')"
              prop="beijianIds"
            >
              <el-input
                :model-value="beijianDisplay"
                readonly
                clearable
                class="device-ledger-selection-input"
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderBeijianIds')"
                @clear="clearBeijian"
                @click="openBeijianDialog"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item :label="t('EquipmentManagement.EquipmentLedger.fileUrl')" prop="fileUrl">
              <UploadFile
                :is-show-tip="false"
                v-model="formData.fileUrl"
                :limit="9"
                @uploading-change="handleFileUploadingChange"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="formType === 'update'" :span="24">
            <el-form-item :label="t('EquipmentManagement.EquipmentLedger.qrcode')" prop="qrcodeUrl">
              <QrcodeActionCard
                :image-url="formData.qrcodeUrl"
                :print-id="formData.id"
                :print-template-type="2"
                :print-title="`${formData.deviceName || 'Device'} QR Code`"
                :print-paper-width="80"
                :print-paper-height="80"
                :print-max-width="220"
                :empty-text="t('EquipmentManagement.EquipmentLedger.qrcodeEmpty')"
                :error-text="t('EquipmentManagement.EquipmentLedger.qrcodeLoadError')"
                :refresh-url="getQrcodeRefreshUrl()"
                :refresh-disabled="!formData.id || !formData.deviceCode"
                refresh-confirm-text="纭鍒锋柊璇ヨ澶囦簩缁寸爜鍚楋紵"
                :template-json="formData.templateJson"
                :print-data="buildPrintData()"
                @refresh-success="handleQrcodeRefreshSuccess"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item :label="t('EquipmentManagement.EquipmentLedger.remark')" prop="remark">
              <el-input
                v-model="formData.remark"
                :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderRemark')"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="device-ledger-footer">
      <el-button @click="closeForm">{{ t('common.cancel') }}</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading || fileUploading">{{
        t('common.ok')
      }}</el-button>
    </div>
  </div>

  <el-dialog
    v-model="iotDeviceDialogVisible"
    :title="t('EquipmentManagement.EquipmentLedger.dvName')"
    width="1000px"
    class="device-ledger-device-dialog"
    append-to-body
  >
    <el-form
      ref="iotDeviceQueryFormRef"
      :model="iotDeviceQueryParams"
      :inline="true"
      min-label-width="68px"
      class="-mb-15px"
      style="margin-bottom: 10px"
    >
      <el-form-item :label="t('DataCollection.Device.deviceCode')" prop="deviceCode">
        <el-input
          v-model="iotDeviceQueryParams.deviceCode"
          :placeholder="t('DataCollection.Device.placeholderDeviceCode')"
          clearable
          class="!w-240px"
          @keyup.enter="handleIotDeviceQuery"
        />
      </el-form-item>
      <el-form-item :label="t('DataCollection.Device.deviceName')" prop="deviceName">
        <el-input
          v-model="iotDeviceQueryParams.deviceName"
          :placeholder="t('DataCollection.Device.placeholderDeviceName')"
          clearable
          class="!w-240px"
          @keyup.enter="handleIotDeviceQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleIotDeviceQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.query') }}
        </el-button>
        <el-button @click="resetIotDeviceQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
      </el-form-item>
    </el-form>
    <ContentWrap>
      <el-table
        v-loading="iotDeviceLoading"
        :data="iotDeviceList"
        :stripe="true"
        :show-overflow-tooltip="true"
        row-key="id"
        class="device-ledger-device-table"
        :row-class-name="getIotDeviceRowClassName"
        @row-click="handleIotDeviceRowClick"
      >
        <el-table-column width="56" align="center">
          <template #default="scope">
            <el-radio
              :model-value="iotDeviceDraftId"
              :label="scope.row.id"
              :disabled="!isIotDeviceSelectable(scope.row)"
              @change="selectIotDevice(scope.row)"
              @click.stop
            >
              <span></span>
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column
          :label="t('DataCollection.Device.deviceCode')"
          align="left"
          prop="deviceCode"
          min-width="160"
        />
        <el-table-column
          :label="t('DataCollection.Device.deviceName')"
          align="left"
          prop="deviceName"
          min-width="180"
        />
        <el-table-column
          label="已绑定的设备台账名称"
          align="left"
          prop="boundLedgerName"
          min-width="180"
        />
        <el-table-column
          :label="t('DataCollection.Device.operatingStatus')"
          align="center"
          prop="operatingStatus"
          width="120"
        >
          <template #default="scope">
            <el-tag size="small" type="info">{{ scope.row.operatingStatus || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="t('DataCollection.Device.protocol')"
          align="center"
          prop="protocol"
          width="130"
        >
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.IOT_PROTOCOL" :value="scope.row.protocol" />
          </template>
        </el-table-column>
        <!-- <el-table-column
          :label="t('DataCollection.Device.isEnable')"
          align="center"
          prop="isEnable"
          width="110"
        >
          <template #default="scope">
            <el-tag :type="isIotDeviceEnabled(scope.row) ? 'success' : 'info'" size="small">
              {{ isIotDeviceEnabled(scope.row) ? t('EquipmentManagement.EquipmentLedger.statusEnabled') : t('EquipmentManagement.EquipmentLedger.statusDisabled') }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column
          :label="t('DataCollection.Device.collectionTime')"
          align="center"
          prop="collectionTime"
          min-width="170"
        />
      </el-table>
      <div class="device-ledger-dialog-pagination">
        <Pagination
          :total="iotDeviceTotal"
          v-model:page="iotDeviceQueryParams.pageNo"
          v-model:limit="iotDeviceQueryParams.pageSize"
          @pagination="getIotDeviceList"
        />
      </div>
    </ContentWrap>
    <template #footer>
      <div class="device-ledger-dialog-footer">
        <el-button @click="iotDeviceDialogVisible = false">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="confirmIotDeviceDialog">{{ t('common.ok') }}</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="criticalComponentDialogVisible"
    :title="t('EquipmentManagement.EquipmentLedger.gjTitle')"
    width="1200px"
    class="device-ledger-transfer-dialog"
    append-to-body
  >
    <!--    <div class="device-ledger-transfer">
          <el-transfer
            v-model="criticalComponentDraft"
            :data="criticalComponentTransferData"
            filterable
            :filter-placeholder="t('EquipmentManagement.EquipmentLedger.placeholderComponentIds')"
          />
        </div>-->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      min-label-width="68px"
      style="margin-bottom: 10px"
    >
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.code')" prop="code">
        <el-input
          v-model="queryParams.code"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item
        :label="t('EquipmentManagement.EquipmentKeyItems.description')"
        prop="description"
      >
        <el-input
          v-model="queryParams.description"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderDescription')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.query') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
      </el-form-item>
    </el-form>
    <ContentWrap>
      <el-table
        ref="multipleTableRef"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        class="no-select-all"
        @selection-change="handleSelectionChange"
        @select="handleSelect"
        @select-all="handleSelectAll"
        row-key="id"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column
          :label="t('EquipmentManagement.EquipmentKeyItems.code')"
          align="center"
          prop="code"
          min-width="140"
          sortable
        />
        <el-table-column
          :label="t('EquipmentManagement.EquipmentKeyItems.name')"
          align="center"
          prop="name"
          min-width="140"
          sortable
        />
        <el-table-column
          :label="t('EquipmentManagement.EquipmentKeyItems.description')"
          align="center"
          prop="description"
          min-width="180"
        />
        <!--        <el-table-column :label="t('EquipmentManagement.EquipmentKeyItems.count')" align="center" prop="count"
          min-width="180" />-->
        <el-table-column
          :label="t('EquipmentManagement.EquipmentKeyItems.remark')"
          align="center"
          prop="remark"
          min-width="180"
        />
        <el-table-column
          :label="t('EquipmentManagement.EquipmentKeyItems.createTime')"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180"
          sortable
        />
      </el-table>

      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
    <template #footer>
      <el-button @click="criticalComponentDialogVisible = false">{{
        t('common.cancel')
      }}</el-button>
      <el-button type="primary" @click="confirmCriticalComponentDialog">{{
        t('common.ok')
      }}</el-button>
    </template>
  </el-dialog>

  <el-dialog
    v-model="beijianDialogVisible"
    :title="t('EquipmentManagement.EquipmentLedger.bjTitle')"
    width="1000px"
    class="device-ledger-transfer-dialog"
    append-to-body
  >
    <!--    <div class="device-ledger-transfer">
      <el-transfer
        v-model="beijianDraft"
        :data="beijianTransferData"
        filterable
        :filter-placeholder="t('EquipmentManagement.EquipmentLedger.placeholderBeijianIds')"
      />
    </div>-->
    <!-- 鍒楄〃 -->
    <el-form
      class="-mb-15px"
      :model="bjQueryParams"
      ref="bjQueryFormRef"
      :inline="true"
      min-label-width="68px"
      style="margin-bottom: 10px"
    >
      <el-form-item :label="t('SparePartsManagement.SpareInfo.code')" prop="barCode">
        <el-input
          v-model="bjQueryParams.barCode"
          :placeholder="t('SparePartsManagement.SpareInfo.placeholderCode')"
          clearable
          @keyup.enter="bjHandleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('SparePartsManagement.SpareInfo.name')" prop="name">
        <el-input
          v-model="bjQueryParams.name"
          :placeholder="t('SparePartsManagement.SpareInfo.placeholderName')"
          clearable
          @keyup.enter="bjHandleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="bjHandleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.query') }}
        </el-button>
        <el-button @click="bjResetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
      </el-form-item>
    </el-form>
    <ContentWrap>
      <el-table
        ref="bjMultipleTableRef"
        v-loading="loading"
        :data="bjList"
        :stripe="true"
        class="no-select-all"
        @selection-change="bjHandleSelectionChange"
        @select="bjHandleSelect"
        @select-all="bjHandleSelectAll"
        :show-overflow-tooltip="true"
        row-key="id"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column
          :label="t('SparePartsManagement.SpareInfo.code')"
          align="center"
          prop="barCode"
          width="240px"
          sortable
        />
        <el-table-column
          :label="t('SparePartsManagement.SpareInfo.name')"
          align="left"
          prop="name"
          width="220px"
          sortable
        />
        <el-table-column
          :label="t('SparePartsManagement.SpareInfo.unit')"
          align="center"
          prop="unitName"
          sortable
        />
        <el-table-column
          :label="t('SparePartsManagement.SpareInfo.status')"
          align="center"
          prop="status"
          sortable
        >
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column
          :label="t('SparePartsManagement.SpareInfo.createTime')"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
          sortable
        />
      </el-table>
      <!-- 鍒嗛〉 -->
      <Pagination
        :total="bjTotal"
        v-model:page="bjQueryParams.pageNo"
        v-model:limit="bjQueryParams.pageSize"
        @pagination="bjGetList"
      />
    </ContentWrap>
    <template #footer>
      <el-button @click="beijianDialogVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" @click="confirmBeijianDialog">{{ t('common.ok') }}</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { DeviceLedgerApi, DeviceLedgerVO } from '@/api/mes/deviceledger'
import { CriticalComponentApi, CriticalComponentVO } from '@/api/mes/criticalComponent'
import { DeviceTypeApi, DeviceTypeTreeVO } from '@/api/mes/devicetype'
import { getSimpleUserList, UserVO } from '@/api/system/user'
import { formatDate } from '@/utils/formatTime'
import type { FormRules } from 'element-plus'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { DeviceApi, DeviceVO } from '@/api/iot/device'
import QrcodeActionCard from '@/components/QrcodeActionCard/index.vue'
import { dateFormatter } from '@/utils/formatTime'
import { ref } from 'vue'
import { ElTable } from 'element-plus'
import { DICT_TYPE } from '@/utils/dict'
/** 璁惧绫诲瀷 琛ㄥ崟 */
defineOptions({ name: 'DeviceLedgerForm' })
const queryFormRef = ref()
const bjQueryFormRef = ref()
const iotDeviceQueryFormRef = ref()
const { t } = useI18n() // 鍥介檯鍖?
const message = useMessage() // 娑堟伅寮圭獥
const loading = ref(true)
const total = ref(0)
const bjTotal = ref(0)
const selectedIds = ref<number[]>([])
const bjSelectedIds = ref<number[]>([])
const dialogTitle = ref('') // 寮圭獥鐨勬爣棰?
const formLoading = ref(false) // 琛ㄥ崟鐨勫姞杞戒腑锛?锛変慨鏀规椂鐨勬暟鎹姞杞斤紱2锛夋彁浜ょ殑鎸夐挳绂佺敤
const fileUploading = ref(false)
const formType = ref('') // 琛ㄥ崟鐨勭被鍨嬶細create - 鏂板锛泆pdate - 淇敼
const iotDeviceLoading = ref(false)
const iotDeviceDialogVisible = ref(false)
const iotDeviceList = ref<DeviceVO[]>([])
const iotDeviceTotal = ref(0)
const iotDeviceSelectedLabel = ref('')
const iotDeviceDraftId = ref<number | undefined>()
const iotDeviceDraftRow = ref<DeviceVO | undefined>()
const list = ref<CriticalComponentVO[]>([])
const bjList = ref<ProductVO[]>([])
const selectedRows = ref<any[]>([]) // 瀛樺偍鎵€鏈夐€変腑鐨勮
const bjSelectedRows = ref<any[]>([]) // 瀛樺偍鎵€鏈夐€変腑鐨勮
// 琛ㄦ牸寮曠敤
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const bjMultipleTableRef = ref<InstanceType<typeof ElTable>>()
const parseIdsValue = (value: any): number[] => {
  if (!value) return []
  if (Array.isArray(value)) return value.map((v) => Number(v)).filter((v) => !Number.isNaN(v))
  return String(value)
    .split(',')
    .map((v) => Number(v.trim()))
    .filter((v) => !Number.isNaN(v))
}

const normalizeNumberish = (value: any): number | undefined => {
  if (value === null || value === undefined || value === '') return undefined
  if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
  if (typeof value === 'string') {
    const trimmed = value.trim()
    if (!trimmed) return undefined
    const n = Number(trimmed)
    return Number.isFinite(n) ? n : undefined
  }
  return undefined
}

const normalizeYmd = (value: any): string | undefined => {
  if (value === null || value === undefined || value === '') return undefined
  if (typeof value === 'string') {
    const trimmed = value.trim()
    const matched = trimmed.match(/^(\d{4}-\d{2}-\d{2})/)
    if (matched?.[1]) return matched[1]
    const parsed = Date.parse(trimmed)
    if (!Number.isNaN(parsed)) return formatDate(new Date(parsed), 'YYYY-MM-DD')
    return trimmed
  }
  if (typeof value === 'number') return formatDate(new Date(value), 'YYYY-MM-DD')
  if (value instanceof Date) return formatDate(value, 'YYYY-MM-DD')
  return formatDate(new Date(value), 'YYYY-MM-DD')
}

const normalizeFileUrlAsJsonArrayString = (value: any): string | undefined => {
  if (value === null || value === undefined || value === '') return undefined
  if (typeof value === 'string') {
    const trimmed = value.trim()
    if (!trimmed) return undefined
    try {
      const parsed = JSON.parse(trimmed)
      if (Array.isArray(parsed)) {
        const normalized = parsed
          .map((item) => {
            if (!item) return undefined
            if (typeof item === 'string') {
              const url = item.trim()
              if (!url) return undefined
              const idx = url.lastIndexOf('/')
              const name = idx !== -1 ? url.substring(idx + 1) : url
              return { fileName: name, fileUrl: url }
            }
            if (typeof item === 'object' && (item as any).fileUrl) {
              const url = String((item as any).fileUrl)
              const name = (item as any).fileName ? String((item as any).fileName) : undefined
              const idx = url.lastIndexOf('/')
              return { fileName: name || (idx !== -1 ? url.substring(idx + 1) : url), fileUrl: url }
            }
            return undefined
          })
          .filter((v) => Boolean(v))
        return normalized.length ? JSON.stringify(normalized) : undefined
      }
      if (parsed && typeof parsed === 'object') {
        const url = (parsed as any).fileUrl ? String((parsed as any).fileUrl) : undefined
        if (!url) return undefined
        const name = (parsed as any).fileName ? String((parsed as any).fileName) : undefined
        const idx = url.lastIndexOf('/')
        return JSON.stringify([
          { fileName: name || (idx !== -1 ? url.substring(idx + 1) : url), fileUrl: url }
        ])
      }
    } catch {}

    const urls = trimmed
      .split(',')
      .map((s) => s.trim())
      .filter((s) => !!s)
    if (!urls.length) return undefined
    const infos = urls.map((url) => {
      const idx = url.lastIndexOf('/')
      const name = idx !== -1 ? url.substring(idx + 1) : url
      return { fileName: name, fileUrl: url }
    })
    return JSON.stringify(infos)
  }
  if (Array.isArray(value)) return JSON.stringify(value)
  if (typeof value === 'object' && (value as any).fileUrl) return JSON.stringify([value])
  return JSON.stringify([{ fileName: '', fileUrl: String(value) }])
}

const initFormData = () => ({
  id: undefined,
  deviceCode: undefined,
  isCode: true,
  deviceName: undefined,
  deviceStatus: undefined,
  deviceBrand: undefined,
  sn: undefined,
  deviceModel: undefined,
  deviceSpec: undefined,
  isScheduled: 0,
  ratedCapacity: undefined,
  deviceType: undefined as string | undefined,
  deviceLine: undefined as string | undefined,
  supplier: undefined,
  workshop: undefined,
  deviceLocation: undefined,
  systemOrg: undefined,
  deviceManagerIds: [] as number[],
  productionDate: undefined,
  outgoingTime: undefined,
  factoryEntryDate: undefined,
  remark: undefined,
  componentIds: [] as number[],
  beijianIds: [] as number[],
  fileUrl: '',
  qrcodeUrl: undefined,
  templateJson: undefined,
  sort: undefined,
  dvId: undefined as string | undefined
})

const formData = ref({
  ...initFormData()
})
const isScheduledEnabled = computed(() => Number(formData.value.isScheduled) === 1)
const validateDeviceCode = (_rule, value, callback) => {
  if (Boolean(formData.value.isCode)) {
    callback()
    return
  }
  if (value === undefined || value === null || String(value).trim() === '') {
    callback(new Error(t('EquipmentManagement.EquipmentLedger.validatorDeviceCodeRequired')))
    return
  }
  callback()
}
const validateScheduledRequired = (label: string) => (_rule, value, callback) => {
  if (!isScheduledEnabled.value) {
    callback()
    return
  }
  const normalized = normalizeNumberish(value)
  if (normalized === undefined) {
    callback(new Error(`璇疯緭鍏?{label}`))
    return
  }
  callback()
}
const formRules = reactive<FormRules>({
  deviceCode: [{ validator: validateDeviceCode, trigger: ['blur', 'change'] }],
  deviceName: [
    {
      required: true,
      message: t('EquipmentManagement.EquipmentLedger.placeholderDeviceName'),
      trigger: 'blur'
    }
  ],
  deviceType: [
    {
      required: true,
      message: t('EquipmentManagement.EquipmentLedger.placeholderDeviceType'),
      trigger: 'change'
    }
  ],
  ratedCapacity: [
    { validator: validateScheduledRequired('棰濆畾浜ц兘'), trigger: ['blur', 'change'] }
  ]
})
const formRef = ref() // 琛ㄥ崟 Ref

const handleFileUploadingChange = (uploading: boolean) => {
  fileUploading.value = uploading
}

watch(
  () => formData.value.isScheduled,
  () => {
    formRef.value?.clearValidate?.(['ratedCapacity'])
  }
)

const treeSelectProps = { label: 'name', children: 'children' }
const deviceTypeTree = ref<DeviceTypeTreeVO[]>([])
const users = ref<UserVO[]>([])
type SelectionOption = { label: string; value: number }
const criticalComponentOptions = ref<SelectionOption[]>([])
const beijianOptions = ref<SelectionOption[]>([])
const savedCriticalComponentOptions = ref<SelectionOption[]>([])
const savedBeijianOptions = ref<SelectionOption[]>([])
const SPARE_PART_CATEGORY_TYPE = 3
const buildCriticalComponentOptions = (items: any[] = []): SelectionOption[] =>
  (items ?? [])
    .map((item: any) => {
      const id = normalizeNumberish(item?.id)
      if (id === undefined) return undefined
      const code = item.code ? String(item.code) : ''
      const name = item.name ? String(item.name) : ''
      const label = code && name ? `${code}-${name}` : name || code || String(id)
      return { label, value: id }
    })
    .filter((item): item is SelectionOption => Boolean(item))
const buildBeijianOptions = (items: any[] = []): SelectionOption[] =>
  (items ?? [])
    .map((item: any) => {
      const id = normalizeNumberish(item?.id)
      if (id === undefined) return undefined
      const code = item.barCode ? String(item.barCode) : ''
      const name = item.name ? String(item.name) : ''
      const label = code && name ? `${code}-${name}` : name || code || String(id)
      return { label, value: id }
    })
    .filter((item): item is SelectionOption => Boolean(item))
const mergeSelectionOptions = (...groups: SelectionOption[][]): SelectionOption[] => {
  const optionMap = new Map<number, SelectionOption>()
  groups.flat().forEach((item) => optionMap.set(item.value, item))
  return Array.from(optionMap.values())
}
const filterValidSelectedIds = (selectedIds: any[], options: SelectionOption[]) => {
  const validIds = new Set(options.map((item) => item.value))
  return Array.from(
    new Set(
      (selectedIds ?? [])
        .map((id) => normalizeNumberish(id))
        .filter((id): id is number => id !== undefined && validIds.has(id))
    )
  )
}
const criticalComponentTransferData = computed(() =>
  criticalComponentOptions.value.map((item) => ({ key: item.value, label: item.label }))
)
const beijianTransferData = computed(() =>
  beijianOptions.value.map((item) => ({ key: item.value, label: item.label }))
)

const criticalComponentDialogVisible = ref(false)
const beijianDialogVisible = ref(false)
const criticalComponentDraft = ref<number[]>([])
const beijianDraft = ref<number[]>([])

const formatSelectedSummary = (ids: number[], options: { label: string; value: number }[]) => {
  const optionMap = new Map<number, string>(options.map((item) => [item.value, item.label]))
  const labels = ids.map((id) => optionMap.get(id)).filter((v): v is string => Boolean(v))
  if (!labels.length) return ''
  if (labels.length <= 3) return labels.join(', ')
  return `${labels.slice(0, 3).join(', ')}...${labels.length}`
}

const criticalComponentDisplay = computed(() =>
  formatSelectedSummary(
    formData.value.componentIds ?? [],
    mergeSelectionOptions(criticalComponentOptions.value, savedCriticalComponentOptions.value)
  )
)
const beijianDisplay = computed(() =>
  formatSelectedSummary(
    formData.value.beijianIds ?? [],
    mergeSelectionOptions(beijianOptions.value, savedBeijianOptions.value)
  )
)

const clearCriticalComponent = () => {
  formData.value.componentIds = []
}
const clearBeijian = () => {
  formData.value.beijianIds = []
}

const buildIotDeviceLabel = (item: any) => {
  if (!item) return ''
  const code = item.deviceCode ? String(item.deviceCode) : ''
  const name = item.deviceName ? String(item.deviceName) : ''
  return code && name ? `${code}-${name}` : name || code || (item.id ? String(item.id) : '')
}

const getIotDeviceIdFromDetail = (detail: any) =>
  normalizeNumberish(
    detail?.dvId ?? detail?.iotDeviceId ?? detail?.iotDevice?.id ?? detail?.device?.id
  )

const getIotDeviceLabelFromDetail = (detail: any) => {
  const directLabel =
    detail?.dvName ??
    detail?.iotDeviceName ??
    detail?.iotDeviceLabel ??
    detail?.iotDevice?.deviceName ??
    detail?.device?.deviceName
  if (directLabel) return String(directLabel)

  const code = detail?.iotDeviceCode ?? detail?.iotDevice?.deviceCode ?? detail?.device?.deviceCode
  const name = detail?.iotDeviceName ?? detail?.iotDevice?.deviceName ?? detail?.device?.deviceName
  return buildIotDeviceLabel({
    id: getIotDeviceIdFromDetail(detail),
    deviceCode: code,
    deviceName: name
  })
}

const iotDeviceDisplay = computed(() => iotDeviceSelectedLabel.value)

const isIotDeviceSelectable = (row: any) => {
  const value = row?.selectable
  return value !== false && String(value ?? 'true').toLowerCase() !== 'false'
}

const isIotDeviceEnabled = (row: any) => {
  const value = row?.isEnable
  if (typeof value === 'boolean') return value
  const text = String(value ?? '')
    .toLowerCase()
    .trim()
  return text === 'true' || text === '1' || text === 'yes'
}

const selectIotDevice = (row: DeviceVO) => {
  if (!isIotDeviceSelectable(row)) return
  const id = normalizeNumberish(row?.id)
  if (id === undefined) return
  iotDeviceDraftId.value = id
  iotDeviceDraftRow.value = row
}

const handleIotDeviceRowClick = (row: DeviceVO) => {
  selectIotDevice(row)
}

const getIotDeviceRowClassName = ({ row }: { row: DeviceVO }) => {
  return isIotDeviceSelectable(row) ? '' : 'is-not-selectable'
}

const openIotDeviceDialog = async () => {
  const id = normalizeNumberish(formData.value.dvId)
  iotDeviceDraftId.value = id
  iotDeviceDraftRow.value =
    id === undefined ? undefined : ({ id, deviceName: iotDeviceSelectedLabel.value } as DeviceVO)
  iotDeviceDialogVisible.value = true
  await getIotDeviceList()
}

const clearIotDevice = () => {
  formData.value.dvId = undefined
  iotDeviceSelectedLabel.value = ''
  iotDeviceDraftId.value = undefined
  iotDeviceDraftRow.value = undefined
  formRef.value?.clearValidate?.(['dvId'])
}

const confirmIotDeviceDialog = () => {
  if (iotDeviceDraftId.value === undefined || !iotDeviceDraftRow.value) {
    message.warning(t('EquipmentManagement.EquipmentLedger.dvId'))
    return
  }
  if (!isIotDeviceSelectable(iotDeviceDraftRow.value)) {
    message.warning('璇ョ墿鑱旇澶囦笉鍙€夋嫨')
    return
  }
  formData.value.dvId = iotDeviceDraftId.value
  iotDeviceSelectedLabel.value = buildIotDeviceLabel(iotDeviceDraftRow.value)
  iotDeviceDialogVisible.value = false
  formRef.value?.clearValidate?.(['dvId'])
}

const hydrateIotDeviceFromDetail = async (detail: any) => {
  const id = getIotDeviceIdFromDetail(detail)
  formData.value.dvId = id
  if (id === undefined) {
    iotDeviceSelectedLabel.value = ''
    return
  }
  const label = getIotDeviceLabelFromDetail(detail)
  if (label) {
    iotDeviceSelectedLabel.value = String(label)
    return
  }
  try {
    const device = await DeviceApi.getDevice(id)
    iotDeviceSelectedLabel.value = buildIotDeviceLabel(device)
  } catch {
    iotDeviceSelectedLabel.value = String(id)
  }
}
const openCriticalComponentDialog = () => {
  criticalComponentDraft.value = [...(formData.value.componentIds ?? [])]
  criticalComponentDialogVisible.value = true
  ids.value = [...(formData.value.componentIds ?? [])]
  setDefaultSelections()
}
const openBeijianDialog = () => {
  beijianDraft.value = [...(formData.value.beijianIds ?? [])]
  beijianDialogVisible.value = true
  bjIds.value = [...(formData.value.beijianIds ?? [])]
  setBJDefaultSelections()
}
const ids = ref<number[]>([])
const confirmCriticalComponentDialog = () => {
  //let ids = selectedRows.value.map(item => item.id);
  //const validMap = new Set(criticalComponentOptions.value.map((item) => item.value))
  //const selected = Array.from(new Set(criticalComponentDraft.value.map((v) => Number(v)).filter((v) => validMap.has(v))))
  formData.value.componentIds = filterValidSelectedIds(ids.value, criticalComponentOptions.value)
  criticalComponentDialogVisible.value = false
  //multipleTableRef.value.clearSelection()
}
const bjIds = ref<number[]>([])
const confirmBeijianDialog = () => {
  // let ids = bjSelectedRows.value.map(item => item.id);
  /* const validMap = new Set(beijianOptions.value.map((item) => item.value))
   const selected = Array.from(new Set(beijianDraft.value.map((v) => Number(v)).filter((v) => validMap.has(v))))*/
  formData.value.beijianIds = filterValidSelectedIds(bjIds.value, beijianOptions.value)
  beijianDialogVisible.value = false
  //multipleTableRef.value.clearSelection()
}

const handleCodeAutoChange = (value: boolean) => {
  if (value) {
    formData.value.deviceCode = undefined
  }
  formRef.value?.clearValidate('deviceCode')
}

const getQrcodeRefreshUrl = () => {
  if (!formData.value.id || !formData.value.deviceCode) return ''
  return `/mes/device-ledger/regenerate-code?id=${formData.value.id}&code=${encodeURIComponent(String(formData.value.deviceCode))}`
}

const buildPrintData = () => {
  return {
    id: formData.value.id,
    deviceCode: formData.value.deviceCode,
    deviceName: formData.value.deviceName,
    deviceSpec: formData.value.deviceSpec,
    deviceBrand: formData.value.deviceBrand,
    sn: formData.value.sn,
    outgoingTime: formData.value.outgoingTime,
    deviceModel: formData.value.deviceModel,
    deviceLocation: formData.value.deviceLocation,
    remark: formData.value.remark,
    qrcodeUrl: formData.value.qrcodeUrl
  }
}

const handleQrcodeRefreshSuccess = async (data: any) => {
  if (!formData.value.id) return
  if (data?.qrcodeUrl) {
    formData.value.qrcodeUrl = data.qrcodeUrl
    return
  }
  const detail = await DeviceLedgerApi.getDeviceLedger(formData.value.id)
  formData.value.qrcodeUrl = detail?.qrcodeUrl
  formData.value.deviceCode = detail?.deviceCode ?? formData.value.deviceCode
}

const ensureOptionsLoaded = async () => {
  const [deviceTypeRes, userRes, criticalRes, beijianRes] = await Promise.all([
    DeviceTypeApi.getDeviceTypeTree({ pageNo: 1, pageSize: 10 }),
    getSimpleUserList(),
    CriticalComponentApi.getCriticalComponentList(),
    ProductApi.getProductPage({ pageNo: 1, pageSize: 10, categoryType: SPARE_PART_CATEGORY_TYPE })
  ])
  deviceTypeTree.value = deviceTypeRes
  users.value = userRes ?? []
  criticalComponentOptions.value = buildCriticalComponentOptions(criticalRes ?? [])
  beijianOptions.value = buildBeijianOptions(beijianRes?.list ?? [])
}

/** 鎵撳紑寮圭獥 */
const open = async (
  type: string,
  id?: string,
  defaultDeviceTypeId?: string,
  defaultDeviceLineId?: string
) => {
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await ensureOptionsLoaded()
  if (type === 'create' && defaultDeviceTypeId) {
    formData.value.deviceType = defaultDeviceTypeId
  }
  if (type === 'create' && defaultDeviceLineId) {
    ;(formData.value as any).deviceLine = defaultDeviceLineId
  }
  // 淇敼鏃讹紝璁剧疆鏁版嵁
  if (id) {
    formLoading.value = true
    try {
      const detail = await DeviceLedgerApi.getDeviceLedger(id)
      const templateJson = (detail as any)?.templateJson
      const parsedTemplateJson =
        typeof templateJson === 'string' ? JSON.parse(templateJson) : templateJson
      formData.value = {
        ...initFormData(),
        ...(detail as any),
        templateJson: parsedTemplateJson,
        isCode: (detail as any)?.isCode ?? false,
        isScheduled:
          normalizeNumberish((detail as any)?.isScheduled ?? (detail as any)?.isScheduled) ?? 0,
        ratedCapacity: normalizeNumberish((detail as any)?.ratedCapacity),
        deviceType: (detail as any)?.deviceType ?? undefined,
        deviceLine: (detail as any)?.deviceLine ?? undefined,
        deviceManagerIds: parseIdsValue((detail as any)?.deviceManager),
        productionDate: normalizeYmd((detail as any)?.productionDate),
        outgoingTime: normalizeYmd((detail as any)?.outgoingTime),
        factoryEntryDate: normalizeYmd((detail as any)?.factoryEntryDate),
        componentIds: parseIdsValue((detail as any)?.componentId),
        beijianIds: parseIdsValue((detail as any)?.beijianId),
        qrcodeUrl: (detail as any)?.qrcodeUrl
      }
      savedCriticalComponentOptions.value = buildCriticalComponentOptions(
        (detail as any)?.componentList ?? []
      )
      savedBeijianOptions.value = buildBeijianOptions((detail as any)?.beijianList ?? [])
      await hydrateIotDeviceFromDetail(detail as any)
    } finally {
      formLoading.value = false
    }
  }
  getList()

  bjGetList()
}
defineExpose({ open }) // 鎻愪緵 open 鏂规硶锛岀敤浜庢墦寮€寮圭獥
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined as string | undefined,
  name: undefined as string | undefined,
  description: undefined as string | undefined,
  remark: undefined as string | undefined,
  createTime: [] as string[]
})

const bjQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  barCode: undefined,
  name: undefined,
  categoryType: SPARE_PART_CATEGORY_TYPE
})

const iotDeviceQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceCode: undefined as string | undefined,
  deviceName: undefined as string | undefined
})

const getIotDeviceList = async () => {
  iotDeviceLoading.value = true
  try {
    const data = await DeviceApi.getDevicePage(iotDeviceQueryParams)
    iotDeviceList.value = (data?.list ?? []) as DeviceVO[]
    iotDeviceTotal.value = data?.total ?? 0
  } finally {
    iotDeviceLoading.value = false
  }
}

const handleIotDeviceQuery = () => {
  iotDeviceQueryParams.pageNo = 1
  getIotDeviceList()
}

const resetIotDeviceQuery = () => {
  iotDeviceQueryFormRef.value?.resetFields?.()
  handleIotDeviceQuery()
}
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 閰嶄欢鎼滅储鎸夐挳鎿嶄綔 */
const bjHandleQuery = () => {
  bjQueryParams.pageNo = 1
  bjGetList()
}

/** 閰嶄欢閲嶇疆鎸夐挳鎿嶄綔 */
const bjResetQuery = () => {
  bjQueryFormRef.value.resetFields()
  bjHandleQuery()
}

const handleSelectionChange = (rows: CriticalComponentVO[]) => {
  selectedIds.value = rows.map((r) => r.id).filter((id): id is number => typeof id === 'number')
  // 鑾峰彇褰撳墠椤垫墍鏈夎鐨?id
  const currentPageIds = rows.map((item) => item.id)

  // 浠庡凡閫変腑鐨勬暟缁勪腑绉婚櫎褰撳墠椤电殑鏁版嵁
  selectedRows.value = selectedRows.value.filter((item) => !currentPageIds.includes(item.id))
  // 娣诲姞褰撳墠椤垫柊閫変腑鐨勬暟鎹?
  selectedRows.value.push(...rows)
}

// 瀛樺偍褰撳墠宸查€変腑鐨勮
const currentSelectedRows = ref([])

// select 浜嬩欢锛歳ow 鏄綋鍓嶆搷浣滅殑琛岋紝selected 鏄搷浣滃悗鐨勭姸鎬?
const handleSelect = (selection, row) => {
  // 鍒ゆ柇鏄€変腑杩樻槸鍙栨秷閫変腑
  const isSelected = selection.includes(row)
  if (isSelected) {
    // console.log(`鉁?琛岃閫変腑: ID=${row.id}, Name=${row.name}`)
    ids.value.push(row.id)
  } else {
    ids.value = ids.value.filter((item) => item !== row.id)
    // console.log(`鉂?琛岃鍙栨秷閫変腑: ID=${row.id}, Name=${row.name}`)
  }
  // 鏇存柊褰撳墠閫変腑鐘舵€?
  currentSelectedRows.value = selection
}

const handleSelectAll = (selection) => {
  ids.value = selection?.map((row) => row.id).filter((id) => id !== undefined) ?? []

  /*  let newVar = selection?.map((row) => row.id).filter((id) => id !== undefined) ?? [];
  newVar.forEach(row => {
    ids.value.push(row)
  })*/
}

const bjHandleSelectionChange = (rows: CriticalComponentVO[]) => {
  bjSelectedIds.value = rows.map((r) => r.id).filter((id): id is number => typeof id === 'number')
  // 鑾峰彇褰撳墠椤垫墍鏈夎鐨?id
  const currentPageIds = rows.map((item) => item.id)

  // 浠庡凡閫変腑鐨勬暟缁勪腑绉婚櫎褰撳墠椤电殑鏁版嵁
  bjSelectedRows.value = bjSelectedRows.value.filter((item) => !currentPageIds.includes(item.id))
  // 娣诲姞褰撳墠椤垫柊閫変腑鐨勬暟鎹?
  bjSelectedRows.value.push(...rows)
}

// 瀛樺偍褰撳墠宸查€変腑鐨勮
const bjCurrentSelectedRows = ref([])

// select 浜嬩欢锛歳ow 鏄綋鍓嶆搷浣滅殑琛岋紝selected 鏄搷浣滃悗鐨勭姸鎬?
const bjHandleSelect = (selection, row) => {
  // 鍒ゆ柇鏄€変腑杩樻槸鍙栨秷閫変腑
  const isSelected = selection.includes(row)
  if (isSelected) {
    // console.log(`鉁?琛岃閫変腑: ID=${row.id}, Name=${row.name}`)
    bjIds.value.push(row.id)
  } else {
    bjIds.value = bjIds.value.filter((item) => item !== row.id)
    // console.log(`鉂?琛岃鍙栨秷閫変腑: ID=${row.id}, Name=${row.name}`)
  }
  // 鏇存柊褰撳墠閫変腑鐘舵€?
  bjCurrentSelectedRows.value = selection
}

const bjHandleSelectAll = (selection) => {
  bjIds.value = selection?.map((row) => row.id).filter((id) => id !== undefined) ?? []
}

const getList = async () => {
  loading.value = true
  try {
    const data = await CriticalComponentApi.getCriticalComponentPage(queryParams)
    list.value = data.list
    total.value = data.total
    // 鏁版嵁鍔犺浇鍚庯紝閲嶆柊璁剧疆閫変腑鐘舵€?
    nextTick(() => {
      toggleSelection()
    })
  } finally {
    loading.value = false
  }
}

/** 閰嶄欢鏌ヨ鍒楄〃 */
const bjGetList = async () => {
  loading.value = true
  try {
    bjQueryParams.categoryType = SPARE_PART_CATEGORY_TYPE
    const data = await ProductApi.getProductPage(bjQueryParams)
    bjList.value = data.list
    bjTotal.value = data.total
    beijianOptions.value = mergeSelectionOptions(beijianOptions.value, buildBeijianOptions(bjList.value))
    // 鏁版嵁鍔犺浇鍚庯紝閲嶆柊璁剧疆閫変腑鐘舵€?
    nextTick(() => {
      bjToggleSelection()
    })
  } finally {
    loading.value = false
  }
}

// 鍒囨崲閫変腑鐘舵€?
const toggleSelection = () => {
  if (!multipleTableRef.value || !selectedRows.value.length) return

  // 閬嶅巻褰撳墠椤电殑鏁版嵁
  list.value.forEach((row) => {
    // 妫€鏌ヨ繖涓€琛屾槸鍚﹀湪宸查€変腑鏁扮粍涓?
    const isSelected = selectedRows.value.some((item) => item.id === row.id)

    if (isSelected) {
      // 濡傛灉搴旇閫変腑锛屽氨閫変腑
      multipleTableRef.value!.toggleRowSelection(row, true)
    } else {
      // 鍚﹀垯鍙栨秷閫変腑
      multipleTableRef.value!.toggleRowSelection(row, false)
    }
  })
}

// 鍒囨崲閫変腑鐘舵€?
const bjToggleSelection = () => {
  if (!bjMultipleTableRef.value || !bjSelectedRows.value.length) return

  // 閬嶅巻褰撳墠椤电殑鏁版嵁
  bjList.value.forEach((row) => {
    // 妫€鏌ヨ繖涓€琛屾槸鍚﹀湪宸查€変腑鏁扮粍涓?
    const isSelected = bjSelectedRows.value.some((item) => item.id === row.id)

    if (isSelected) {
      // 濡傛灉搴旇閫変腑锛屽氨閫変腑
      bjMultipleTableRef.value!.toggleRowSelection(row, true)
    } else {
      // 鍚﹀垯鍙栨秷閫変腑
      bjMultipleTableRef.value!.toggleRowSelection(row, false)
    }
  })
}

/** 鎻愪氦琛ㄥ崟 */
const emit = defineEmits(['success', 'closed']) // 瀹氫箟 success 鍜?closed 浜嬩欢
const submitForm = async () => {
  if (fileUploading.value) {
    message.warning(t('common.loading'))
    return
  }
  // 鏍￠獙琛ㄥ崟
  await formRef.value.validate()
  // 鎻愪氦璇锋眰
  formLoading.value = true
  try {
    const data = {
      ...(formData.value as any),
      isScheduled: normalizeNumberish((formData.value as any).isScheduled) ?? 0,
      ratedCapacity: normalizeNumberish((formData.value as any).ratedCapacity),
      deviceType: (formData.value as any).deviceType ?? undefined,
      deviceLine: (formData.value as any).deviceLine ?? undefined,
      productionDate: normalizeYmd(formData.value.productionDate),
      outgoingTime: normalizeYmd((formData.value as any).outgoingTime),
      factoryEntryDate: normalizeYmd(formData.value.factoryEntryDate),
      deviceManager: formData.value.deviceManagerIds?.length
        ? formData.value.deviceManagerIds.join(',')
        : undefined,
      componentId: formData.value.componentIds?.length
        ? formData.value.componentIds.join(',')
        : undefined,
      beijianId: formData.value.beijianIds?.length
        ? formData.value.beijianIds.join(',')
        : undefined,
      fileUrl: normalizeFileUrlAsJsonArrayString((formData.value as any).fileUrl)
    } as unknown as DeviceLedgerVO
    delete (data as any).deviceManagerIds
    delete (data as any).componentIds
    delete (data as any).beijianIds
    if (formType.value === 'create') {
      await DeviceLedgerApi.createDeviceLedger(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceLedgerApi.updateDeviceLedger(data)
      message.success(t('common.updateSuccess'))
    }
    closeForm()
    // 鍙戦€佹搷浣滄垚鍔熺殑浜嬩欢
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 鏂规硶1锛氱洿鎺ョ洃鍚?data
watch(
  list,
  (newData, oldData) => {
    // 鍙互鍦ㄨ繖閲屾墽琛岀浉鍏虫搷浣?
    if (newData.length > 0) {
      // 鏁版嵁鍔犺浇瀹屾垚鍚庣殑鎿嶄綔
      setDefaultSelections()
    }
  },
  { deep: true }
)

//const defaultSelectedIds = [144, 143,141]

// 璁剧疆榛樿閫変腑鐨勮
const setDefaultSelections = () => {
  // 绛夊緟DOM鏇存柊瀹屾垚
  nextTick(() => {
    if (!multipleTableRef.value) return
    multipleTableRef.value.clearSelection()
    const rawSubjectIds = toRaw(formData.value.componentIds)
    if (rawSubjectIds.length != 0) {
      let row = {
        id: undefined
      }
      multipleTableRef.value.toggleRowSelection(row, true)
    }
    // 閬嶅巻鏁版嵁锛屾壘鍒伴渶瑕侀€変腑鐨勮
    list.value.forEach((row) => {
      let id = row.id
      if (rawSubjectIds.includes(row.id)) {
        multipleTableRef.value.toggleRowSelection(row, true)
      }
    })
  })
}

// 鏂规硶1锛氱洿鎺ョ洃鍚?data
watch(
  bjList,
  (newData, oldData) => {
    // 鍙互鍦ㄨ繖閲屾墽琛岀浉鍏虫搷浣?
    if (newData.length > 0) {
      // 鏁版嵁鍔犺浇瀹屾垚鍚庣殑鎿嶄綔
      setBJDefaultSelections()
    }
  },
  { deep: true }
)

//const defaultSelectedIds = [144, 143,141]

// 璁剧疆榛樿閫変腑鐨勮
const setBJDefaultSelections = () => {
  // 绛夊緟DOM鏇存柊瀹屾垚
  nextTick(() => {
    if (!bjMultipleTableRef.value) return
    bjMultipleTableRef.value.clearSelection()
    const rawSubjectIds = toRaw(formData.value.beijianIds)
    if (rawSubjectIds.length != 0) {
      let row = {
        id: undefined
      }
      bjMultipleTableRef.value.toggleRowSelection(row, true)
    }
    // 閬嶅巻鏁版嵁锛屾壘鍒伴渶瑕侀€変腑鐨勮
    bjList.value.forEach((row) => {
      let id = row.id
      if (rawSubjectIds.includes(row.id)) {
        bjMultipleTableRef.value.toggleRowSelection(row, true)
      }
    })
  })
}

const closeForm = () => {
  emit('closed')
}

/** 閲嶇疆琛ㄥ崟 */
const resetForm = () => {
  fileUploading.value = false
  formData.value = initFormData()
  savedCriticalComponentOptions.value = []
  savedBeijianOptions.value = []
  ids.value = []
  bjIds.value = []
  iotDeviceSelectedLabel.value = ''
  iotDeviceDraftId.value = undefined
  iotDeviceDraftRow.value = undefined
  iotDeviceList.value = []
  iotDeviceTotal.value = 0
  selectedRows.value = []
  bjSelectedRows.value = []
  formRef.value?.resetFields()
}
</script>

<style scoped>
.device-ledger-manager {
  display: flex;
  width: 100%;
  gap: 12px;
}

.device-ledger-manager :deep(.el-input) {
  flex: 1;
}

:deep(.ellipsis-text) {
  max-width: 300px;
}

.device-ledger-transfer {
  width: 100%;
  overflow-x: auto;
}

.device-ledger-transfer :deep(.el-transfer) {
  width: 100%;
  min-width: 760px;
  flex-wrap: nowrap;
}

.device-ledger-transfer :deep(.el-transfer-panel) {
  flex: 1 0 340px;
  width: 340px;
}

.device-ledger-transfer-dialog :deep(.el-dialog__body) {
  padding-top: 8px;
}

.device-ledger-transfer-dialog .device-ledger-transfer :deep(.el-transfer-panel) {
  height: 560px;
}

.device-ledger-transfer-dialog .device-ledger-transfer :deep(.el-transfer-panel__body) {
  height: 520px;
}

.device-ledger-transfer-dialog .device-ledger-transfer :deep(.el-transfer-panel__list) {
  height: 100%;
}

.device-ledger-transfer :deep(.el-transfer__buttons) {
  flex: 0 0 72px;
  padding: 0 12px;
}

.device-ledger-selection-input :deep(.el-input__inner) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-select-all :deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}

.device-ledger-device-dialog :deep(.el-dialog__body) {
  padding-top: 8px;
}

.device-ledger-device-table :deep(.el-radio) {
  height: 18px;
}

.device-ledger-device-table :deep(.el-radio__label) {
  display: none;
}

.device-ledger-device-table :deep(.is-not-selectable) {
  color: #a8abb2;
  cursor: not-allowed;
}

.device-ledger-device-table :deep(.is-not-selectable .el-table__cell) {
  background-color: #fafafa;
}

.device-ledger-dialog-pagination {
  display: flex;
  justify-content: flex-end;
  padding-top: 12px;
}

.device-ledger-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.device-ledger-panel {
  background: #fff;
  border-radius: 12px;
  box-shadow: var(--el-box-shadow-light);
}

.device-ledger-panel__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.device-ledger-panel__title {
  color: #1f2937;
  font-size: 18px;
  font-weight: 600;
}

.device-ledger-dialog {
  max-height: calc(100vh - 220px);
  padding: 20px 20px 0;
  padding-right: 16px;
  overflow-y: auto;
}

.device-ledger-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  width: 100%;
  padding: 16px 20px 20px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .device-ledger-panel__header {
    padding: 14px 16px;
  }

  .device-ledger-dialog {
    max-height: none;
    padding: 16px 16px 0;
    overflow-y: visible;
  }

  .device-ledger-footer {
    padding: 16px;
  }
}
</style>
