<template>
  <div class="app-container medical-resource-page">
    <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
      <el-tab-pane :label="dtT('tabVet')" name="vet" />
      <el-tab-pane :label="dtT('tabTeam')" name="team" />
      <el-tab-pane :label="dtT('tabOrg')" name="org" />
      <el-tab-pane :label="dtT('tabEquipment')" name="equipment" />
    </el-tabs>

    <br />

    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="resourceType">
          <template slot="label">{{ dtT("queryResourceType") }}</template>
          <el-select v-model="queryParams.resourceType" :placeholder="dtCommon('pleaseSelect')" style="width: 180px" @change="handleQueryTypeChange">
            <el-option v-for="item in resourceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="resourceName">
          <template slot="label">{{ dtT("queryResourceName") }}</template>
          <el-input
            v-model="queryParams.resourceName"
            :placeholder="dtT('queryResourceNamePh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="publishStatus">
          <template slot="label">{{ dtT("queryPublishStatus") }}</template>
          <el-select v-model="queryParams.publishStatus" :placeholder="dtCommon('pleaseSelect')" clearable style="width: 130px">
            <el-option :label="$t('diseaseTreatment.status.unpublished')" :value="0" />
            <el-option :label="$t('diseaseTreatment.status.published')" :value="1" />
            <el-option :label="$t('diseaseTreatment.status.offline')" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="activeTab === 'vet'" prop="townDeptId">
          <template slot="label">{{ dtT("queryTown") }}</template>
          <el-select
            v-model="queryParams.townDeptId"
            :placeholder="dtCommon('pleaseSelect')"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in townOptions"
              :key="'q-town-' + item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ dtCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ dtCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['diseaseTreatment:medicalResource:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dtCommon("add") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <div slot="header" class="table-card-header">
        <el-button
          v-hasPermi="['diseaseTreatment:medicalResource:publish']"
          type="primary"
          plain
          size="mini"
          :disabled="!selectedRows.length"
          @click="handleBatchPublish"
        >{{ dtCommon("batchPublish") }}</el-button>
        <el-button
          v-hasPermi="['diseaseTreatment:medicalResource:offline']"
          type="warning"
          plain
          size="mini"
          :disabled="!selectedRows.length"
          @click="handleBatchOffline"
        >{{ dtCommon("batchOffline") }}</el-button>
        <el-button
          v-if="showColAccount"
          v-hasPermi="['diseaseTreatment:medicalResource:assignAccount']"
          type="success"
          plain
          size="mini"
          :disabled="!selectedRows.length"
          @click="handleBatchAssignAccount"
        >{{ dtCommon("batchAssignAccount") }}</el-button>
      </div>
      <el-table ref="table" v-loading="loading" :data="tableList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column :label="dtT('colResourceName')" prop="resourceName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dtT('colIntro')" prop="introduction" align="center" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column v-if="showColContact" :label="dtT('colContact')" prop="contactPhone" align="center" width="120" />
        <el-table-column v-if="showColTown" :label="dtT('colTown')" prop="townName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column v-if="showColAffiliated" :label="dtT('colAffiliatedUnit')" prop="affiliatedUnit" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column v-if="showColAddress" :label="dtT('colDetailAddress')" prop="detailAddress" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column v-if="activeTab === 'org'" :label="dtT('colOrgLevel')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ orgLevelLabel(scope.row.orgLevel) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="activeTab === 'equipment'" :label="dtT('colEquipmentModel')" prop="equipmentModel" align="center" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column v-if="showColAccount" :label="dtT('colAccount')" align="center" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.accountAssigned === 1">
              {{ $t('diseaseTreatment.status.yes') }}
              <template v-if="scope.row.assignedLoginName">（{{ scope.row.assignedLoginName }}）</template>
            </span>
            <span v-else>{{ $t('diseaseTreatment.status.no') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dtCommon('colShelf')" align="center" width="92">
          <template slot-scope="scope">
            <span>{{ displayPublishStatusText(scope.row.displayPublishStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dtCommon('colCreate')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime) : $t('diseaseTreatment.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dtCommon('colOp')" align="center" class-name="small-padding fixed-width" width="300" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['diseaseTreatment:medicalResource:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dtCommon("view") }}</el-button>
            <el-button
              v-hasPermi="['diseaseTreatment:medicalResource:edit']"
              v-if="scope.row.canEdit"
              type="text"
              size="mini"
              @click="handleEdit(scope.row)"
            >{{ dtCommon("edit") }}</el-button>
            <el-button
              v-hasPermi="['diseaseTreatment:medicalResource:remove']"
              v-if="scope.row.canDelete"
              type="text"
              size="mini"
              @click="handleDelete(scope.row)"
            >{{ dtCommon("delete") }}</el-button>
            <el-button
              v-hasPermi="['diseaseTreatment:medicalResource:publish']"
              v-if="scope.row.canPublish"
              type="text"
              size="mini"
              @click="handlePublish(scope.row)"
            >{{ dtCommon("publish") }}</el-button>
            <el-button
              v-hasPermi="['diseaseTreatment:medicalResource:offline']"
              v-if="scope.row.canOffline"
              type="text"
              size="mini"
              @click="handleOffline(scope.row)"
            >{{ dtCommon("offline") }}</el-button>
            <el-button
              v-hasPermi="['diseaseTreatment:medicalResource:assignAccount']"
              v-if="scope.row.canAssignAccount"
              type="text"
              size="mini"
              @click="handleAssignAccount(scope.row)"
            >{{ dtCommon("assignAccount") }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="open" width="720px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="140px">
        <el-form-item prop="resourceType" :rules="formRules.resourceType">
          <template slot="label">{{ dtT("formResourceType") }}</template>
          <el-select v-model="form.resourceType" :placeholder="dtCommon('pleaseSelect')" :disabled="dialogEdit" style="width: 100%" @change="handleFormTypeChange">
            <el-option v-for="item in resourceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <div v-if="dialogEdit" class="el-form-item__tip">{{ dtT("resourceTypeLocked") }}</div>
        </el-form-item>
        <el-form-item prop="resourceName" :rules="formRules.resourceName">
          <template slot="label">{{ dtT("formResourceName") }}</template>
          <el-input v-model="form.resourceName" :placeholder="dtT('phResourceName')" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item prop="photoFilePath" :rules="formRules.photoFilePath">
          <template slot="label">{{ dtT("formPhoto") }}</template>
          <el-upload
            list-type="picture-card"
            :class="{ hide: hidePhotoUpload }"
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforePhotoUpload"
            :on-success="handlePhotoUploadSuccess"
            :on-error="handleUploadHttpError"
            :on-remove="handlePhotoRemove"
            :limit="1"
            :file-list="photoFileList"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <div class="el-upload__tip">{{ dtCommon("tipPhoto") }}</div>
        </el-form-item>
        <el-form-item prop="introduction" :rules="formRules.introduction">
          <template slot="label">{{ dtT("formIntroduction") }}</template>
          <el-input v-model="form.introduction" type="textarea" :rows="3" :placeholder="dtT('phIntroduction')" maxlength="500" show-word-limit />
        </el-form-item>

        <template v-if="isVetType(form.resourceType)">
          <el-form-item prop="contactPhone" :rules="formRules.contactPhone">
            <template slot="label">{{ dtT("formContactPhone") }}</template>
            <el-input v-model="form.contactPhone" :placeholder="dtT('phContactPhone')" maxlength="11" />
          </el-form-item>
          <el-form-item prop="affiliatedUnit" :rules="formRules.affiliatedUnit">
            <template slot="label">{{ dtT("formAffiliatedUnit") }}</template>
            <el-input v-model="form.affiliatedUnit" :placeholder="dtT('phAffiliatedUnit')" maxlength="20" show-word-limit />
          </el-form-item>
          <el-form-item prop="townDeptId">
            <template slot="label">{{ dtT("formTown") }}</template>
            <el-select
              v-model="form.townDeptId"
              :placeholder="dtT('phTown')"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in townOptions"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="detailAddress" :rules="formRules.detailAddress">
            <template slot="label">{{ dtT("formDetailAddress") }}</template>
            <el-input v-model="form.detailAddress" :placeholder="dtT('phDetailAddress')" maxlength="100" show-word-limit />
          </el-form-item>
          <el-form-item prop="consultModesList" :rules="formRules.consultModesList">
            <template slot="label">{{ dtT("formConsultModes") }}</template>
            <el-checkbox-group v-model="form.consultModesList" @change="validateFormField('consultModesList')">
              <el-checkbox v-for="item in consultModeOptions" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item prop="serviceArea" :rules="formRules.serviceArea">
            <template slot="label">{{ dtT("formServiceArea") }}</template>
            <el-input v-model="form.serviceArea" :placeholder="dtT('phServiceArea')" maxlength="100" show-word-limit />
          </el-form-item>
          <el-form-item prop="feeStandard" :rules="formRules.feeStandard">
            <template slot="label">{{ dtT("formFeeStandard") }}</template>
            <div class="form-unit-wrap">
              <el-input-number v-model="form.feeStandard" :min="0.01" :precision="2" :step="10" controls-position="right" class="form-unit-input" />
              <span class="form-unit">{{ dtCommon("unitYuanHour") }}</span>
            </div>
          </el-form-item>
          <el-form-item prop="serviceStartTime" :rules="formRules.serviceStartTime">
            <template slot="label">{{ dtT("formServiceTime") }}</template>
            <el-time-select
              v-model="form.serviceStartTime"
              :placeholder="dtT('formServiceStart')"
              :picker-options="timePickerOptions"
              style="width: 160px"
              @change="handleServiceStartTimeChange"
            />
            <span class="time-sep">{{ dtCommon("timeSeparator") }}</span>
            <el-time-select
              v-model="form.serviceEndTime"
              :placeholder="dtT('formServiceEnd')"
              :picker-options="timePickerOptionsEnd"
              style="width: 160px"
              @change="handleServiceEndTimeChange"
            />
          </el-form-item>
          <el-form-item prop="serviceWeekdaysList" :rules="formRules.serviceWeekdaysList">
            <template slot="label">{{ dtT("formServiceWeekdays") }}</template>
            <el-checkbox-group v-model="form.serviceWeekdaysList" @change="validateFormField('serviceWeekdaysList')">
              <el-checkbox v-for="item in weekdayOptions" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </template>

        <template v-if="isTeamType(form.resourceType)">
          <el-form-item prop="contactPhone" :rules="formRules.contactPhone">
            <template slot="label">{{ dtT("formContactPhone") }}</template>
            <el-input v-model="form.contactPhone" :placeholder="dtT('phContactPhone')" maxlength="11" />
          </el-form-item>
          <el-form-item prop="affiliatedUnit" :rules="formRules.affiliatedUnit">
            <template slot="label">{{ dtT("formAffiliatedUnit") }}</template>
            <el-input v-model="form.affiliatedUnit" :placeholder="dtT('phAffiliatedUnit')" maxlength="20" show-word-limit />
          </el-form-item>
          <el-form-item prop="establishDate" :rules="formRules.establishDate">
            <template slot="label">{{ dtT("formEstablishDate") }}</template>
            <el-date-picker v-model="form.establishDate" type="date" value-format="yyyy-MM-dd" :placeholder="dtCommon('pleaseSelect')" style="width: 100%" />
          </el-form-item>
          <el-form-item prop="teamSize" :rules="formRules.teamSize">
            <template slot="label">{{ dtT("formTeamSize") }}</template>
            <div class="form-unit-wrap">
              <el-input-number v-model="form.teamSize" :min="1" :precision="0" :step="1" controls-position="right" class="form-unit-input" />
              <span class="form-unit">{{ dtCommon("unitPerson") }}</span>
            </div>
          </el-form-item>
          <el-form-item prop="teamMembers">
            <template slot="label">{{ dtT("formTeamMembers") }}</template>
            <el-input v-model="form.teamMembers" type="textarea" :rows="2" :placeholder="dtT('phTeamMembers')" maxlength="500" show-word-limit />
          </el-form-item>
          <el-form-item prop="personInCharge" :rules="formRules.personInCharge">
            <template slot="label">{{ dtT("formPersonInCharge") }}</template>
            <el-input v-model="form.personInCharge" :placeholder="dtT('phResourceName')" maxlength="10" show-word-limit />
          </el-form-item>
        </template>

        <template v-if="isOrgType(form.resourceType)">
          <el-form-item prop="orgLevel" :rules="formRules.orgLevel">
            <template slot="label">{{ dtT("formOrgLevel") }}</template>
            <el-radio-group v-model="form.orgLevel">
              <el-radio v-for="item in orgLevelOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="detailAddress" :rules="formRules.detailAddress">
            <template slot="label">{{ dtT("formDetailAddress") }}</template>
            <el-input v-model="form.detailAddress" :placeholder="dtT('phDetailAddress')" maxlength="100" show-word-limit />
          </el-form-item>
          <el-form-item prop="personInCharge" :rules="formRules.personInCharge">
            <template slot="label">{{ dtT("formPersonInCharge") }}</template>
            <el-input v-model="form.personInCharge" :placeholder="dtT('phResourceName')" maxlength="10" show-word-limit />
          </el-form-item>
          <el-form-item prop="contactPhone" :rules="formRules.contactPhone">
            <template slot="label">{{ dtT("formContactPhone") }}</template>
            <el-input v-model="form.contactPhone" :placeholder="dtT('phContactPhone')" maxlength="11" />
          </el-form-item>
          <el-form-item prop="serviceStartTime" :rules="formRules.serviceStartTime">
            <template slot="label">{{ dtT("formServiceTime") }}</template>
            <el-time-select
              v-model="form.serviceStartTime"
              :placeholder="dtT('formServiceStart')"
              :picker-options="timePickerOptions"
              style="width: 160px"
              @change="handleServiceStartTimeChange"
            />
            <span class="time-sep">{{ dtCommon("timeSeparator") }}</span>
            <el-time-select
              v-model="form.serviceEndTime"
              :placeholder="dtT('formServiceEnd')"
              :picker-options="timePickerOptionsEnd"
              style="width: 160px"
              @change="handleServiceEndTimeChange"
            />
          </el-form-item>
          <el-form-item prop="serviceWeekdaysList" :rules="formRules.serviceWeekdaysList">
            <template slot="label">{{ dtT("formServiceWeekdays") }}</template>
            <el-checkbox-group v-model="form.serviceWeekdaysList" @change="validateFormField('serviceWeekdaysList')">
              <el-checkbox v-for="item in weekdayOptions" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item prop="maxDailyAppointments" :rules="formRules.maxDailyAppointments">
            <template slot="label">{{ dtT("formMaxDaily") }}</template>
            <div class="form-unit-wrap">
              <el-input-number v-model="form.maxDailyAppointments" :min="1" :precision="0" :step="1" controls-position="right" class="form-unit-input" />
              <span class="form-unit">{{ dtCommon("unitPerson") }}</span>
            </div>
          </el-form-item>
        </template>

        <template v-if="isEquipmentType(form.resourceType)">
          <el-form-item prop="equipmentModel" :rules="formRules.equipmentModel">
            <template slot="label">{{ dtT("formEquipmentModel") }}</template>
            <el-input v-model="form.equipmentModel" :placeholder="dtT('phEquipmentModel')" maxlength="10" show-word-limit />
          </el-form-item>
          <el-form-item prop="affiliatedUnit" :rules="formRules.affiliatedUnit">
            <template slot="label">{{ dtT("formAffiliatedUnit") }}</template>
            <el-input v-model="form.affiliatedUnit" :placeholder="dtT('phAffiliatedUnit')" maxlength="20" show-word-limit />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ dtCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ dtCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dtCommon('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form label-width="140px" size="small">
        <el-form-item :label="dtT('formResourceType')">
          <span>{{ resourceTypeLabel(viewRow.resourceType) }}</span>
        </el-form-item>
        <el-form-item :label="dtT('formResourceName')">
          <span>{{ viewRow.resourceName || $t('diseaseTreatment.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="dtT('formPhoto')">
          <image-preview v-if="viewRow.photoFileUrl" :src="viewRow.photoFileUrl" :width="120" :height="120" />
          <span v-else>{{ $t('diseaseTreatment.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="dtT('formIntroduction')">
          <span class="view-text">{{ viewRow.introduction || $t('diseaseTreatment.status.dash') }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.contactPhone" :label="dtT('formContactPhone')">
          <span>{{ viewRow.contactPhone }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.affiliatedUnit" :label="dtT('formAffiliatedUnit')">
          <span>{{ viewRow.affiliatedUnit }}</span>
        </el-form-item>
        <el-form-item v-if="isVetType(viewRow.resourceType)" :label="dtT('formTown')">
          <span>{{ viewRow.townName || $t('diseaseTreatment.status.dash') }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.detailAddress" :label="dtT('formDetailAddress')">
          <span>{{ viewRow.detailAddress }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.consultModesList && viewRow.consultModesList.length" :label="dtT('formConsultModes')">
          <span>{{ consultModesLabel(viewRow.consultModesList) }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.serviceArea" :label="dtT('formServiceArea')">
          <span>{{ viewRow.serviceArea }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.feeStandard != null" :label="dtT('formFeeStandard')">
          <span>{{ viewRow.feeStandard }} {{ dtCommon('unitYuanHour') }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.serviceStartTime" :label="dtT('formServiceTime')">
          <span>{{ viewRow.serviceStartTime }} {{ dtCommon('timeSeparator') }} {{ viewRow.serviceEndTime }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.serviceWeekdaysList && viewRow.serviceWeekdaysList.length" :label="dtT('formServiceWeekdays')">
          <span>{{ weekdaysLabel(viewRow.serviceWeekdaysList) }}</span>
        </el-form-item>
        <el-form-item v-if="isOrgType(viewRow.resourceType) && viewRow.maxDailyAppointments != null" :label="dtT('formMaxDaily')">
          <span>{{ viewRow.maxDailyAppointments }} {{ dtCommon('unitPerson') }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.establishDate" :label="dtT('formEstablishDate')">
          <span>{{ viewRow.establishDate }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.teamSize != null" :label="dtT('formTeamSize')">
          <span>{{ viewRow.teamSize }} {{ dtCommon('unitPerson') }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.teamMembers" :label="dtT('formTeamMembers')">
          <span class="view-text">{{ viewRow.teamMembers }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.personInCharge" :label="dtT('formPersonInCharge')">
          <span>{{ viewRow.personInCharge }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.orgLevel" :label="dtT('formOrgLevel')">
          <span>{{ orgLevelLabel(viewRow.orgLevel) }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.equipmentModel" :label="dtT('formEquipmentModel')">
          <span>{{ viewRow.equipmentModel }}</span>
        </el-form-item>
        <el-form-item v-if="showViewAccount" :label="dtT('viewAccountAssigned')">
          <span>{{ viewRow.accountAssigned === 1 ? $t('diseaseTreatment.status.yes') : $t('diseaseTreatment.status.no') }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.assignedLoginName" :label="dtT('viewAssignedLogin')">
          <span>{{ viewRow.assignedLoginName }}</span>
        </el-form-item>
        <el-form-item :label="dtCommon('colShelf')">
          <span>{{ displayPublishStatusText(viewRow.displayPublishStatus) }}</span>
        </el-form-item>
        <el-form-item :label="dtT('viewPublishTime')">
          <span>{{ viewRow.publishTime ? parseTime(viewRow.publishTime) : $t('diseaseTreatment.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="dtT('viewOfflineTime')">
          <span>{{ viewRow.offlineTime ? parseTime(viewRow.offlineTime) : $t('diseaseTreatment.status.dash') }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="viewRow.canEdit" v-hasPermi="['diseaseTreatment:medicalResource:edit']" type="primary" @click="handleEditFromView">{{ dtCommon("edit") }}</el-button>
        <el-button @click="viewOpen = false">{{ dtCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import diseaseTreatmentLocaleMixin from "@/mixins/diseaseTreatmentLocaleMixin"
import {
  listMedicalResource,
  getMedicalResource,
  addMedicalResource,
  updateMedicalResource,
  delMedicalResource,
  publishMedicalResource,
  offlineMedicalResource,
  assignAccountMedicalResource,
  listMedicalResourceTownOptions,
  batchPublishMedicalResource,
  batchOfflineMedicalResource,
  batchAssignAccountMedicalResource
} from "@/api/diseaseTreatment/medicalResource"
import { listInformationCategoryChildren } from "@/api/category/informationCategory"

const PHONE_REG = /^1[3-9]\d{9}$/
const RESOURCE_TYPE_CODE = {
  VET: "004001",
  TEAM: "004002",
  ORG: "004003",
  EQUIPMENT: "004004"
}
const TAB_TYPE_MAP = {
  vet: RESOURCE_TYPE_CODE.VET,
  team: RESOURCE_TYPE_CODE.TEAM,
  org: RESOURCE_TYPE_CODE.ORG,
  equipment: RESOURCE_TYPE_CODE.EQUIPMENT
}
const TYPE_TAB_MAP = {
  [RESOURCE_TYPE_CODE.VET]: "vet",
  [RESOURCE_TYPE_CODE.TEAM]: "team",
  [RESOURCE_TYPE_CODE.ORG]: "org",
  [RESOURCE_TYPE_CODE.EQUIPMENT]: "equipment"
}
/** 存量 tinyint 迁移前 */
const LEGACY_RESOURCE_TYPE = {
  1: RESOURCE_TYPE_CODE.VET,
  2: RESOURCE_TYPE_CODE.TEAM,
  3: RESOURCE_TYPE_CODE.ORG,
  4: RESOURCE_TYPE_CODE.EQUIPMENT
}
const RESOURCE_TYPE_PARENT_CODE = "004"
const RESOURCE_TYPE_CATEGORY_TYPE = "6"

export default {
  name: "DiseaseTreatmentMedicalResource",
  mixins: [diseaseTreatmentLocaleMixin],
  data() {
    return {
      dtNs: "medicalResource",
      activeTab: "vet",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      selectedRows: [],
      resourceTypeOptions: [],
      townOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        resourceType: RESOURCE_TYPE_CODE.VET,
        resourceName: undefined,
        publishStatus: undefined,
        townDeptId: undefined
      },
      form: {},
      imageFileExts: ["jpg", "jpeg", "png"],
      timePickerOptions: { start: "00:00", step: "00:15", end: "23:45" }
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.dtT("dialogEdit") : this.dtT("dialogAdd")
    },
    consultModeOptions() {
      return [1, 2, 3].map((value) => ({ label: this.dtT("consultMode" + value), value }))
    },
    weekdayOptions() {
      return [1, 2, 3, 4, 5, 6, 7].map((value) => ({ label: this.dtT("weekday" + value), value }))
    },
    orgLevelOptions() {
      return [1, 2].map((value) => ({ label: this.dtT("orgLevel" + value), value }))
    },
    showColContact() {
      return this.activeTab !== "equipment"
    },
    showColTown() {
      return this.activeTab === "vet"
    },
    showColAffiliated() {
      return this.activeTab === "vet" || this.activeTab === "team" || this.activeTab === "equipment"
    },
    showColAddress() {
      return this.activeTab === "vet" || this.activeTab === "org"
    },
    showColAccount() {
      return this.activeTab === "vet" || this.activeTab === "org"
    },
    showViewAccount() {
      const t = this.viewRow.resourceType
      return this.isVetType(t) || this.isOrgType(t)
    },
    uploadAction() {
      return process.env.VUE_APP_BASE_API + "/common/upload"
    },
    uploadHeaders() {
      return { Authorization: "Bearer " + getToken() }
    },
    photoFileList() {
      if (!this.form.photoFileUrl) {
        return []
      }
      return [{ name: "photo", url: this.form.photoFileUrl }]
    },
    hidePhotoUpload() {
      return !!(this.form.photoFilePath || this.form.photoFileUrl)
    },
    timePickerOptionsEnd() {
      return {
        start: "00:00",
        step: "00:15",
        end: "23:45",
        minTime: this.form.serviceStartTime || "00:00"
      }
    },
    formRules() {
      const phoneRuleOptional = [{ validator: this.validatePhoneOptional, trigger: "blur" }]
      const rules = {
        resourceType: [{ required: true, message: this.dtT("ruleResourceType"), trigger: "change" }],
        resourceName: [
          { required: true, message: this.dtT("ruleResourceName"), trigger: "blur" },
          { min: 1, max: 10, message: this.dtCommon("ruleLen110"), trigger: "blur" }
        ]
      }
      const t = this.normalizeResourceType(this.form.resourceType)
      if (this.isVetType(t)) {
        rules.photoFilePath = []
        rules.introduction = [{ max: 500, message: this.dtCommon("ruleLen1500"), trigger: "blur" }]
        rules.contactPhone = phoneRuleOptional
        rules.affiliatedUnit = [{ max: 20, message: this.dtCommon("ruleLen120"), trigger: "blur" }]
        rules.detailAddress = [{ max: 100, message: this.dtCommon("ruleLen1100"), trigger: "blur" }]
        rules.consultModesList = [{ validator: this.validateConsultModes, trigger: "change" }]
        rules.serviceArea = [{ max: 100, message: this.dtCommon("ruleLen1100"), trigger: "blur" }]
        rules.feeStandard = []
        rules.serviceStartTime = [{ validator: this.validateServiceTimeOptional, trigger: "change" }]
        rules.serviceWeekdaysList = []
      } else if (this.isOrgType(t) || this.isTeamType(t) || this.isEquipmentType(t)) {
        rules.photoFilePath = []
        rules.introduction = [{ max: 500, message: this.dtCommon("ruleLen1500"), trigger: "blur" }]
      } else {
        rules.photoFilePath = []
        rules.introduction = [{ max: 500, message: this.dtCommon("ruleLen1500"), trigger: "blur" }]
      }
      if (this.isTeamType(t)) {
        rules.contactPhone = phoneRuleOptional
        rules.affiliatedUnit = [{ max: 20, message: this.dtCommon("ruleLen120"), trigger: "blur" }]
        rules.establishDate = []
        rules.teamSize = []
        rules.personInCharge = [{ max: 10, message: this.dtCommon("ruleLen110"), trigger: "blur" }]
      } else if (this.isOrgType(t)) {
        rules.orgLevel = [{ required: true, message: this.dtT("ruleOrgLevel"), trigger: "change" }]
        rules.detailAddress = [{ max: 100, message: this.dtCommon("ruleLen1100"), trigger: "blur" }]
        rules.personInCharge = [{ max: 10, message: this.dtCommon("ruleLen110"), trigger: "blur" }]
        rules.contactPhone = phoneRuleOptional
        rules.serviceStartTime = [{ validator: this.validateServiceTimeOptional, trigger: "change" }]
        rules.serviceWeekdaysList = []
        rules.maxDailyAppointments = []
      } else if (this.isEquipmentType(t)) {
        rules.equipmentModel = [{ max: 10, message: this.dtCommon("ruleLen110"), trigger: "blur" }]
        rules.affiliatedUnit = [{ max: 20, message: this.dtCommon("ruleLen120"), trigger: "blur" }]
      }
      return rules
    }
  },
  created() {
    this.loadResourceTypeOptions().finally(() => {
      this.getList()
    })
    this.loadTownOptions()
  },
  methods: {
    loadTownOptions() {
      listMedicalResourceTownOptions()
        .then((res) => {
          this.townOptions = Array.isArray(res.data) ? res.data : []
        })
        .catch(() => {
          this.townOptions = []
        })
    },
    mapCategoryItem(item) {
      if (!item) {
        return { value: "", label: "" }
      }
      return {
        value: item.code != null ? item.code : item["code"],
        label: item.name != null ? item.name : item["name"]
      }
    },
    loadResourceTypeOptions() {
      return listInformationCategoryChildren(RESOURCE_TYPE_PARENT_CODE, RESOURCE_TYPE_CATEGORY_TYPE)
        .then((res) => {
          const list = res.data || []
          this.resourceTypeOptions = list.map((item) => this.mapCategoryItem(item)).filter((o) => o.value)
        })
        .catch(() => {
          this.resourceTypeOptions = [
            { value: RESOURCE_TYPE_CODE.VET, label: this.dtT("resourceType1") },
            { value: RESOURCE_TYPE_CODE.TEAM, label: this.dtT("resourceType2") },
            { value: RESOURCE_TYPE_CODE.ORG, label: this.dtT("resourceType3") },
            { value: RESOURCE_TYPE_CODE.EQUIPMENT, label: this.dtT("resourceType4") }
          ]
        })
    },
    normalizeResourceType(val) {
      if (val == null || val === "") {
        return ""
      }
      const num = Number(val)
      if (!Number.isNaN(num) && LEGACY_RESOURCE_TYPE[num]) {
        return LEGACY_RESOURCE_TYPE[num]
      }
      return String(val)
    },
    isVetType(val) {
      return this.normalizeResourceType(val) === RESOURCE_TYPE_CODE.VET
    },
    isTeamType(val) {
      return this.normalizeResourceType(val) === RESOURCE_TYPE_CODE.TEAM
    },
    isOrgType(val) {
      return this.normalizeResourceType(val) === RESOURCE_TYPE_CODE.ORG
    },
    isEquipmentType(val) {
      return this.normalizeResourceType(val) === RESOURCE_TYPE_CODE.EQUIPMENT
    },
    resourceTypeLabel(val) {
      const key = this.normalizeResourceType(val)
      const item = this.resourceTypeOptions.find((o) => String(o.value) === key)
      if (item) {
        return item.label
      }
      const legacy = Number(key)
      if (!Number.isNaN(legacy) && legacy >= 1 && legacy <= 4) {
        return this.dtT("resourceType" + legacy)
      }
      return key || this.$t("diseaseTreatment.status.dash")
    },
    orgLevelLabel(val) {
      const item = this.orgLevelOptions.find((o) => o.value === val)
      return item ? item.label : this.$t("diseaseTreatment.status.dash")
    },
    consultModesLabel(list) {
      return (list || [])
        .map((v) => {
          const item = this.consultModeOptions.find((o) => o.value === v)
          return item ? item.label : ""
        })
        .filter(Boolean)
        .join("、")
    },
    weekdaysLabel(list) {
      return (list || [])
        .map((v) => {
          const item = this.weekdayOptions.find((o) => o.value === v)
          return item ? item.label : ""
        })
        .filter(Boolean)
        .join("、")
    },
    validateFormField(field) {
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.validateField(field)
      })
    },
    validatePhone(rule, value, callback) {
      if (!value || !PHONE_REG.test(String(value).trim())) {
        callback(new Error(this.dtCommon("rulePhone")))
        return
      }
      callback()
    },
    validatePhoneOptional(rule, value, callback) {
      if (!value || !String(value).trim()) {
        callback()
        return
      }
      if (!PHONE_REG.test(String(value).trim())) {
        callback(new Error(this.dtCommon("rulePhone")))
        return
      }
      callback()
    },
    validateConsultModes(rule, value, callback) {
      if (!value || !value.length) {
        callback(new Error(this.dtCommon("ruleConsultOne")))
        return
      }
      callback()
    },
    validateWeekdays(rule, value, callback) {
      if (!value || !value.length) {
        callback(new Error(this.dtCommon("ruleWeekdayOne")))
        return
      }
      callback()
    },
    validateServiceTime(rule, value, callback) {
      const start = this.form.serviceStartTime
      const end = this.form.serviceEndTime
      if (!start || !end) {
        callback(new Error(this.dtT("ruleServiceTime")))
        return
      }
      if (start > end) {
        callback(new Error(this.dtCommon("ruleServiceEnd")))
        return
      }
      callback()
    },
    validateServiceTimeOptional(rule, value, callback) {
      const start = this.form.serviceStartTime
      const end = this.form.serviceEndTime
      if (!start && !end) {
        callback()
        return
      }
      if (!start || !end) {
        callback(new Error(this.dtT("ruleServiceTime")))
        return
      }
      if (start > end) {
        callback(new Error(this.dtCommon("ruleServiceEnd")))
        return
      }
      callback()
    },
    handleTabClick() {
      this.queryParams.resourceType = TAB_TYPE_MAP[this.activeTab]
      this.queryParams.pageNum = 1
      if (this.activeTab !== "vet") {
        this.queryParams.townDeptId = undefined
      }
      this.getList()
    },
    handleQueryTypeChange(val) {
      const key = this.normalizeResourceType(val)
      const tab = TYPE_TAB_MAP[key]
      if (tab) {
        this.activeTab = tab
      }
      if (key !== RESOURCE_TYPE_CODE.VET) {
        this.queryParams.townDeptId = undefined
      }
      this.handleQuery()
    },
    normalizeIntList(val) {
      if (Array.isArray(val)) {
        return val.map((v) => Number(v)).filter((n) => !Number.isNaN(n))
      }
      if (typeof val === "string" && val.trim()) {
        return val
          .split(",")
          .map((s) => parseInt(s.trim(), 10))
          .filter((n) => !Number.isNaN(n))
      }
      return []
    },
    resolveDisplayPublishStatus(row) {
      if (row.displayPublishStatus != null) {
        return row.displayPublishStatus
      }
      const ps = Number(row.publishStatus)
      if (ps === 1) {
        return 1
      }
      if (row.offlineTime) {
        return 2
      }
      return 0
    },
    /** 列表/详情：补齐三态展示与操作按钮显隐（与后端 MedicalResourcePublishStatusResolver 一致） */
    normalizeMedicalResourceRow(row) {
      if (!row) {
        return {}
      }
      const displayPublishStatus = this.resolveDisplayPublishStatus(row)
      const canModify = Number(row.publishStatus) === 0 && String(row.delFlag || "0") === "0"
      const isPublished = Number(row.publishStatus) === 1
      const resourceType = this.normalizeResourceType(row.resourceType)
      return {
        ...row,
        resourceType,
        displayPublishStatus,
        consultModesList: this.normalizeIntList(row.consultModesList != null ? row.consultModesList : row.consultModes),
        serviceWeekdaysList: this.normalizeIntList(row.serviceWeekdaysList != null ? row.serviceWeekdaysList : row.serviceWeekdays),
        canEdit: row.canEdit != null ? row.canEdit : canModify,
        canDelete: row.canDelete != null ? row.canDelete : canModify,
        canPublish: row.canPublish != null ? row.canPublish : canModify,
        canOffline: row.canOffline != null ? row.canOffline : isPublished,
        canAssignAccount:
          row.canAssignAccount != null
            ? row.canAssignAccount
            : (this.isVetType(resourceType) || this.isOrgType(resourceType)) && Number(row.accountAssigned) === 0 && canModify
      }
    },
    clearTableSelection() {
      this.selectedRows = []
      this.$refs.table && this.$refs.table.clearSelection()
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    unselectBatchInvalidRows(invalidRows) {
      const table = this.$refs.table
      if (!table || !invalidRows.length) {
        return
      }
      invalidRows.forEach((row) => {
        table.toggleRowSelection(row, false)
      })
    },
    /** 批量操作：筛掉不可操作行并取消勾选，返回仍可操作的行 */
    prepareBatchShelfRows(checkFn, autoUncheckMsgKey) {
      const rows = this.selectedRows
      if (!rows.length) {
        this.$modal.msgWarning(this.dtT("msgSelectRows"))
        return null
      }
      const invalidRows = rows.filter((row) => !checkFn(row))
      const validRows = rows.filter((row) => checkFn(row))
      if (invalidRows.length) {
        this.unselectBatchInvalidRows(invalidRows)
        const names = invalidRows
          .map((row) => row.resourceName || this.$t("diseaseTreatment.status.dash"))
          .filter(Boolean)
          .join("、")
        this.$modal.msgWarning(this.dtT(autoUncheckMsgKey, { names }))
      }
      if (!validRows.length) {
        return null
      }
      return validRows
    },
    runBatchShelfAction(options) {
      const { checkFn, autoUncheckMsgKey, confirmKey, loadingKey, requestFn, successMsgKey } = options
      const validRows = this.prepareBatchShelfRows(checkFn, autoUncheckMsgKey)
      if (!validRows) {
        return
      }
      const ids = validRows.map((row) => row.id)
      this.$nextTick(() => {
        this.$modal
          .confirm(this.dtT(confirmKey))
          .then(() => {
            this.$modal.loading(this.dtCommon(loadingKey))
            return requestFn(ids)
          })
          .then(() => {
            this.$modal.msgSuccess(this.dtCommon(successMsgKey))
            this.clearTableSelection()
            this.getList()
          })
          .catch(() => {})
          .finally(() => {
            this.$modal.closeLoading()
          })
      })
    },
    handleBatchPublish() {
      this.runBatchShelfAction({
        checkFn: (row) => row.canPublish,
        autoUncheckMsgKey: "msgBatchAutoUncheckPublish",
        confirmKey: "confirmBatchPublish",
        loadingKey: "batchPublishing",
        requestFn: batchPublishMedicalResource,
        successMsgKey: "msgPubOk"
      })
    },
    handleBatchOffline() {
      this.runBatchShelfAction({
        checkFn: (row) => row.canOffline,
        autoUncheckMsgKey: "msgBatchAutoUncheckOffline",
        confirmKey: "confirmBatchOffline",
        loadingKey: "batchOfflining",
        requestFn: batchOfflineMedicalResource,
        successMsgKey: "msgOffOk"
      })
    },
    handleBatchAssignAccount() {
      if (!this.showColAccount) {
        return
      }
      this.runBatchShelfAction({
        checkFn: (row) => row.canAssignAccount,
        autoUncheckMsgKey: "msgBatchAutoUncheckAssignAccount",
        confirmKey: "confirmBatchAssign",
        loadingKey: "batchAssigning",
        requestFn: batchAssignAccountMedicalResource,
        successMsgKey: "msgAssignOk"
      })
    },
    getList() {
      this.loading = true
      listMedicalResource(this.queryParams)
        .then((res) => {
          this.tableList = (res.rows || []).map((row) => this.normalizeMedicalResourceRow(row))
          this.total = res.total != null ? res.total : 0
        })
        .catch(() => {
          this.tableList = []
          this.total = 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.resourceName = undefined
      this.queryParams.publishStatus = undefined
      this.queryParams.townDeptId = undefined
      this.queryParams.resourceType = TAB_TYPE_MAP[this.activeTab]
      this.resetForm("queryForm")
      this.handleQuery()
    },
    allConsultModeValues() {
      return this.consultModeOptions.map((item) => item.value)
    },
    hasServiceScheduleType(resourceType) {
      const t = this.normalizeResourceType(resourceType)
      return this.isVetType(t) || this.isOrgType(t)
    },
    defaultServiceStartTime() {
      return "08:00"
    },
    defaultServiceEndTime() {
      return "18:00"
    },
    defaultServiceWeekdaysList() {
      return [1, 2, 3, 4, 5]
    },
    applyDefaultServiceSchedule(resourceType) {
      if (!this.hasServiceScheduleType(resourceType)) {
        return
      }
      this.form.serviceStartTime = this.defaultServiceStartTime()
      this.form.serviceWeekdaysList = this.defaultServiceWeekdaysList()
      this.$nextTick(() => {
        this.form.serviceEndTime = this.defaultServiceEndTime()
      })
    },
    handleServiceStartTimeChange() {
      const start = this.form.serviceStartTime
      const end = this.form.serviceEndTime
      if (start && (!end || end <= start)) {
        this.$nextTick(() => {
          this.form.serviceEndTime = this.defaultServiceEndTime()
          this.validateFormField("serviceStartTime")
        })
        return
      }
      this.validateFormField("serviceStartTime")
    },
    handleServiceEndTimeChange() {
      this.validateFormField("serviceStartTime")
    },
    resetFormModel() {
      const resourceType = TAB_TYPE_MAP[this.activeTab]
      const hasServiceSchedule = this.hasServiceScheduleType(resourceType)
      this.form = {
        id: undefined,
        resourceType,
        resourceName: undefined,
        photoFileUrl: undefined,
        photoFilePath: undefined,
        introduction: undefined,
        contactPhone: undefined,
        affiliatedUnit: undefined,
        townDeptId: undefined,
        detailAddress: undefined,
        consultModesList: this.isVetType(resourceType) ? this.allConsultModeValues() : [],
        serviceArea: undefined,
        feeStandard: undefined,
        serviceStartTime: hasServiceSchedule ? this.defaultServiceStartTime() : undefined,
        serviceEndTime: hasServiceSchedule ? this.defaultServiceEndTime() : undefined,
        serviceWeekdaysList: hasServiceSchedule ? this.defaultServiceWeekdaysList() : [],
        maxDailyAppointments: undefined,
        establishDate: undefined,
        teamSize: undefined,
        teamMembers: undefined,
        personInCharge: undefined,
        orgLevel: undefined,
        equipmentModel: undefined
      }
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => {
        if (this.hasServiceScheduleType(this.form.resourceType)) {
          this.form.serviceEndTime = this.defaultServiceEndTime()
        }
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    fillFormFromApi(data) {
      const row = this.normalizeMedicalResourceRow(data)
      this.form = {
        id: row.id,
        resourceType: this.normalizeResourceType(row.resourceType),
        resourceName: row.resourceName,
        photoFileUrl: row.photoFileUrl,
        photoFilePath: row.photoFilePath,
        introduction: row.introduction,
        contactPhone: row.contactPhone,
        affiliatedUnit: row.affiliatedUnit,
        townDeptId: this.isVetType(row.resourceType) ? row.townDeptId : undefined,
        detailAddress: row.detailAddress,
        consultModesList: [...(row.consultModesList || [])],
        serviceArea: row.serviceArea,
        feeStandard: row.feeStandard,
        serviceStartTime: row.serviceStartTime,
        serviceEndTime: row.serviceEndTime,
        serviceWeekdaysList: [...(row.serviceWeekdaysList || [])],
        maxDailyAppointments: this.isOrgType(row.resourceType) ? row.maxDailyAppointments : undefined,
        establishDate: row.establishDate,
        teamSize: row.teamSize,
        teamMembers: row.teamMembers,
        personInCharge: row.personInCharge,
        orgLevel: row.orgLevel,
        equipmentModel: row.equipmentModel
      }
    },
    handleEdit(row) {
      if (!row.canEdit) {
        return
      }
      getMedicalResource(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.fillFormFromApi(data)
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleEditFromView() {
      this.viewOpen = false
      this.handleEdit(this.viewRow)
    },
    handleView(row) {
      getMedicalResource(row.id).then((res) => {
        this.viewRow = this.normalizeMedicalResourceRow(res.data || {})
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      if (!row.canDelete) {
        this.$modal.msgWarning(this.dtT("msgPublishedCannotDelete"))
        return
      }
      this.$modal
        .confirm(this.dtT("confirmDelete", { name: row.resourceName }))
        .then(() => delMedicalResource(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dtCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handlePublish(row) {
      this.$modal
        .confirm(this.dtT("confirmPublish"))
        .then(() => publishMedicalResource(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dtCommon("msgPubOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleOffline(row) {
      this.$modal
        .confirm(this.dtT("confirmOffline"))
        .then(() => offlineMedicalResource(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dtCommon("msgOffOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleAssignAccount(row) {
      this.$modal
        .confirm(this.dtT("confirmAssign"))
        .then(() => assignAccountMedicalResource(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dtCommon("msgAssignOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleFormTypeChange() {
      const t = this.normalizeResourceType(this.form.resourceType)
      if (this.isVetType(t)) {
        this.form.consultModesList = this.allConsultModeValues()
      } else {
        this.form.townDeptId = undefined
        this.form.detailAddress = undefined
        this.form.consultModesList = []
        this.form.serviceArea = undefined
        this.form.feeStandard = undefined
      }
      if (!this.isTeamType(t)) {
        this.form.establishDate = undefined
        this.form.teamSize = undefined
        this.form.teamMembers = undefined
      }
      if (!this.isOrgType(t)) {
        this.form.orgLevel = undefined
        this.form.maxDailyAppointments = undefined
      } else {
        this.form.maxDailyAppointments = undefined
      }
      if (!this.isVetType(t) && !this.isOrgType(t)) {
        this.form.serviceStartTime = undefined
        this.form.serviceEndTime = undefined
        this.form.serviceWeekdaysList = []
      } else {
        this.applyDefaultServiceSchedule(t)
      }
      if (!this.isVetType(t) && !this.isTeamType(t) && !this.isEquipmentType(t)) {
        this.form.affiliatedUnit = undefined
      }
      if (!this.isTeamType(t) && !this.isOrgType(t)) {
        this.form.personInCharge = undefined
      }
      if (!this.isVetType(t) && !this.isTeamType(t) && !this.isOrgType(t)) {
        this.form.contactPhone = undefined
      }
      if (!this.isEquipmentType(t)) {
        this.form.equipmentModel = undefined
      }
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    extOf(fileName) {
      if (!fileName || fileName.lastIndexOf(".") < 0) {
        return ""
      }
      return fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase()
    },
    beforePhotoUpload(file) {
      const ext = this.extOf(file.name)
      if (!this.imageFileExts.includes(ext)) {
        this.$modal.msgError(this.dtCommon("errPhotoFmt"))
        return false
      }
      if (file.name.includes(",")) {
        this.$modal.msgError(this.dtCommon("errComma"))
        return false
      }
      if (file.size / 1024 / 1024 >= 10) {
        this.$modal.msgError(this.dtCommon("errPhotoMb"))
        return false
      }
      this.$modal.loading(this.dtCommon("uploadingImg"))
      return true
    },
    handlePhotoUploadSuccess(res) {
      this.$modal.closeLoading()
      if (res.code === 200) {
        this.form.photoFileUrl = res.url
        this.form.photoFilePath = res.fileName
        this.$refs.form && this.$refs.form.validateField("photoFilePath")
      } else {
        this.$modal.msgError(res.msg || this.dtCommon("errUploadFail"))
      }
    },
    handlePhotoRemove() {
      this.form.photoFileUrl = undefined
      this.form.photoFilePath = undefined
    },
    handleUploadHttpError() {
      this.$modal.closeLoading()
      this.$modal.msgError(this.dtCommon("errUploadRetry"))
    },
    buildSubmitPayload() {
      const t = this.normalizeResourceType(this.form.resourceType)
      const payload = {
        resourceType: t,
        resourceName: (this.form.resourceName || "").trim(),
        photoFileUrl: this.form.photoFileUrl,
        photoFilePath: this.form.photoFilePath,
        introduction: (this.form.introduction || "").trim()
      }
      if (this.isVetType(t)) {
        Object.assign(payload, {
          contactPhone: this.form.contactPhone,
          affiliatedUnit: (this.form.affiliatedUnit || "").trim(),
          townDeptId: this.form.townDeptId,
          detailAddress: (this.form.detailAddress || "").trim(),
          consultModesList: this.form.consultModesList,
          serviceArea: (this.form.serviceArea || "").trim(),
          feeStandard: this.form.feeStandard,
          serviceStartTime: this.form.serviceStartTime,
          serviceEndTime: this.form.serviceEndTime,
          serviceWeekdaysList: this.form.serviceWeekdaysList
        })
      } else if (this.isTeamType(t)) {
        Object.assign(payload, {
          contactPhone: this.form.contactPhone,
          affiliatedUnit: (this.form.affiliatedUnit || "").trim(),
          establishDate: this.form.establishDate,
          teamSize: this.form.teamSize,
          teamMembers: this.form.teamMembers ? this.form.teamMembers.trim() : undefined,
          personInCharge: (this.form.personInCharge || "").trim()
        })
      } else if (this.isOrgType(t)) {
        Object.assign(payload, {
          orgLevel: this.form.orgLevel,
          detailAddress: (this.form.detailAddress || "").trim(),
          personInCharge: (this.form.personInCharge || "").trim(),
          contactPhone: this.form.contactPhone,
          serviceStartTime: this.form.serviceStartTime,
          serviceEndTime: this.form.serviceEndTime,
          serviceWeekdaysList: this.form.serviceWeekdaysList,
          maxDailyAppointments: this.form.maxDailyAppointments
        })
      } else if (this.isEquipmentType(t)) {
        Object.assign(payload, {
          equipmentModel: (this.form.equipmentModel || "").trim(),
          affiliatedUnit: (this.form.affiliatedUnit || "").trim()
        })
      }
      return payload
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildSubmitPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateMedicalResource(payload).then(() => {
            this.$modal.msgSuccess(this.dtCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addMedicalResource(payload).then(() => {
            this.$modal.msgSuccess(this.dtCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
.medical-resource-page ::v-deep .el-tabs__content {
  display: none;
}
.form-unit-wrap {
  display: flex;
  align-items: center;
  width: 100%;
}
.form-unit-wrap .form-unit-input {
  flex: 1;
  width: auto;
}
.form-unit-wrap ::v-deep .el-input-number {
  width: 100%;
}
.form-unit {
  flex-shrink: 0;
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
}
.time-sep {
  margin: 0 8px;
  color: #909399;
}
.hide ::v-deep .el-upload--picture-card {
  display: none;
}
.view-text {
  white-space: pre-wrap;
  word-break: break-word;
}
.table-card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 8px;
}
</style>
