<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('礼品名称')">
        <el-input
          v-model.trim="queryParams.title"
          :placeholder="$t('请输入礼品名称')"
          clearable
          onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('兑换积分')">
        <el-row :gutter="10">
          <el-col :span="8">
            <dict-selector
              v-model="queryParams.pointsRequireSymbol"
              clearable
              :type="DICT_TYPE.QUANTITATIVE_RELATION_SYMBOL"
              @change="handleQuery"
            />
          </el-col>
          <el-col :span="16">
            <el-input
              v-model.trim="queryParams.pointsRequire"
              :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('领取方式')" prop="level">
        <dict-selector
          v-model="queryParams.pickMethod"
          clearable
          :type="DICT_TYPE.WAY_OF_RECEIVING"
          @change="handleQuery"
        />
      </el-form-item>

      <el-form-item :label="$t('兑换网点')" prop="level">
        <el-select
          v-model="queryParams.nodeId"
          :placeholder="$t('请选择兑换网点')"
          clearable
          size="small"
          @change="handleQuery"
        >
          <el-option
            v-for="nodeItem in nodeList"
            :key="nodeItem.id"
            :label="isChinese ? nodeItem.titleZh : nodeItem.titleEn"
            :value="nodeItem.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('状态')" prop="level">
        <dict-selector
          v-model="queryParams.status"
          clearable
          :type="DICT_TYPE.GIFT_STATUS"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('备注')" prop="level">
        <el-input
          v-model.trim="queryParams.remark"
          :placeholder="$t('请输入备注')"
          clearable
          onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('剩余数量')">
        <el-row :gutter="10">
          <el-col :span="8">
            <dict-selector
              v-model="queryParams.quantityRemainSymbol"
              clearable
              :type="DICT_TYPE.QUANTITATIVE_RELATION_SYMBOL"
              @change="handleQuery"
            />
          </el-col>
          <el-col :span="16">
            <el-input
              v-model.trim="queryParams.quantityRemain"
              :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
        v-hasPermi="['ecw:giftManagement:add']"
        type="success"
        size="mini"
        icon="el-icon-plus"
        @click="handleAddReward"
        >{{ $t("添加礼品") }}</el-button
      >
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>
    <!-- 礼品列表 -->
    <el-table ref="multipleTable" v-loading="loading" :data="list">
      <el-table-column
        width="140"
        :label="$t('礼品ID')"
        align="center"
        prop="code"
      />
      <el-table-column :label="$t('礼品名称')" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">{{
            isChinese ? scope.row.titleZh : scope.row.titleEn
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('图片')">
        <template slot-scope="scope">
          <el-image
            :src="firstImg(isChinese ? scope.row.imgZh : scope.row.imgEn)"
            style="width: 50px; height: 50px"
            >{{ $t("无") }}</el-image
          >
        </template>
      </el-table-column>
      <el-table-column width="100" :label="$t('开始日期')">
        <template #default="{ row }">
          {{ parseTime(row.startTime, "{y}-{m}-{d}") || "/" }}
        </template>
      </el-table-column>
      <el-table-column width="100" :label="$t('结束日期')">
        <template #default="{ row }">
          {{ parseTime(row.endTime, "{y}-{m}-{d}") || "/" }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('兑换积分')" prop="pointsRequire" />
      <el-table-column :label="$t('领取方式')" align="center" prop="pickMethod">
        <template #default="{ row }">
          {{ handlePickMethod(row.pickMethod) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('兑换网点')" align="center">
        <template #default="{ row }">
          {{
            isChinese
              ? handleExchangeNodeId(row.nodeId).titleZh
              : handleExchangeNodeId(row.nodeId).titleEn
          }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('允许兑换次数')"
        align="center"
        prop="allowCount"
      />
      <el-table-column :label="$t('状态')">
        <template slot-scope="{ row }">
          {{
            isChinese
              ? handleRewardsStatus(row.status).label
              : handleRewardsStatus(row.status).labelEn
          }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('备注')" align="center" width="200">
        <template slot-scope="{ row }">
          <el-tooltip
            popper-class="rewardstToolTip"
            :content="isChinese ? row.remarkZh : remarkEn"
            placement="top"
          >
            <div
              style="
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              "
            >
              {{ isChinese ? row.remarkZh : remarkEn }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column :label="$t('已兑换次数')" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="$router.push('/memberManagement/exchangeRecord')"
            >{{ scope.row.exchangeCount }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('剩余数量')"
        align="center"
        prop="quantityRemain"
      />
      <el-table-column
        width="220px"
        align="center"
        :label="$t('操作')"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['ecw:giftManagement:check']"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >{{ $t("查看") }}</el-button
          >
          <el-button
            v-hasPermi="['ecw:giftManagement:close']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.status == '2' || scope.row.status == '3'"
            @click="handleCloseStatus(scope.row)"
            >{{ $t("关闭") }}</el-button
          >
          <el-button
            v-hasPermi="['ecw:giftManagement:copy']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="copyRewards(scope.row)"
            >{{ $t("复制") }}</el-button
          >
          <el-button
            v-hasPermi="['ecw:giftManagement:postpone']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.status != '1'"
            @click="handlePostpone(scope.row)"
            >{{ $t("延期") }}</el-button
          >
          <el-button
            v-hasPermi="['ecw:giftManagement:delete']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="scope.row.status != '2'"
            @click="handleDelete(scope.row)"
            >{{ $t("删除") }}</el-button
          >
          <el-button
            v-has-permi="['ecw:giftManagement:edit']"
            size="mini"
            type="text"
            :disabled="scope.row.status != '2' && scope.row.status != '1'"
            icon="el-icon-collection"
            @click="editRewards(scope.row)"
            >{{ $t("编辑") }}</el-button
          >
          <el-button
            v-has-permi="['ecw:giftManagement:enable']"
            size="mini"
            type="text"
            icon="el-icon-user"
            :disabled="
              scope.row.status == '1' ||
              scope.row.status == '3' ||
              scope.row.status == '4'
            "
            @click="handleLaunchRewards(scope.row)"
            >{{ $t("启用") }}</el-button
          >
          <el-button
            v-has-permi="['ecw:giftManagement:exchange']"
            :disabled="scope.row.status == '3' || scope.row.status == '4'"
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleExchange(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="getList"
    />
    <!-- 查看 编辑 新增弹窗 -->
    <operating-gift
      ref="operatingGift"
      :title="operatingPagetitle"
      :rewards-details="rewardsItem"
      :show.sync="dialogVisible"
      :node-list="nodeList"
    />
    <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="confirmPostponeRewards">{{
          $t("确 定")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getNodeList,
  getGiftList,
  deleteRewards,
  copyRewardsAPI,
  changeRewardsStatus,
  delayRewards,
} from "@/api/ecw/giftManagement";
import { getDictDatas, DICT_TYPE } from "@/utils/dict";
import { parseTime } from "../../../utils/ruoyi";
import OperatingGift from "@/views/ecw/giftManagement/components/operatingGift.vue";
import { uploadFile } from "@/api/infra/file";
import ImageUpload from "@/components/ImageUpload";
export default {
  name: "GiftManagementList",
  components: {
    OperatingGift,
  },
  data() {
    return {
      getDictDatas,
      env: process.env.NODE_ENV,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 礼品列表
      list: [],
      // 弹出层标题
      operatingPagetitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      rewardsItem: {},
      dateRangeCreateTime: [],
      postponeDatetime: "",
      postponeRewardsID: "",
      dialogPostponeVisible: false,
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10,
        title: null,
        pointsRequire: null,
        pointsRequireSymbol: null,
        pickMethod: null,
        nodeId: null,
        status: "1",
        remark: null,
        quantityRemainSymbol: null,
        quantityRemain: null,
        beginCreateTime: null,
        endCreateTime: null,
      },
      // 网点
      nodeList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
    };
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN";
    },
  },
  created() {
    this.getList();
    this.getNodeList();
  },
  activated() {
    this.getList();
  },
  methods: {
    arraysEqual(arr1, arr2) {
      return arr1.filter((current) => {
        return !!arr2.find((item) => item == current.value.toString());
      });
    },
    handleRewardsStatus(status) {
      return this.getDictDatas(DICT_TYPE.GIFT_STATUS).filter(
        (dicItem) => dicItem.value.toString() == status
      )[0];
    },
    firstImg(imgString) {
      if (!imgString || imgString == "") return imgString;
      const imgs = imgString.split(",");
      return imgs.length ? imgs[0] : null;
    },
    handlePickMethod(pickMethod) {
      const pickMethodLabel = [];
      if (this.isChinese) {
        this.arraysEqual(
          this.getDictDatas(DICT_TYPE.WAY_OF_RECEIVING),
          pickMethod.split(",")
        ).forEach((element) => {
          pickMethodLabel.push(element.label);
        });
      } else {
        this.arraysEqual(
          this.getDictDatas(DICT_TYPE.WAY_OF_RECEIVING),
          pickMethod.split(",")
        ).forEach((element) => {
          pickMethodLabel.push(element.labelEn);
        });
      }
      return pickMethodLabel.join();
    },
    handleExchangeNodeId(nodeId) {
      return this.nodeList.filter((nodeItem) => nodeItem.id == nodeId)[0];
    },
    handleAddReward() {
      this.rewardsItem = {};
      this.dialogVisible = true;
      this.operatingPagetitle = "3";
    },
    handleExchange(row) {
      this.$router.push({
        path: "/giftManagement/bulkExchange",
        query: { rewardsID: row.id },
      });
    },
    /** 延期按钮操作 */
    handlePostpone(row) {
      this.postponeRewardsID = row.id;
      this.dialogPostponeVisible = true;
    },
    confirmPostponeRewards() {
      this.dialogPostponeVisible = false;
      delayRewards({
        id: this.postponeRewardsID,
        endTime: this.postponeDatetime,
      }).then((res) => {
        this.getList();
        this.$message.success(this.$t("延期成功"));
      });
    },
    /** 关闭按钮操作 */
    handleCloseStatus(row) {
      this.$confirm(this.$t("是否关闭当前礼品？"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then((_) => {
          return changeRewardsStatus({ id: row.id, status: "3" });
        })
        .then((res) => {
          this.getList();
          this.$message.success(this.$t("关闭成功"));
        })
        .catch((_) => {
          // this.queryAllData();
        });
    },
    // 启用礼品状态
    handleLaunchRewards(row) {
      this.$confirm(this.$t("是否启用当前礼品？"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then(() => {
          changeRewardsStatus({ id: row.id, status: "1" }).then((r) => {
            this.$message.success(this.$t("启用成功"));
            this.getList();
          });
        })
        .catch(() => {});
    },
    getNodeList() {
      getNodeList().then((res) => {
        this.nodeList = res.data;
      });
    },
    getList() {
      this.loading = true;
      // 处理查询参数
      const params = { ...this.queryParams };
      this.addBeginAndEndTime(
        params,
        this.dateRangeCreateTime,
        "createTime",
        false
      );
      getGiftList(params).then((res) => {
        this.loading = false;
        this.list = res.data.list;
        this.total = res.data.total;
      });
    },

    // 新增潜在客户
    handleAddPotential() {
      this.$refs.potentialCustom.dialogTableVisible = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("是否确认删除此礼品"))
        .then(function () {
          return deleteRewards({ id: row.id });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("删除成功"));
        })
        .catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$nextTick(() => {
        this.queryParams.page = 1;
        this.getList();
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.dialogVisible = true;
      this.operatingPagetitle = "1";
      this.rewardsItem = row;
    },
    /** 编辑按钮操作 */
    editRewards(row) {
      this.dialogVisible = true;
      this.operatingPagetitle = "2";
      this.rewardsItem = row;
    },

    /** 复制按钮操作 */
    copyRewards(row) {
      copyRewardsAPI(row.id).then((res) => {
        this.$modal.msgSuccess(this.$t("复制成功"));
        this.handleQuery();
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.queryParams = {
        page: 1,
        rows: 10,
        number: null,
        name: null,
        level: null,
        source: null,
        customerService: null,
        status: "1",
        department: null,
        creditLevel: null,
        country: null,
        memberCode: null,
        memberName: null,
        memberMobile: null,
        memberAreaCode: null,
      };
      this.handleQuery();
    },
  },
};
</script>
<style>
.rewardstToolTip {
  max-width: 90%;
}
</style>
