<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        :placeholder="$t('pages.noticeMessage.filter.system')"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;">
            <sys-origin-icon :icon="item.value" :desc="item.value"
          /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>
      <el-select
        v-model="listQuery.shelfStatus"
        :placeholder="$t('pages.noticeMessage.filter.status')"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in shelfStatusOptions"
          :key="index"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.announcement"
        :placeholder="$t('pages.noticeMessage.filter.announcementStatus')"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in announcementOptions"
          :key="index"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          :range-separator="$t('pages.noticeMessage.dateRange.separator')"
          :start-placeholder="$t('pages.noticeMessage.dateRange.start')"
          :end-placeholder="$t('pages.noticeMessage.dateRange.end')"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        {{ $t('common.search') }}
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('pages.noticeMessage.action.add') }}
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="$t('pages.noticeMessage.loading')"
      fit
      highlight-current-row
    >
      <el-table-column :label="$t('pages.noticeMessage.table.cover')" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" :label="$t('pages.noticeMessage.table.title')" align="center" />
      <el-table-column :label="$t('pages.noticeMessage.table.sourceSystem')" align="center">
        <template slot-scope="scope">
          <sys-origin-icon
            :icon="scope.row.sysOrigin"
            :desc="scope.row.sysOrigin"
          />
        </template>
      </el-table-column>
      <el-table-column prop="type" :label="$t('pages.noticeMessage.table.type')" align="center">
        <template slot-scope="scope">{{ formatType[scope.row.type] }}</template>
      </el-table-column>
      <el-table-column prop="link" :label="$t('pages.noticeMessage.table.link')" align="center" />
      <el-table-column prop="description" :label="$t('pages.noticeMessage.table.description')" align="center" />
      <el-table-column prop="announcement" :label="$t('pages.noticeMessage.table.announcementStatus')" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.announcement"
            @change="handleSwitchAnnouncementChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="announcementTime" :label="$t('pages.noticeMessage.table.announcementTime')" align="center">
        <template slot-scope="scope">
          {{ scope.row.announcementTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="shelfStatus" :label="$t('pages.noticeMessage.table.shelfStatus')" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.shelfStatus"
            @change="handleSwitchShelfStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" :label="$t('pages.noticeMessage.table.createdAt')" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('pages.noticeMessage.table.actions')" align="center" width="200">
        <template slot-scope="scope">
          <el-button type="text" @click.native="handleUpdate(scope.row)"
            >{{ $t('pages.noticeMessage.action.edit') }}</el-button
          >
          <el-button type="text" @click.native="handlDel(scope.row.id)"
            >{{ $t('pages.noticeMessage.action.delete') }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />
    <el-dialog
      :title="textOptTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      width="450px"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-form-item :label="$t('pages.noticeMessage.form.cover')">
            <el-upload
              class="upload-demo"
              action=""
              :http-request="httpRequest"
              :show-file-list="false"
              accept="image/png,image/jpg,image/jpeg"
            >
              <el-image
                v-if="form.cover"
                :src="form.cover"
                fit="fill"
                style="width: 50px; height: 50px"
              />
              <el-button v-loading="uploadLoading" size="small" type="primary"
                >{{ $t('pages.noticeMessage.action.upload') }}</el-button
              >
            </el-upload>
          </el-form-item>
          <el-form-item :label="$t('pages.noticeMessage.form.system')" prop="sysOrigin">
            <el-select
              v-model="form.sysOrigin"
              :placeholder="$t('pages.noticeMessage.placeholder.system')"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="item in permissionsSysOriginPlatforms"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left;">
                  <sys-origin-icon :icon="item.value" :desc="item.value"
                /></span>
                <span style="float: left;margin-left:10px">{{
                  item.label
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.noticeMessage.form.title')" prop="title">
            <el-input v-model.trim="form.title" type="text" />
          </el-form-item>

          <el-form-item :label="$t('pages.noticeMessage.form.type')" prop="type">
            <el-select v-model="form.type" style="width:100%;">
              <el-option :label="$t('pages.noticeMessage.type.notification')" value="notification" />
              <el-option :label="$t('pages.noticeMessage.type.activity')" value="activity" />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('pages.noticeMessage.form.link')">
            <el-input v-model.trim="form.link" type="text" />
          </el-form-item>
          <el-form-item :label="$t('pages.noticeMessage.form.description')" prop="description">
            <el-input
              v-model.trim="form.description"
              type="textarea"
              :rows="8"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">{{ $t('pages.noticeMessage.action.save') }}</el-button>
            <el-button @click="handleClose()">{{ $t('common.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  noticeMessageTable,
  updateNoticeMessage,
  deleteNoticeMessage,
  addNoticeMessage,
  changeAnnouncementStatus,
  changeShelfStatus
} from "@/api/notice-message";
import Pagination from "@/components/Pagination";
import { getAccessImgUrl } from "@/api/oss";
import { productConfigShowcase, announcementArray } from "@/constant/type";
import { pickerOptions } from "@/constant/el-const";
import { mapGetters } from "vuex";
function getFormData() {
  return {
    id: "",
    cover: "",
    sysOrigin: "", //来源系统
    type: "", //公告类型
    title: "",
    link: "", //链接
    description: "" //描述
  };
}
export default {
  components: { Pagination },
  data() {
    return {
      pickerOptions,
      activeGiftId: "",
      pushTextHistoryLoading: false,
      pushTextHistoryVisible: false,
      pushTextHistory: [],
      list: [],
      delarr: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        sysOrigin: "",
        startTime: "",
        endTime: ""
      },
      formVisible: false,
      textOptTitle: "",
      form: getFormData(),
      submitLoading: false,
      rangeDate: "",
      listLoading: true,
      uploadLoading: false
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"]),
    announcementOptions() {
      return announcementArray.map(item => ({
        ...item,
        name: item.value
          ? this.$t("pages.noticeMessage.announcement.published")
          : this.$t("pages.noticeMessage.announcement.unpublished")
      }));
    },
    shelfStatusOptions() {
      return productConfigShowcase.map(item => ({
        ...item,
        name: item.value
          ? this.$t("pages.noticeMessage.shelfStatus.on")
          : this.$t("pages.noticeMessage.shelfStatus.off")
      }));
    },
    formatType() {
      return {
        notification: this.$t("pages.noticeMessage.type.notification"),
        activity: this.$t("pages.noticeMessage.type.activity")
      };
    },
    rules() {
      return {
        sysOrigin: [{ required: true, message: this.$t("pages.noticeMessage.validation.selectSystem"), trigger: "blur" }],
        title: [{ required: true, message: this.$t("pages.noticeMessage.validation.enterTitle"), trigger: "blur" }],
        description: [
          { required: true, message: this.$t("pages.noticeMessage.validation.enterDescription"), trigger: "blur" }
        ]
      };
    }
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0];
          this.listQuery.endTime = newVal[1];
          return;
        }
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    }
  },
  created() {
    const that = this;
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    that.listQuery.sysOrigin = querySystem.value;
    that.renderData();
  },
  methods: {
    renderData() {
      const that = this;
      that.listLoading = true;
      noticeMessageTable(that.listQuery).then(res => {
        const { body } = res;
        that.total = body.total || 0;
        that.list = body.records;
        that.listLoading = false;
      });
    },
    handleSearch() {
      this.renderData();
    },
    handleSwitchAnnouncementChange(row) {
      const that = this;
      if (!row.announcement) {
        this.$message({
          message: this.$t("pages.noticeMessage.message.cannotCancelAnnouncement"),
          type: "error"
        });
        row.announcement = true;
        return;
      }
      that
        .$confirm(this.$t("pages.noticeMessage.confirm.publish"), this.$t("pages.noticeMessage.confirm.title"), {
          confirmButtonText: this.$t("pages.noticeMessage.confirm.confirm"),
          cancelButtonText: this.$t("pages.noticeMessage.confirm.cancel"),
          type: "warning"
        })
        .then(() => {
          that.listLoading = true;
          changeAnnouncementStatus(row.id)
            .then(res => {
              this.listLoading = false;
              this.$message({
                message: this.$t("pages.noticeMessage.message.publishSuccess"),
                type: "success"
              });
              this.renderData();
            })
            .catch(() => {});
        })
        .catch(() => {
          if (!row.announcement) {
            row.announcement = true;
          } else if (row.announcement) {
            row.announcement = false;
          }
        });
    },
    handleSwitchShelfStatusChange(row) {
      changeShelfStatus(row.id, row.shelfStatus)
        .then(res => {
          this.$message({
            message: row.shelfStatus
              ? this.$t("pages.noticeMessage.message.shelfOnSuccess")
              : this.$t("pages.noticeMessage.message.shelfOffSuccess"),
            type: "success"
          });
        })
        .catch(er => {
          if (row.status === 0) {
            row.status = 1;
          } else if (row.status === 1) {
            row.status = 0;
          }
        });
    },
    renderDataSuccess() {
      this.$message({
        message: this.$t("pages.noticeMessage.message.success"),
        type: "success"
      });
      this.renderData();
    },
    queryUserDetails(row) {
      this.userDeatilsDrawer = true;
      this.thatSelectedUserId = row.id;
    },
    submitForm() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true;
          if (that.form.id) {
            updateNoticeMessage(that.form)
              .then(res => {
                that.submitLoading = false;
                that.formVisible = false;
                that.form = getFormData();
                that.renderData();
              })
              .catch(er => {
                that.submitLoading = false;
                that.$emit("fial", er);
              });
            return;
          }
          addNoticeMessage(that.form)
            .then(res => {
              that.submitLoading = false;
              that.formVisible = false;
              that.form = getFormData();
              that.renderData();
            })
            .catch(er => {
              that.submitLoading = false;
              console.error(er);
              that.$emit("fial", er);
            });
        } else {
          console.error("error submit!!");
          return false;
        }
      });
    },
    // 删除
    handlDel(id) {
      this.$confirm(this.$t("pages.noticeMessage.confirm.delete"), this.$t("pages.noticeMessage.confirm.title"), {
        confirmButtonText: this.$t("pages.noticeMessage.confirm.confirm"),
        cancelButtonText: this.$t("pages.noticeMessage.confirm.cancel"),
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          deleteNoticeMessage(id).then(res => {
            this.listLoading = false;
            this.$message({
              message: this.$t("pages.noticeMessage.message.deleteSuccess"),
              type: "success"
            });
            this.renderData();
          });
        })
        .catch(() => {});
    },
    handleClose() {
      this.formVisible = false;
    },

    httpRequest(file) {
      const that = this;
      that.uploadLoading = true;
      this.$simpleUploadFlie(file)
        .then(res => {
          that.uploadLoading = false;
          that.form.cover = getAccessImgUrl(res.name);
        })
        .catch(er => {
          that.uploadLoading = false;
        });
    },
    handleCreate() {
      this.formVisible = true;
      this.textOptTitle = this.$t("pages.noticeMessage.dialog.create");
      this.form = getFormData();
    },
    handleUpdate(row) {
      this.textOptTitle = this.$t("pages.noticeMessage.dialog.edit");
      this.formVisible = true;
      this.form = Object.assign(this.form, row);
    }
  }
};
</script>
