<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item :label="$t('指标类型')">
        <dict-selector v-model="queryParams.type" clearable :type="DICT_TYPE.SCORE_RULE_TYPE" @change="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('标题：')">
        <el-input v-model="queryParams.title" v-trim :placeholder="$t('请输入查找')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('规则说明')">
        <el-input v-model="queryParams.desc" :placeholder="$t('请输入关键词查找')" clearable v-trim @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('状态')">
        <dict-selector v-model="queryParams.status" clearable :type="DICT_TYPE.GIFT_STATUS" />
      </el-form-item>
      <el-form-item :label="$t('单次积分')">
        <el-row :gutter="10" style="width: 300px">
          <el-col :span="10">
            <dict-selector v-model="queryParams.getScoreOnceSymbol" clearable :type="DICT_TYPE.QUANTITATIVE_RELATION_SYMBOL" @change="handleQuery" />
          </el-col>
          <el-col :span="14">
            <el-input v-model.trim="queryParams.getScoreOnce" :placeholder="$t('请输入数字')" clearable onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" @keyup.enter.native="handleQuery" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item :label="$t('最高积分')">
        <el-row :gutter="10" style="width: 300px">
          <el-col :span="10">
            <dict-selector v-model="queryParams.maxScoreTotalSymbol" clearable :type="DICT_TYPE.QUANTITATIVE_RELATION_SYMBOL" @change="handleQuery" />
          </el-col>
          <el-col :span="14">
            <el-input v-model.trim="queryParams.maxScoreTotal" :placeholder="$t('请输入数字')" clearable onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" @keyup.enter.native="handleQuery" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item :label="$t('创建时间')">
        <el-date-picker v-model="dateRangeCreateTime" type="datetimerange" clearable placement="bottom-start" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>
    <el-row class="mb8">
      <el-button type="success" size="mini" icon="el-icon-plus" @click="handleNewScoreRule">{{ $t("添加规则") }}</el-button>

      <right-toolbar :show-search.sync="showSearch" @queryTable="handleQueryPagination" />
      <el-tooltip v-hasPermi="['ecw:memberManagement:enableMemberPointsSystem']" :content="`${$t('开启会员积分系统')} : ${switchState} `" placement="top" class="switchBtn">
        <el-switch v-model="switchState" :active-value="true" :inactive-text="$t('开启会员积分系统')" :inactive-value="false" @change="openSwitch($event)" />
      </el-tooltip>
    </el-row>
    <el-table ref="multipleTable" v-loading="loading" :data="integrationRuleList">
      <el-table-column width="90" :label="$t('编号')" align="center">
        <template #default="{ row }">
          <el-button size="mini" type="text" @click="handleViewDetails(row)"> {{ row.code || "/" }}</el-button>
        </template>
      </el-table-column>
      <el-table-column width="100" :label="$t('指标类型')" align="center">
        <template slot-scope="scope">
          {{ isChinese ? handleSourceType(scope.row.type).label : handleSourceType(scope.row.type).labelEn }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('标题')" width="200" align="center" :prop="isChinese ? 'titleZh' : 'titleEn'" />

      <el-table-column :label="$t('开始时间')" width="150px" align="center">
        <template #default="{ row }"> {{ parseTime(row.startTime) || "/" }}</template>
      </el-table-column>
      <el-table-column :label="$t('结束时间')" width="150px" align="center">
        <template #default="{ row }"> {{ parseTime(row.endTime) || "/" }}</template>
      </el-table-column>

      <el-table-column :label="$t('单次积分')" align="center">
        <template #default="{ row }"> {{ row.getScoreOnce || "--" }}</template>
      </el-table-column>
      <el-table-column :label="$t('累计最高积分')" width="140px" align="center" prop="maxScoreTotal">
        <template #default="{ row }"> {{ row.maxScoreTotal || "--" }}</template>
      </el-table-column>
      <el-table-column :label="$t('规则说明')" width="260px" align="center" :prop="isChinese ? 'descZh' : 'descEn'" />

      <el-table-column :label="$t('展示平台')" align="center">
        <template #default="{ row }"> {{ handlePlatform(row.showPlatform) || "/" }}</template>
      </el-table-column>
      <el-table-column :label="$t('状态')" align="center">
        <template #default="{ row }"> {{ $l(handleStatus(row.status), "label") || "/" }}</template>
      </el-table-column>

      <el-table-column :label="$t('创建人')" width="120px" align="center" prop="creator" />
      <el-table-column :label="$t('创建时间')" width="150px" align="center">
        <template #default="{ row }"> {{ parseTime(row.createTime) || "/" }}</template>
      </el-table-column>

      <el-table-column :label="$t('最后更新人')" width="140px" align="center" prop="updater" />
      <el-table-column :label="$t('最后更新时间')" width="150px" align="center">
        <template #default="{ row }"> {{ parseTime(row.updateTime) || "/" }}</template>
      </el-table-column>
      <el-table-column width="140px" :label="$t('操作')" align="center" fixed="right">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleViewDetails(scope.row)"
            >{{ $t("查看") }}</el-button
          > -->
          <el-button size="mini" type="text" :disabled="scope.row.status != '1'" @click="handleCloseButton(scope.row)">{{ $t("关闭") }}</el-button>
          <el-button size="mini" type="text" @click="handleCopyButton(scope.row)">{{ $t("复制") }}</el-button>
          <el-button size="mini" type="text" :disabled="scope.row.status != '1'" @click="handleDelayButton(scope.row)">{{ $t("延期") }}</el-button>
          <el-button size="mini" :disabled="scope.row.status != '2'" type="text" @click="handleDelete(scope.row)">{{ $t("删除") }}</el-button>
          <el-button size="mini" type="text" :disabled="scope.row.status != '2'" @click="handleUpdate(scope.row)">{{ $t("编辑") }}</el-button>
          <el-button size="mini" type="text" :disabled="scope.row.status != '2'" @click="handleEnabledStatus(scope.row)">{{ $t("启用") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- //分页列表 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="handleQueryPagination" />
    <el-dialog :title="$t('提示')" :visible.sync="dialogPostponeVisible" width="30%">
      <el-row class="mb8">{{ $t("请选择延期时间") }}</el-row>
      <el-date-picker v-model="postponeDatetime" type="datetime" clearable style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" :placeholder="$t('请选择时间')" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogPostponeVisible = false">{{ $t("取 消") }}</el-button>
        <el-button type="primary" @click="confirmPostponeIntegral">{{ $t("确 定") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getDictDatas, DICT_TYPE } from "@/utils/dict"
import { getScoreRecordList, integralRuleStatus, integralRuleCopy, integralRuleDelay, integralRuleDelete, switchRuleSet, switchRuleGet } from "@/api/ecw/memberManagement"
export default {
  name: "EcwMembermanagementIntegrationrule",
  data() {
    return {
      switchState: true,
      dateRangeCreateTime: [],
      total: 0,
      showSearch: true,
      loading: true,
      dialogPostponeVisible: false,
      integrationRuleList: [],
      postponeIntegralID: "",
      postponeDatetime: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      queryParams: {
        type: "",
        title: "",
        desc: "",
        status: "1",
        getScoreOnceSymbol: "",
        getScoreOnce: "",
        maxScoreTotalSymbol: "",
        maxScoreTotal: "",
        page: 1,
        rows: 10
      }
    }
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN"
    }
  },
  created() {
    this.handleQuery()
    this.getSwitchRuleStatus()
  },
  activated() {
    this.handleQuery()
  },
  methods: {
    openSwitch(status) {
      this.$modal
        .confirm(
          this.$t("是否确认{val}会员积分系统", {
            val: status ? this.$t("开启") : this.$t("关闭")
          })
        )
        .then(async () => {
          // return integralRuleDelete({ id: row.id })
          const { code } = await switchRuleSet({ switchState: status })
          if (code === 0) {
            this.$modal.msgSuccess(this.$t("成功"))
          }
        })
        .catch(() => {
          this.switchState = !status
        })
    },
    getSwitchRuleStatus() {
      switchRuleGet().then((res) => {
        this.switchState = res.data
      })
    },
    // 编辑操作按钮
    handleUpdate(row) {
      this.$router.push({
        path: "/member/memberManagement/addIntegrationRuleOperation",
        query: { id: row.id, pageStatus: "edit" }
      })
    },
    // 查看按钮操作
    handleViewDetails(row) {
      this.$router.push({
        path: "/member/memberManagement/addIntegrationRuleOperation",
        query: { id: row.id, pageStatus: "view" }
      })
    },
    // 延期按钮操作
    handleDelayButton(row) {
      this.postponeIntegralID = row.id
      this.dialogPostponeVisible = true
    },
    confirmPostponeIntegral() {
      integralRuleDelay({
        id: this.postponeIntegralID,
        endTime: this.postponeDatetime
      }).then((res) => {
        this.postponeDatetime = ""
        this.$modal.msgSuccess(this.$t("延期成功"))
      })
    },
    // 删除按钮操作
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("是否确认删除此积分规则"))
        .then(function () {
          return integralRuleDelete({ id: row.id })
        })
        .then(() => {
          this.handleQuery()
          this.$modal.msgSuccess(this.$t("删除成功"))
        })
        .catch(() => {})
    },
    // 启用按钮操作
    handleEnabledStatus(row) {
      this.$modal
        .confirm(this.$t("是否确认启用此积分规则"))
        .then(function () {
          return integralRuleStatus({ id: row.id, status: "1" })
        })
        .then(() => {
          this.handleQuery()
          this.$modal.msgSuccess(this.$t("启用成功"))
        })
        .catch(() => {})
    },
    // 复制按钮操作
    handleCopyButton(row) {
      this.$modal
        .confirm(this.$t("是否确认复制积分规则"))
        .then(function () {
          return integralRuleCopy({ id: row.id })
        })
        .then(() => {
          this.handleQuery()
          this.$modal.msgSuccess(this.$t("复制成功"))
        })
        .catch(() => {})
    },

    // 关闭按钮操作
    handleCloseButton(row) {
      this.$modal
        .confirm(this.$t("是否确认关闭此积分规则"))
        .then(function () {
          return integralRuleStatus({ id: row.id, status: "3" })
        })
        .then(() => {
          this.handleQuery()
          this.$modal.msgSuccess(this.$t("关闭成功"))
        })
        .catch(() => {})
    },
    // new score rule func
    handleNewScoreRule() {
      this.$router.push({
        path: "/member/memberManagement/addIntegrationRuleOperation",
        query: { pageStatus: "new" }
      })
    },
    // 积分来源
    handleSourceType(id) {
      return this.getDictDatas(DICT_TYPE.SCORE_RULE_TYPE).filter((item) => item.value == id)[0]
    },
    //	活动状态
    handleStatus(id) {
      return this.getDictDatas(DICT_TYPE.GIFT_STATUS).filter((item) => item.value == id)[0]
    },
    arraysEqual(arr1, arr2) {
      return arr1.filter((current) => {
        return !!arr2.find((item) => item == current.value.toString())
      })
    },
    // 展示平台
    handlePlatform(platformId) {
      const platformIdLabel = []
      if (this.isChinese) {
        this.arraysEqual(this.getDictDatas(DICT_TYPE.PLATFORM_TYPE), platformId.split(",")).forEach((element) => {
          platformIdLabel.push(element.label)
        })
      } else {
        this.arraysEqual(this.getDictDatas(DICT_TYPE.PLATFORM_TYPE), platformId.split(",")).forEach((element) => {
          platformIdLabel.push(element.labelEn)
        })
      }
      return platformIdLabel.join()
    },
    handleQuery() {
      this.queryParams.page = 1
      const params = { ...this.queryParams }
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime", false)
      getScoreRecordList(params).then((res) => {
        this.loading = false
        this.integrationRuleList = res.data.list
        this.total = res.data.total
      })
    },
    handleQueryPagination() {
      const params = { ...this.queryParams }
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime", false)
      getScoreRecordList(params).then((res) => {
        this.loading = false
        this.integrationRuleList = res.data.list
        this.total = res.data.total
      })
    },
    resetQuery() {
      this.loading = true
      this.dateRangeCreateTime = []
      this.queryParams = {
        ruleTitle: "",
        ruleDesc: "",
        key: "",
        sourceType: "",
        scoreCount: "",
        status: "",
        scoreCountOperate: "",
        endTime: "",
        pageNo: 1,
        pageSize: 10,
        startTime: ""
      }
      this.handleQuery()
    }
  }
}
</script>
<style scoped>
.switchBtn {
  float: right;
  padding-right: 70px;
  padding-top: 6px;
}
</style>
