<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="projectName">
          <template slot="label">{{ ipT("queryProjectName") }}</template>
          <el-input
            v-model="queryParams.projectName"
            :placeholder="ipT('queryProjectNamePh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="projectType">
          <template slot="label">{{ ipT("queryProjectType") }}</template>
          <el-select v-model="queryParams.projectType" :placeholder="ipCommon('pleaseSelect')" clearable style="width: 160px">
            <el-option v-for="item in projectTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="publishStatus">
          <template slot="label">{{ ipT("queryPublishStatus") }}</template>
          <el-select v-model="queryParams.publishStatus" :placeholder="ipCommon('pleaseSelect')" clearable style="width: 140px">
            <el-option :label="$t('innovationPlatform.status.unpublished')" :value="0" />
            <el-option :label="$t('innovationPlatform.status.published')" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ ipCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ ipCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['innovationPlatform:techProjectGuide:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ ipCommon("add") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <el-table-column :label="ipT('colProjectName')" prop="projectName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="ipT('colProjectType')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ projectTypeLabel(scope.row.projectType) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ipT('colApplicationTarget')" prop="applicationTarget" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="ipT('colAppStart')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.applicationStartDate || $t('innovationPlatform.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ipT('colAppEnd')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.applicationEndDate || $t('innovationPlatform.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ipT('colProjectPeriod')" prop="projectPeriod" align="center" width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="ipT('colPersonInCharge')" prop="personInCharge" align="center" width="90" />
        <el-table-column :label="ipT('colContactPhone')" prop="contactPhone" align="center" width="120" />
        <el-table-column :label="ipCommon('colPub')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.publishTime ? parseTime(scope.row.publishTime, '{y}-{m}-{d}') : $t('innovationPlatform.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ipCommon('colShelf')" align="center" width="92">
          <template slot-scope="scope">
            <span>{{ publishStatusText(scope.row.publishStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ipCommon('colOp')" align="center" class-name="small-padding fixed-width" width="280">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['innovationPlatform:techProjectGuide:query']"
              type="text"
              size="mini"
              @click="handleView(scope.row)"
            >{{ ipCommon("view") }}</el-button>
            <el-button
              v-hasPermi="['innovationPlatform:techProjectGuide:edit']"
              v-if="canEdit(scope.row)"
              type="text"
              size="mini"
              @click="handleEdit(scope.row)"
            >{{ ipCommon("edit") }}</el-button>
            <el-button
              v-hasPermi="['innovationPlatform:techProjectGuide:remove']"
              v-if="canDelete(scope.row)"
              type="text"
              size="mini"
              @click="handleDelete(scope.row)"
            >{{ ipCommon("delete") }}</el-button>
            <el-button
              v-hasPermi="['innovationPlatform:techProjectGuide:publish']"
              v-if="canPublish(scope.row)"
              type="text"
              size="mini"
              @click="handlePublish(scope.row)"
            >{{ ipCommon("publish") }}</el-button>
            <el-button
              v-hasPermi="['innovationPlatform:techProjectGuide:offline']"
              v-if="canOffline(scope.row)"
              type="text"
              size="mini"
              @click="handleOffline(scope.row)"
            >{{ ipCommon("offline") }}</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="120px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="projectName" :rules="formRules.projectName">
              <template slot="label">{{ ipT("formProjectName") }}</template>
              <el-input v-model="form.projectName" :placeholder="ipT('phProjectName')" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="projectType" :rules="formRules.projectType">
              <template slot="label">{{ ipT("formProjectType") }}</template>
              <el-select v-model="form.projectType" :placeholder="ipCommon('pleaseSelect')" style="width: 100%">
                <el-option v-for="item in projectTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="projectIntro" :rules="formRules.projectIntro">
          <template slot="label">{{ ipT("formProjectIntro") }}</template>
          <el-input v-model="form.projectIntro" type="textarea" :rows="2" :placeholder="ipT('phProjectIntro')" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="applicationTarget" :rules="formRules.applicationTarget">
          <template slot="label">{{ ipT("formApplicationTarget") }}</template>
          <el-input v-model="form.applicationTarget" :placeholder="ipT('phApplicationTarget')" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item prop="applicationDateRange" :rules="formRules.applicationDateRange">
          <template slot="label">{{ ipT("formApplicationDate") }}</template>
          <el-date-picker
            v-model="form.applicationDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :range-separator="ipT('appRangeSeparator')"
            :start-placeholder="ipT('appRangeStartPh')"
            :end-placeholder="ipT('appRangeEndPh')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="projectPeriod" :rules="formRules.projectPeriod">
          <template slot="label">{{ ipT("formProjectPeriod") }}</template>
          <el-input v-model="form.projectPeriod" :placeholder="ipT('phProjectPeriod')" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="applicationConditions" :rules="formRules.applicationConditions">
          <template slot="label">{{ ipT("formApplicationConditions") }}</template>
          <el-input v-model="form.applicationConditions" type="textarea" :rows="3" :placeholder="ipT('phApplicationConditions')" />
        </el-form-item>
        <el-form-item prop="applicationProcess" :rules="formRules.applicationProcess">
          <template slot="label">{{ ipT("formApplicationProcess") }}</template>
          <el-input v-model="form.applicationProcess" type="textarea" :rows="3" :placeholder="ipT('phApplicationProcess')" />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="personInCharge" :rules="formRules.personInCharge">
              <template slot="label">{{ ipT("formPersonInCharge") }}</template>
              <el-input v-model="form.personInCharge" :placeholder="ipT('phPersonInCharge')" maxlength="10" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="contactPhone" :rules="formRules.contactPhone">
              <template slot="label">{{ ipT("formContactPhone") }}</template>
              <el-input v-model="form.contactPhone" :placeholder="ipT('phContactPhone')" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="attachmentFilePath">
          <template slot="label">{{ ipT("formAttachment") }}</template>
          <el-upload
            class="upload-file-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforeAttachmentUpload"
            :on-success="handleAttachmentUploadSuccess"
            :on-error="handleUploadHttpError"
            :show-file-list="false"
            :disabled="dialogEdit && !canEditUploadRow"
          >
            <el-button size="mini" type="primary" :disabled="dialogEdit && !canEditUploadRow">{{ ipCommon("pickFile") }}</el-button>
          </el-upload>
          <div class="el-upload__tip">{{ ipCommon("tipAttachment") }}</div>
          <ul v-if="form.attachmentFilePath" class="upload-file-list el-upload-list el-upload-list--text">
            <li class="el-upload-list__item ele-upload-list__item-content">
              <el-link :href="form.attachmentFileUrl || '#'" :underline="false" target="_blank">
                <span class="el-icon-document"> {{ form.attachmentFileName }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action">
                <el-link v-if="!(dialogEdit && !canEditUploadRow)" type="danger" :underline="false" @click="clearAttachment">{{ ipCommon("del") }}</el-link>
              </div>
            </li>
          </ul>
        </el-form-item>
        <el-form-item prop="coverFilePath">
          <template slot="label">{{ ipT("formCover") }}</template>
          <el-upload
            list-type="picture-card"
            :class="{ hide: hideCoverUpload }"
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforeCoverUpload"
            :on-success="handleCoverUploadSuccess"
            :on-error="handleUploadHttpError"
            :on-remove="handleCoverRemove"
            :limit="1"
            :file-list="coverFileList"
            :disabled="dialogEdit && !canEditUploadRow"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <div class="el-upload__tip">{{ ipCommon("tipCover") }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="!dialogEdit"
          v-hasPermi="['innovationPlatform:techProjectGuide:publish']"
          type="warning"
          @click="submitForm(true)"
        >{{ ipT("btnSaveAndPublish") }}</el-button>
        <el-button type="primary" @click="submitForm(false)">{{ ipCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ ipCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="ipCommon('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form label-width="120px" size="small">
        <el-form-item :label="ipT('formProjectName')">
          <span>{{ viewRow.projectName }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formProjectType')">
          <span>{{ projectTypeLabel(viewRow.projectType) }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formProjectIntro')">
          <span>{{ viewRow.projectIntro || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formApplicationTarget')">
          <span>{{ viewRow.applicationTarget || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formApplicationDate')">
          <span>{{ applicationDateRangeText(viewRow) }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formProjectPeriod')">
          <span>{{ viewRow.projectPeriod || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formApplicationConditions')">
          <span class="view-text-block">{{ viewRow.applicationConditions || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formApplicationProcess')">
          <span class="view-text-block">{{ viewRow.applicationProcess || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formPersonInCharge')">
          <span>{{ viewRow.personInCharge || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formContactPhone')">
          <span>{{ viewRow.contactPhone || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formAttachment')">
          <el-link v-if="viewRow.attachmentFileUrl" type="primary" :href="viewRow.attachmentFileUrl" target="_blank">{{ viewRow.attachmentFileName }}</el-link>
          <span v-else>{{ $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('formCover')">
          <image-preview v-if="viewRow.coverFileUrl" :src="viewRow.coverFileUrl" :width="200" :height="120" />
          <span v-else>{{ $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipCommon('colShelf')">
          <span>{{ publishStatusText(viewRow.publishStatus) }}</span>
        </el-form-item>
        <el-form-item :label="ipCommon('viewPubTime')">
          <span>{{ viewRow.publishTime ? parseTime(viewRow.publishTime) : $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipCommon('viewOfflineTime')">
          <span>{{ viewRow.offlineTime ? parseTime(viewRow.offlineTime) : $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('viewCreateBy')">
          <span>{{ viewRow.createBy || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('viewUpdateBy')">
          <span>{{ viewRow.updateBy || $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="ipT('viewUpdateTime')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : $t('innovationPlatform.status.dash') }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-hasPermi="['innovationPlatform:techProjectGuide:publish']"
          v-if="canPublish(viewRow)"
          type="warning"
          @click="handlePublish(viewRow)"
        >{{ ipCommon("publish") }}</el-button>
        <el-button
          v-hasPermi="['innovationPlatform:techProjectGuide:offline']"
          v-if="canOffline(viewRow)"
          type="warning"
          plain
          @click="handleOffline(viewRow)"
        >{{ ipCommon("offline") }}</el-button>
        <el-button @click="viewOpen = false">{{ ipCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import innovationPlatformLocaleMixin from "@/mixins/innovationPlatformLocaleMixin"
import {
  listTechProjectGuide,
  getTechProjectGuide,
  addTechProjectGuide,
  updateTechProjectGuide,
  delTechProjectGuide,
  publishTechProjectGuide,
  offlineTechProjectGuide
} from "@/api/innovationPlatform/techProjectGuide"
import { listInformationCategoryChildren } from "@/api/category/informationCategory"

const PUBLISH_STATUS = { UNPUBLISHED: 0, PUBLISHED: 1 }
const PHONE_REG = /^1[3-9]\d{9}$/
/** 资讯类别：parentCode=002（与后端 TechProjectGuideTypeValidator 一致） */
const PROJECT_TYPE_PARENT_CODE = "002"
/** 存量数据迁移前可能仍为 1～4，展示用 */
const LEGACY_PROJECT_TYPE_LABELS = {
  1: "projectType1",
  2: "projectType2",
  3: "projectType3",
  4: "projectType4"
}

export default {
  name: "TechProjectGuide",
  mixins: [innovationPlatformLocaleMixin],
  data() {
    return {
      ipNs: "techProjectGuide",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      canEditUploadRow: true,
      formKey: 0,
      total: 0,
      tableList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        projectName: undefined,
        projectType: undefined,
        publishStatus: undefined
      },
      form: {},
      projectTypeOptions: [],
      attachmentFileExts: ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"],
      coverFileExts: ["jpg", "jpeg", "png"]
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.ipT("dialogEdit") : this.ipT("dialogAdd")
    },
    formRules() {
      return {
        projectName: [
          { required: true, message: this.ipT("ruleProjectNameRequired"), trigger: "blur" },
          { min: 1, max: 20, message: this.ipCommon("ruleLen120"), trigger: "blur" }
        ],
        projectType: [{ required: true, message: this.ipT("ruleProjectTypeRequired"), trigger: "change" }],
        projectIntro: [
          { required: true, message: this.ipT("ruleProjectIntroRequired"), trigger: "blur" },
          { min: 1, max: 50, message: this.ipCommon("ruleLen50"), trigger: "blur" }
        ],
        applicationTarget: [
          { required: true, message: this.ipT("ruleApplicationTargetRequired"), trigger: "blur" },
          { min: 1, max: 200, message: this.ipCommon("ruleLen200"), trigger: "blur" }
        ],
        applicationDateRange: [
          { required: true, message: this.ipT("ruleApplicationDateRequired"), trigger: "change" },
          { validator: this.validateApplicationDateRange, trigger: "change" }
        ],
        projectPeriod: [
          { required: true, message: this.ipT("ruleProjectPeriodRequired"), trigger: "blur" },
          { min: 1, max: 50, message: this.ipCommon("ruleLen50"), trigger: "blur" }
        ],
        applicationConditions: [{ required: true, message: this.ipT("ruleApplicationConditionsRequired"), trigger: "blur" }],
        applicationProcess: [{ required: true, message: this.ipT("ruleApplicationProcessRequired"), trigger: "blur" }],
        personInCharge: [
          { required: true, message: this.ipT("rulePersonInChargeRequired"), trigger: "blur" },
          { min: 1, max: 10, message: this.ipCommon("ruleLen10"), trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: this.ipT("ruleContactPhoneRequired"), trigger: "blur" },
          { validator: this.validateContactPhone, trigger: "blur" }
        ]
      }
    },
    uploadAction() {
      return process.env.VUE_APP_BASE_API + "/common/upload"
    },
    uploadHeaders() {
      return { Authorization: "Bearer " + getToken() }
    },
    coverFileList() {
      if (!this.form.coverFileUrl) {
        return []
      }
      return [{ name: "cover", url: this.form.coverFileUrl }]
    },
    hideCoverUpload() {
      return !!(this.form.coverFilePath || this.form.coverFileUrl)
    }
  },
  created() {
    this.loadProjectTypeOptions()
    this.getList()
  },
  methods: {
    mapCategoryItem(item) {
      if (!item) {
        return { value: "", label: "" }
      }
      return {
        value: item["code"] != null ? item["code"] : item.code,
        label: item["name"] != null ? item["name"] : item.name
      }
    },
    loadProjectTypeOptions() {
      return listInformationCategoryChildren(PROJECT_TYPE_PARENT_CODE).then((res) => {
        const list = res.data || []
        this.projectTypeOptions = list.map((item) => this.mapCategoryItem(item)).filter((o) => o.value)
      })
    },
    projectTypeLabel(val) {
      if (val == null || val === "") {
        return ""
      }
      const key = String(val)
      const item = this.projectTypeOptions.find((o) => String(o.value) === key)
      if (item) {
        return item.label
      }
      const legacyKey = LEGACY_PROJECT_TYPE_LABELS[val]
      if (legacyKey) {
        return this.ipT(legacyKey)
      }
      return key
    },
    validateContactPhone(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (!PHONE_REG.test(String(value).trim())) {
        callback(new Error(this.ipT("rulePhoneInvalid")))
      } else {
        callback()
      }
    },
    applicationDateRangeText(row) {
      if (!row || !row.applicationStartDate || !row.applicationEndDate) {
        return this.$t("innovationPlatform.status.dash")
      }
      return `${row.applicationStartDate} ${this.ipT("appRangeSeparator")} ${row.applicationEndDate}`
    },
    validateApplicationDateRange(rule, value, callback) {
      if (!value || value.length !== 2 || !value[0] || !value[1]) {
        callback(new Error(this.ipT("ruleApplicationDateRequired")))
        return
      }
      if (value[0] > value[1]) {
        callback(new Error(this.ipT("ruleAppEndBeforeStart")))
        return
      }
      callback()
    },
    canEdit(row) {
      return row && Number(row.publishStatus) === PUBLISH_STATUS.UNPUBLISHED
    },
    canPublish(row) {
      return row && Number(row.publishStatus) === PUBLISH_STATUS.UNPUBLISHED
    },
    canOffline(row) {
      return row && Number(row.publishStatus) === PUBLISH_STATUS.PUBLISHED
    },
    canDelete(row) {
      return row && Number(row.publishStatus) === PUBLISH_STATUS.UNPUBLISHED
    },
    getList() {
      this.loading = true
      listTechProjectGuide(this.queryParams)
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total != null ? res.total : 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.projectName = undefined
      this.queryParams.projectType = undefined
      this.queryParams.publishStatus = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        projectName: undefined,
        projectType: undefined,
        projectIntro: undefined,
        applicationTarget: undefined,
        applicationDateRange: null,
        projectPeriod: undefined,
        applicationConditions: undefined,
        applicationProcess: undefined,
        personInCharge: undefined,
        contactPhone: undefined,
        attachmentFileUrl: undefined,
        attachmentFilePath: undefined,
        attachmentFileName: undefined,
        coverFileUrl: undefined,
        coverFilePath: undefined
      }
    },
    buildPayload() {
      return {
        projectName: this.form.projectName,
        projectType: this.form.projectType,
        projectIntro: this.form.projectIntro,
        applicationTarget: this.form.applicationTarget,
        applicationStartDate: this.form.applicationDateRange[0],
        applicationEndDate: this.form.applicationDateRange[1],
        projectPeriod: this.form.projectPeriod,
        applicationConditions: this.form.applicationConditions,
        applicationProcess: this.form.applicationProcess,
        personInCharge: this.form.personInCharge,
        contactPhone: this.form.contactPhone,
        attachmentFileUrl: this.form.attachmentFileUrl,
        attachmentFilePath: this.form.attachmentFilePath,
        attachmentFileName: this.form.attachmentFileName,
        coverFileUrl: this.form.coverFileUrl,
        coverFilePath: this.form.coverFilePath
      }
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.canEditUploadRow = true
      this.open = true
      this.$nextTick(() => this.resetForm("form"))
    },
    handleEdit(row) {
      if (!this.canEdit(row)) {
        this.$modal.msgWarning(this.ipT("msgPublishedCannotEdit"))
        return
      }
      getTechProjectGuide(row.id).then((res) => {
        const data = res.data || {}
        if (Number(data.publishStatus) === PUBLISH_STATUS.PUBLISHED) {
          this.$modal.msgWarning(this.ipT("msgPublishedCannotEdit"))
          return
        }
        this.formKey += 1
        this.dialogEdit = true
        this.canEditUploadRow = Number(data.publishStatus) === PUBLISH_STATUS.UNPUBLISHED
        this.form = {
          id: data.id,
          projectName: data.projectName,
          projectType: data.projectType,
          projectIntro: data.projectIntro,
          applicationTarget: data.applicationTarget,
          applicationDateRange:
            data.applicationStartDate && data.applicationEndDate
              ? [data.applicationStartDate, data.applicationEndDate]
              : null,
          projectPeriod: data.projectPeriod,
          applicationConditions: data.applicationConditions,
          applicationProcess: data.applicationProcess,
          personInCharge: data.personInCharge,
          contactPhone: data.contactPhone,
          attachmentFileUrl: data.attachmentFileUrl,
          attachmentFilePath: data.attachmentFilePath,
          attachmentFileName: data.attachmentFileName,
          coverFileUrl: data.coverFileUrl,
          coverFilePath: data.coverFilePath
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getTechProjectGuide(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      if (!this.canDelete(row)) {
        this.$modal.msgWarning(this.ipT("msgPublishedCannotDelete"))
        return
      }
      this.$modal
        .confirm(this.ipT("confirmDelete", { id: row.id }))
        .then(() => delTechProjectGuide(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.ipCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handlePublish(row) {
      this.$modal
        .confirm(this.ipT("confirmPublish"))
        .then(() => publishTechProjectGuide(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.ipCommon("msgPubOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    handleOffline(row) {
      this.$modal
        .confirm(this.ipT("confirmOffline"))
        .then(() => offlineTechProjectGuide(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.ipCommon("msgOffOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    extOf(fileName) {
      if (!fileName || fileName.lastIndexOf(".") < 0) {
        return ""
      }
      return fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase()
    },
    beforeAttachmentUpload(file) {
      const ext = this.extOf(file.name)
      if (!this.attachmentFileExts.includes(ext)) {
        this.$modal.msgError(this.ipCommon("errAttachFmt"))
        return false
      }
      if (file.name.includes(",")) {
        this.$modal.msgError(this.ipCommon("errComma"))
        return false
      }
      if (file.size / 1024 / 1024 >= 30) {
        this.$modal.msgError(this.ipCommon("errAttachMb"))
        return false
      }
      this.$modal.loading(this.ipCommon("uploadingFile"))
      return true
    },
    handleUploadHttpError() {
      this.$modal.closeLoading()
      this.$modal.msgError(this.ipCommon("errUploadRetry"))
    },
    handleAttachmentUploadSuccess(res, file) {
      this.$modal.closeLoading()
      if (res.code === 200) {
        this.form.attachmentFileUrl = res.url
        this.form.attachmentFilePath = res.fileName
        this.form.attachmentFileName = res.originalFilename || file.name
      } else {
        this.$modal.msgError(res.msg || this.ipCommon("errUploadFail"))
      }
    },
    clearAttachment() {
      this.form.attachmentFileUrl = undefined
      this.form.attachmentFilePath = undefined
      this.form.attachmentFileName = undefined
    },
    beforeCoverUpload(file) {
      const ext = this.extOf(file.name)
      if (!this.coverFileExts.includes(ext)) {
        this.$modal.msgError(this.ipCommon("errCoverFmt"))
        return false
      }
      if (file.name.includes(",")) {
        this.$modal.msgError(this.ipCommon("errComma"))
        return false
      }
      if (file.size / 1024 / 1024 >= 10) {
        this.$modal.msgError(this.ipCommon("errCoverMb"))
        return false
      }
      this.$modal.loading(this.ipCommon("uploadingImg"))
      return true
    },
    handleCoverUploadSuccess(res) {
      this.$modal.closeLoading()
      if (res.code === 200) {
        this.form.coverFileUrl = res.url
        this.form.coverFilePath = res.fileName
      } else {
        this.$modal.msgError(res.msg || this.ipCommon("errUploadFail"))
      }
    },
    handleCoverRemove() {
      this.form.coverFileUrl = undefined
      this.form.coverFilePath = undefined
    },
    submitForm(saveAndPublish) {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateTechProjectGuide(payload).then(() => {
            this.$modal.msgSuccess(this.ipCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          if (saveAndPublish) {
            payload.saveAndPublish = true
          }
          addTechProjectGuide(payload).then(() => {
            this.$modal.msgSuccess(saveAndPublish ? this.ipCommon("msgPubOk") : this.ipCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
.upload-file-uploader {
  margin-bottom: 8px;
}
.upload-file-list {
  list-style: none;
  padding: 0;
  margin: 8px 0 0;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  padding: 0 8px;
}
.ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.hide ::v-deep .el-upload--picture-card {
  display: none;
}
.view-text-block {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
