<template>
  <div class="app-container">
    <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="policyLevel">
          <template slot="label">{{ pubT('queryPolicyLevel') }}</template>
          <el-select v-model="queryParams.policyLevel" :placeholder="$t('policy.common.pleaseSelect')" clearable style="width: 160px">
            <el-option
              v-for="item in policyLevelOptions"
              :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:publicity:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ $t('policy.common.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="pubT('colPolicyName')" prop="policyName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="pubT('colPolicyLevel')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ levelLabel(scope.row.policyLevel) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="pubT('colIntro')" prop="introduction" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="pubT('colIssueDate')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.issueDate || $t('policy.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="pubT('colPolicyFile')" align="center" min-width="130" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.policyFileUrl"
              type="primary"
              :href="scope.row.policyFileUrl"
              target="_blank"
            >{{ scope.row.policyFileName }}</el-link>
            <span v-else>{{ $t('policy.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="pubT('colCover')" align="center" width="88">
          <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:publicity:query']"
              type="text"
              size="mini"
              @click="handleView(scope.row)"
            >{{ $t('policy.common.view') }}</el-button>
            <el-button
              v-hasPermi="['industryPolicy:publicity: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:publicity: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:publicity: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:publicity: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="600px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="100px">
        <el-form-item prop="policyName" :rules="formRules.policyName">
          <template slot="label">{{ pubT('formPolicyName') }}</template>
          <el-input v-model="form.policyName" :placeholder="pubT('phPolicyName')" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item prop="policyLevel" :rules="formRules.policyLevel">
          <template slot="label">{{ pubT('formPolicyLevel') }}</template>
          <el-select v-model="form.policyLevel" :placeholder="$t('policy.common.pleaseSelect')" style="width: 100%">
            <el-option
              v-for="item in policyLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </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="issueDate" :rules="formRules.issueDate">
          <template slot="label">{{ pubT('formIssueDate') }}</template>
          <el-date-picker
            v-model="form.issueDate"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('policy.common.pleaseSelect')"
            :picker-options="issueDatePickerOptions"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="policyDesc" :rules="formRules.policyDesc">
          <template slot="label">{{ pubT('formPolicyDesc') }}</template>
          <el-input
            v-model="form.policyDesc"
            type="textarea"
            :rows="2"
            :placeholder="pubT('phPolicyDesc')"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="policyFilePath">
          <template slot="label">{{ pubT('formPolicyFile') }}</template>
          <el-upload
            class="upload-file-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforePolicyFileUpload"
            :on-success="handlePolicyFileUploadSuccess"
            :on-error="handleUploadHttpError"
            :show-file-list="false"
            :disabled="dialogEdit && !canEditUploadRow"
          >
            <el-button size="mini" type="primary" :disabled="dialogEdit && !canEditUploadRow">{{ $t('policy.common.pickFile') }}</el-button>
          </el-upload>
          <div class="el-upload__tip">{{ $t('policy.common.tipPolicyFile') }}</div>
          <ul v-if="form.policyFilePath" 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.policyFileUrl || '#'" :underline="false" target="_blank">
                <span class="el-icon-document"> {{ form.policyFileName }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action">
                <el-link v-if="!(dialogEdit && !canEditUploadRow)" type="danger" :underline="false" @click="clearPolicyFile">{{ $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"
            :disabled="dialogEdit && !canEditUploadRow"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <div class="el-upload__tip">{{ $t('policy.common.tipCover') }}</div>
        </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="580px" append-to-body>
      <el-form label-width="100px" size="small">
        <el-form-item :label="pubT('formPolicyName')">
          <span>{{ viewRow.policyName }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formPolicyLevel')">
          <span>{{ levelLabel(viewRow.policyLevel) }}</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('formIssueDate')">
          <span>{{ viewRow.issueDate || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formPolicyDesc')">
          <span>{{ viewRow.policyDesc || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formPolicyFile')">
          <el-link
            v-if="viewRow.policyFileUrl"
            type="primary"
            :href="viewRow.policyFileUrl"
            target="_blank"
          >{{ viewRow.policyFileName }}</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>
      <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 {
  listPolicyPublicity,
  getPolicyPublicity,
  addPolicyPublicity,
  updatePolicyPublicity,
  delPolicyPublicity,
  publishPolicyPublicity,
  offlinePolicyPublicity
} from "@/api/policy/publicity"

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

export default {
  name: "PolicyPublicity",
  mixins: [policyPublicityLocaleMixin],
  data() {
    return {
      pubNs: "publicity",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      canEditUploadRow: true,
      formKey: 0,
      total: 0,
      tableList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined,
        policyLevel: undefined,
        publishStatus: undefined
      },
      form: {},
      policyFileExts: ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"],
      coverFileExts: ["jpg", "jpeg", "png"]
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.pubT("dialogEdit") : this.pubT("dialogAdd")
    },
    policyLevelOptions() {
      return [1, 2, 3, 4].map((value) => ({ label: this.pubT("level" + value), value }))
    },
    formRules() {
      return {
        policyName: [
          { required: true, message: this.pubT("rulePolicyNameRequired"), trigger: "blur" },
          { min: 1, max: 20, message: this.$t("policy.common.ruleLen120"), trigger: "blur" }
        ],
        policyLevel: [{ required: true, message: this.pubT("rulePolicyLevelRequired"), trigger: "change" }],
        introduction: [{ max: 50, message: this.$t("policy.common.ruleIntroMax50"), trigger: "blur" }],
        issueDate: [
          { required: true, message: this.pubT("ruleIssueDateRequired"), trigger: "change" },
          { validator: this.validateIssueDate, trigger: "change" }
        ],
        policyDesc: [
          { required: true, message: this.pubT("rulePolicyDescRequired"), trigger: "blur" },
          { max: 50, message: this.$t("policy.common.ruleDescMax50"), trigger: "blur" }
        ]
      }
    },
    issueDatePickerOptions() {
      return {
        disabledDate: (time) => time.getTime() > Date.now()
      }
    },
    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: {
    levelLabel(val) {
      const item = this.policyLevelOptions.find((o) => o.value === val)
      return item ? item.label : ""
    },
    validateIssueDate(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      const today = new Date()
      today.setHours(23, 59, 59, 999)
      const picked = new Date(value.replace(/-/g, "/"))
      if (picked.getTime() > today.getTime()) {
        callback(new Error(this.pubT("ruleIssueDateFuture")))
      } else {
        callback()
      }
    },
    canEdit(row) {
      return row.publishStatus === PUBLISH_STATUS.UNPUBLISHED
    },
    canPublish(row) {
      return row.publishStatus === PUBLISH_STATUS.UNPUBLISHED
    },
    canOffline(row) {
      return row.publishStatus === PUBLISH_STATUS.PUBLISHED
    },
    canDelete(row) {
      return row.publishStatus === PUBLISH_STATUS.UNPUBLISHED
    },
    getList() {
      this.loading = true
      listPolicyPublicity(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.policyLevel = undefined
      this.queryParams.publishStatus = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        policyName: undefined,
        policyLevel: undefined,
        introduction: undefined,
        issueDate: undefined,
        policyDesc: undefined,
        policyFileUrl: undefined,
        policyFilePath: undefined,
        policyFileName: undefined,
        coverFileUrl: undefined,
        coverFilePath: undefined
      }
    },
    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)) {
        return
      }
      getPolicyPublicity(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.canEditUploadRow = data.publishStatus === PUBLISH_STATUS.UNPUBLISHED
        this.form = {
          id: data.id,
          policyName: data.policyName,
          policyLevel: data.policyLevel,
          introduction: data.introduction,
          issueDate: data.issueDate,
          policyDesc: data.policyDesc,
          policyFileUrl: data.policyFileUrl,
          policyFilePath: data.policyFilePath,
          policyFileName: data.policyFileName,
          coverFileUrl: data.coverFileUrl,
          coverFilePath: data.coverFilePath
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getPolicyPublicity(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("policy.publicity.confirmDelete", { id: row.id }))
        .then(() => delPolicyPublicity(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handlePublish(row) {
      this.$modal
        .confirm(this.pubT("confirmPublish"))
        .then(() => publishPolicyPublicity(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgPubOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleOffline(row) {
      this.$modal
        .confirm(this.pubT("confirmOffline"))
        .then(() => offlinePolicyPublicity(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgOffOk"))
          this.getList()
        })
        .catch(() => {})
    },
    extOf(fileName) {
      if (!fileName || fileName.lastIndexOf(".") < 0) {
        return ""
      }
      return fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase()
    },
    beforePolicyFileUpload(file) {
      const ext = this.extOf(file.name)
      if (!this.policyFileExts.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"))
    },
    handlePolicyFileUploadSuccess(res, file) {
      this.$modal.closeLoading()
      if (res.code === 200) {
        this.form.policyFileUrl = res.url
        this.form.policyFilePath = res.fileName
        this.form.policyFileName = res.originalFilename || file.name
      } else {
        this.$modal.msgError(res.msg || this.$t("policy.common.errUploadFail"))
      }
    },
    clearPolicyFile() {
      this.form.policyFileUrl = undefined
      this.form.policyFilePath = undefined
      this.form.policyFileName = undefined
    },
    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
        }
        const payload = {
          policyName: this.form.policyName,
          policyLevel: this.form.policyLevel,
          introduction: this.form.introduction || undefined,
          issueDate: this.form.issueDate,
          policyDesc: this.form.policyDesc,
          policyFileUrl: this.form.policyFileUrl,
          policyFilePath: this.form.policyFilePath,
          policyFileName: this.form.policyFileName,
          coverFileUrl: this.form.coverFileUrl,
          coverFilePath: this.form.coverFilePath
        }
        if (this.dialogEdit) {
          payload.id = this.form.id
          updatePolicyPublicity(payload).then(() => {
            this.$modal.msgSuccess(this.$t("policy.common.msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addPolicyPublicity(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>
