<template>
  <div>
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="keyword">
          <template slot="label">{{ pubT('queryKeyword') }}</template>
          <el-input
            v-model="queryParams.keyword"
            :placeholder="pubT('queryKeywordPh')"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="grantStatus">
          <template slot="label">{{ pubT('queryGrantStatus') }}</template>
          <el-select v-model="queryParams.grantStatus" :placeholder="$t('policy.common.pleaseSelect')" clearable style="width: 140px">
            <el-option v-for="item in grantStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="publishStatus">
          <template slot="label">{{ pubT('queryPublishStatus') }}</template>
          <el-select v-model="queryParams.publishStatus" :placeholder="$t('policy.common.pleaseSelect')" clearable style="width: 140px">
            <el-option :label="$t('policy.status.unpublished')" :value="0" />
            <el-option :label="$t('policy.status.published')" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('policy.common.search') }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('policy.common.reset') }}</el-button>
          <el-button
            v-hasPermi="['industryPolicy:subsidyMatter:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ $t('policy.common.add') }}</el-button>
          <el-button
            v-hasPermi="['industryPolicy:subsidyMatter:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!ids.length"
            @click="handleDeleteBatch"
          >{{ $t('policy.common.delete') }}</el-button>
          <!-- 导出功能暂未开放
          <el-button
            v-hasPermi="['industryPolicy:subsidyMatter:export']"
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >{{ $t('policy.common.export') }}</el-button>
          -->
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column :label="pubT('colSubsidyName')" prop="subsidyName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="pubT('colIntro')" prop="introduction" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="pubT('colGrantStatus')" align="center" width="92">
          <template slot-scope="scope">
            <span>{{ grantStatusLabel(scope.row.grantStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="pubT('colDetailFile')" align="center" min-width="130" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-link v-if="scope.row.detailFileUrl" type="primary" :href="scope.row.detailFileUrl" target="_blank">{{ scope.row.detailFileName }}</el-link>
            <span v-else>{{ $t('policy.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="pubT('colCover')" align="center" width="80">
          <template slot-scope="scope">
            <image-preview v-if="scope.row.coverFileUrl" :src="scope.row.coverFileUrl" :width="48" :height="48" />
            <span v-else>{{ $t('policy.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('policy.common.colShelf')" align="center" width="92">
          <template slot-scope="scope">
            <span>{{ publishStatusText(scope.row.publishStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('policy.common.colPub')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.publishTime ? parseTime(scope.row.publishTime, '{y}-{m}-{d}') : $t('policy.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('policy.common.colCreate')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime) : $t('policy.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('policy.common.colOp')" align="center" class-name="small-padding fixed-width" width="280">
          <template slot-scope="scope">
            <el-button v-hasPermi="['industryPolicy:subsidyMatter:query']" type="text" size="mini" @click="handleView(scope.row)">{{ $t('policy.common.view') }}</el-button>
            <el-button v-hasPermi="['industryPolicy:subsidyMatter:edit']" v-if="canEdit(scope.row)" type="text" size="mini" @click="handleEdit(scope.row)">{{ $t('policy.common.edit') }}</el-button>
            <el-button v-hasPermi="['industryPolicy:subsidyMatter:remove']" v-if="canDelete(scope.row)" type="text" size="mini" @click="handleDelete(scope.row)">{{ $t('policy.common.delete') }}</el-button>
            <el-button v-hasPermi="['industryPolicy:subsidyMatter:publish']" v-if="canPublish(scope.row)" type="text" size="mini" @click="handlePublish(scope.row)">{{ $t('policy.common.publish') }}</el-button>
            <el-button v-hasPermi="['industryPolicy:subsidyMatter:offline']" v-if="canOffline(scope.row)" type="text" size="mini" @click="handleOffline(scope.row)">{{ $t('policy.common.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="620px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="120px">
        <el-form-item prop="subsidyName" :rules="formRules.subsidyName">
          <template slot="label">{{ pubT('formSubsidyName') }}</template>
          <el-input v-model="form.subsidyName" :placeholder="pubT('phSubsidyName')" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item prop="introduction" :rules="formRules.introduction">
          <template slot="label">{{ pubT('formIntro') }}</template>
          <el-input v-model="form.introduction" type="textarea" :rows="2" :placeholder="pubT('phIntro')" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="grantStatus" :rules="formRules.grantStatus">
          <template slot="label">{{ pubT('formGrantStatus') }}</template>
          <el-select v-model="form.grantStatus" :placeholder="$t('policy.common.pleaseSelect')" style="width: 100%">
            <el-option v-for="item in grantStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="detailFilePath" :rules="formRules.detailFilePath">
          <template slot="label">{{ pubT('formDetailFile') }}</template>
          <el-upload
            class="upload-file-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforeDetailFileUpload"
            :on-success="handleDetailFileUploadSuccess"
            :on-error="handleUploadHttpError"
            :show-file-list="false"
          >
            <el-button size="mini" type="primary">{{ $t('policy.common.pickFile') }}</el-button>
          </el-upload>
          <div class="el-upload__tip">{{ pubT('tipDetailFile') }}</div>
          <ul v-if="form.detailFilePath" 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.detailFileUrl || '#'" :underline="false" target="_blank">
                <span class="el-icon-document"> {{ form.detailFileName }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action">
                <el-link type="danger" :underline="false" @click="clearDetailFile">{{ $t('policy.common.del') }}</el-link>
              </div>
            </li>
          </ul>
        </el-form-item>
        <el-form-item prop="coverFilePath">
          <template slot="label">{{ pubT('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"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <div class="el-upload__tip">{{ $t('policy.common.tipCover') }}</div>
        </el-form-item>
        <el-form-item prop="remark">
          <template slot="label">{{ pubT('formRemark') }}</template>
          <el-input v-model="form.remark" type="textarea" :rows="2" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('policy.common.ok') }}</el-button>
        <el-button @click="cancel">{{ $t('policy.common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('policy.common.viewTitle')" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-form label-width="120px" size="small">
        <el-form-item :label="pubT('formSubsidyName')"><span>{{ viewRow.subsidyName }}</span></el-form-item>
        <el-form-item :label="pubT('formIntro')"><span>{{ viewRow.introduction || $t('policy.status.dash') }}</span></el-form-item>
        <el-form-item :label="pubT('formGrantStatus')"><span>{{ grantStatusLabel(viewRow.grantStatus) }}</span></el-form-item>
        <el-form-item :label="pubT('formDetailFile')">
          <el-link v-if="viewRow.detailFileUrl" type="primary" :href="viewRow.detailFileUrl" target="_blank">{{ viewRow.detailFileName }}</el-link>
          <span v-else>{{ $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formCover')">
          <image-preview v-if="viewRow.coverFileUrl" :src="viewRow.coverFileUrl" :width="200" :height="120" />
          <span v-else>{{ $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="$t('policy.common.colShelf')"><span>{{ publishStatusText(viewRow.publishStatus) }}</span></el-form-item>
        <el-form-item :label="$t('policy.common.viewPubTime')"><span>{{ viewRow.publishTime ? parseTime(viewRow.publishTime) : $t('policy.status.dash') }}</span></el-form-item>
        <el-form-item :label="$t('policy.common.viewOfflineTime')"><span>{{ viewRow.offlineTime ? parseTime(viewRow.offlineTime) : $t('policy.status.dash') }}</span></el-form-item>
        <el-form-item :label="pubT('formRemark')"><span>{{ viewRow.remark || $t('policy.status.dash') }}</span></el-form-item>
        <el-form-item :label="pubT('viewCreateBy')"><span>{{ viewRow.createBy || $t('policy.status.dash') }}</span></el-form-item>
        <el-form-item :label="$t('policy.common.colCreate')"><span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : $t('policy.status.dash') }}</span></el-form-item>
        <el-form-item :label="pubT('viewUpdateBy')"><span>{{ viewRow.updateBy || $t('policy.status.dash') }}</span></el-form-item>
        <el-form-item :label="pubT('viewUpdateTime')"><span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : $t('policy.status.dash') }}</span></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">{{ $t('policy.common.close') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import policyPublicityLocaleMixin from "@/mixins/policyPublicityLocaleMixin"
import {
  listSubsidyMatter,
  getSubsidyMatter,
  addSubsidyMatter,
  updateSubsidyMatter,
  delSubsidyMatter,
  publishSubsidyMatter,
  offlineSubsidyMatter
} from "@/api/policy/subsidyMatter"

const PUBLISH_STATUS = { UNPUBLISHED: 0, PUBLISHED: 1 }

export default {
  name: "ProjectSubsidyMatterTab",
  mixins: [policyPublicityLocaleMixin],
  data() {
    return {
      pubNs: "subsidyMatter",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      ids: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined,
        grantStatus: undefined,
        publishStatus: undefined
      },
      form: {},
      detailFileExts: ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"],
      coverFileExts: ["jpg", "jpeg", "png"]
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.pubT("dialogEdit") : this.pubT("dialogAdd")
    },
    grantStatusOptions() {
      return [1, 2].map((value) => ({ label: this.pubT("grantStatus" + value), value }))
    },
    formRules() {
      return {
        subsidyName: [
          { required: true, message: this.pubT("ruleSubsidyNameRequired"), trigger: "blur" },
          { min: 1, max: 20, message: this.$t("policy.common.ruleLen120"), trigger: "blur" }
        ],
        introduction: [{ max: 50, message: this.$t("policy.common.ruleIntroMax50"), trigger: "blur" }],
        grantStatus: [{ required: true, message: this.pubT("ruleGrantStatusRequired"), trigger: "change" }],
        detailFilePath: [{ validator: this.validateDetailFile, trigger: "change" }]
      }
    },
    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.getList()
  },
  methods: {
    grantStatusLabel(val) {
      const item = this.grantStatusOptions.find((o) => o.value === val)
      return item ? item.label : ""
    },
    validateDetailFile(rule, value, callback) {
      if (!this.form.detailFilePath) {
        callback(new Error(this.pubT("ruleDetailFileRequired")))
      } else {
        callback()
      }
    },
    getList() {
      this.loading = true
      listSubsidyMatter(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.keyword = undefined
      this.queryParams.grantStatus = undefined
      this.queryParams.publishStatus = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    canEdit(row) {
      return row.publishStatus !== PUBLISH_STATUS.PUBLISHED
    },
    canDelete(row) {
      return row.publishStatus !== PUBLISH_STATUS.PUBLISHED
    },
    canPublish(row) {
      return row.publishStatus !== PUBLISH_STATUS.PUBLISHED
    },
    canOffline(row) {
      return row.publishStatus === PUBLISH_STATUS.PUBLISHED
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        subsidyName: undefined,
        introduction: undefined,
        grantStatus: 1,
        detailFileUrl: undefined,
        detailFilePath: undefined,
        detailFileName: undefined,
        coverFileUrl: undefined,
        coverFilePath: undefined,
        remark: undefined
      }
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => this.resetForm("form"))
    },
    handleEdit(row) {
      if (!this.canEdit(row)) {
        return
      }
      getSubsidyMatter(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.form = {
          id: data.id,
          subsidyName: data.subsidyName,
          introduction: data.introduction,
          grantStatus: data.grantStatus != null ? data.grantStatus : 1,
          detailFileUrl: data.detailFileUrl,
          detailFilePath: data.detailFilePath,
          detailFileName: data.detailFileName,
          coverFileUrl: data.coverFileUrl,
          coverFilePath: data.coverFilePath,
          remark: data.remark
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getSubsidyMatter(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("policy.subsidyMatter.confirmDelete", { id: row.id }))
        .then(() => delSubsidyMatter(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handlePublish(row) {
      this.$modal
        .confirm(this.pubT("confirmPublish"))
        .then(() => publishSubsidyMatter(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgPubOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleOffline(row) {
      this.$modal
        .confirm(this.pubT("confirmOffline"))
        .then(() => offlineSubsidyMatter(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgOffOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleDeleteBatch() {
      if (!this.ids.length) {
        return
      }
      const hasPublished = this.tableList.some((r) => this.ids.includes(r.id) && !this.canDelete(r))
      if (hasPublished) {
        this.$modal.msgError(this.pubT("ruleCannotDeletePublished"))
        return
      }
      this.$modal
        .confirm(this.pubT("confirmDeleteBatch"))
        .then(() => delSubsidyMatter(this.ids.join(",")))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleExport() {
      this.download(
        "industryPolicy/subsidyMatter/export",
        { ...this.queryParams },
        `subsidy_matter_${new Date().getTime()}.xlsx`
      )
    },
    extOf(fileName) {
      if (!fileName || fileName.lastIndexOf(".") < 0) {
        return ""
      }
      return fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase()
    },
    beforeDetailFileUpload(file) {
      const ext = this.extOf(file.name)
      if (!this.detailFileExts.includes(ext)) {
        this.$modal.msgError(this.$t("policy.common.errPolicyFmt"))
        return false
      }
      if (file.name.includes(",")) {
        this.$modal.msgError(this.$t("policy.common.errComma"))
        return false
      }
      if (file.size / 1024 / 1024 >= 30) {
        this.$modal.msgError(this.$t("policy.common.errPolicyMb"))
        return false
      }
      this.$modal.loading(this.$t("policy.common.uploadingFile"))
      return true
    },
    handleUploadHttpError() {
      this.$modal.closeLoading()
      this.$modal.msgError(this.$t("policy.common.errUploadRetry"))
    },
    handleDetailFileUploadSuccess(res, file) {
      this.$modal.closeLoading()
      if (res.code === 200) {
        this.form.detailFileUrl = res.url
        this.form.detailFilePath = res.fileName
        this.form.detailFileName = res.originalFilename || file.name
        this.$refs.form && this.$refs.form.validateField("detailFilePath")
      } else {
        this.$modal.msgError(res.msg || this.$t("policy.common.errUploadFail"))
      }
    },
    clearDetailFile() {
      this.form.detailFileUrl = undefined
      this.form.detailFilePath = undefined
      this.form.detailFileName = undefined
      this.$refs.form && this.$refs.form.validateField("detailFilePath")
    },
    beforeCoverUpload(file) {
      const ext = this.extOf(file.name)
      if (!this.coverFileExts.includes(ext)) {
        this.$modal.msgError(this.$t("policy.common.errCoverFmt"))
        return false
      }
      if (file.name.includes(",")) {
        this.$modal.msgError(this.$t("policy.common.errComma"))
        return false
      }
      if (file.size / 1024 / 1024 >= 10) {
        this.$modal.msgError(this.$t("policy.common.errCoverMb"))
        return false
      }
      this.$modal.loading(this.$t("policy.common.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.$t("policy.common.errUploadFail"))
      }
    },
    handleCoverRemove() {
      this.form.coverFileUrl = undefined
      this.form.coverFilePath = undefined
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        if (!this.form.detailFilePath) {
          this.$modal.msgError(this.pubT("ruleDetailFileRequired"))
          return
        }
        const payload = {
          subsidyName: this.form.subsidyName,
          introduction: this.form.introduction || undefined,
          grantStatus: this.form.grantStatus,
          detailFileUrl: this.form.detailFileUrl,
          detailFilePath: this.form.detailFilePath,
          detailFileName: this.form.detailFileName,
          coverFileUrl: this.form.coverFileUrl,
          coverFilePath: this.form.coverFilePath,
          remark: this.form.remark || undefined
        }
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateSubsidyMatter(payload).then(() => {
            this.$modal.msgSuccess(this.$t("policy.common.msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addSubsidyMatter(payload).then(() => {
            this.$modal.msgSuccess(this.$t("policy.common.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;
}
</style>
