<template>
  <el-dialog
    :title="$t('选择礼品')"
    :visible.sync="dialogVisible"
    width="80%"
    :before-close="dialogBeforeClose"
  >
    <div class="container">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item :label="$t('礼品名称')">
          <el-input
            v-model.trim="queryParams.title"
            :placeholder="$t('请输入礼品名称')"
            clearable
            @keyup.enter.native="handleQuery"
            onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
          />
        </el-form-item>
        <el-form-item :label="$t('兑换积分')">
          <el-row :gutter="10">
            <el-col :span="8">
              <dict-selector
                clearable
                :type="DICT_TYPE.QUANTITATIVE_RELATION_SYMBOL"
                v-model="queryParams.pointsRequireSymbol"
                @change="handleQuery"
              >
              </dict-selector>
            </el-col>
            <el-col :span="16">
              <el-input
                v-model.trim="queryParams.pointsRequire"
                :placeholder="$t('请输入数字')"
                clearable
                @keyup.enter.native="handleQuery"
                onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item :label="$t('领取方式')" prop="level">
          <dict-selector
            clearable
            :type="DICT_TYPE.WAY_OF_RECEIVING"
            v-model="queryParams.pickMethod"
            @change="handleQuery"
          >
          </dict-selector>
        </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
            clearable
            :type="DICT_TYPE.GIFT_STATUS"
            v-model="queryParams.status"
            @change="handleQuery"
          >
          </dict-selector>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="level">
          <el-input
            v-model.trim="queryParams.remark"
            :placeholder="$t('请输入备注')"
            clearable
            @keyup.enter.native="handleQuery"
            onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
          />
        </el-form-item>
        <el-form-item :label="$t('剩余数量')">
          <el-row :gutter="10">
            <el-col :span="8">
              <dict-selector
                clearable
                :type="DICT_TYPE.QUANTITATIVE_RELATION_SYMBOL"
                v-model="queryParams.quantityRemainSymbol"
                @change="handleQuery"
              >
              </dict-selector>
            </el-col>
            <el-col :span="16">
              <el-input
                v-model.trim="queryParams.quantityRemain"
                :placeholder="$t('请输入数字')"
                clearable
                @keyup.enter.native="handleQuery"
                onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item :label="$t('创建时间')">
          <el-date-picker
            type="datetimerange"
            clearable
            placement="bottom-start"
            v-model="dateRangeCreateTime"
            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">
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </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>
        <el-table-column :label="$t('礼品名称')" align="center">
          <template slot-scope="scope">
            <el-button type="text" >{{
              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="160" :label="$t('开始日期')">
          <template v-slot="{ row }">
            {{ parseTime(row.createTime) || "/" }}
          </template>
        </el-table-column>
        <el-table-column width="160" :label="$t('结束日期')">
          <template v-slot="{ row }">
            {{ parseTime(row.endTime) || "/" }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('兑换积分')"
          prop="pointsRequire"
        ></el-table-column>
        <el-table-column
          :label="$t('领取方式')"
          align="center"
          prop="pickMethod"
        >
          <template v-slot="{ row }">
            {{ handlePickMethod(row.pickMethod) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('提货点')" align="center">
          <template v-slot="{ 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>
        <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"
          prop="exchangeCount"
        ></el-table-column>
        <el-table-column
          :label="$t('剩余数量')"
          align="center"
          prop="quantityRemain"
        ></el-table-column>
        <el-table-column
          width="100px"
          align="center"
          :label="$t('操作')"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="transferSelectRewards(scope.row)"
              :disabled="scope.row.status != '1'"
              >{{ $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"
      />
    </div>
  </el-dialog>
</template>
<script>
import {
  getNodeList,
  getGiftList,
  deleteRewards,
  copyRewardsAPI,
  changeRewardsStatus,
  delayRewards,
  getWarehouseList,
} from "@/api/ecw/giftManagement";
import { getDictDatas, DICT_TYPE } from "@/utils/dict";
import { parseTime } from "@/utils/ruoyi";
import { uploadFile } from "@/api/infra/file";
import ImageUpload from "@/components/ImageUpload";
export default {
  name: "chooseGift",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    dialogVisible(val) {
      if (val == true) {
        this.handleQuery();
      }
    },
  },
  data() {
    return {
      env: process.env.NODE_ENV,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 礼品列表
      list: [],
      rewardsItem: {},
      dateRangeCreateTime: [],
      postponeDatetime: "",
      postponeRewardsID: "",
      // 查询参数
      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: [],
    };
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN";
    },
  },
  created() {
    this.getList();
    this.getNodeList();
  },
  activated() {
    this.getList();
  },
  methods: {
    transferSelectRewards(row) {
      this.$emit("transferSelectRewards", row);
      this.dialogBeforeClose();
    },
    dialogBeforeClose() {
      this.loading = true;
      this.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,
      };
      // this.dialogVisible = false;
      this.$emit("update:dialogVisible", false);
    },
    arraysEqual(arr1, arr2) {
      return arr1.filter((current) => {
        return arr2.find((item) => item == current.value.toString())
          ? true
          : false;
      });
    },
    handleRewardsStatus(status) {
      return this.getDictDatas(DICT_TYPE.GIFT_STATUS).filter(
        (dicItem) => dicItem.value.toString() == status
      )[0];
    },
    firstImg(imgString) {
      if (!imgString || imgString == "") return imgString;
      let imgs = imgString.split(",");
      return imgs.length ? imgs[0] : null;
    },
    handlePickMethod(pickMethod) {
      let 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];
    },
    handleExchange(row) {
      this.$router.push({
        path: "/member/giftManagement/bulkExchange",
        query: { rewardsID: row.id },
      });
    },
    /** 关闭按钮操作 */
    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();
        });
    },

    getNodeList() {
      let params = { title: "" };
      getWarehouseList(params).then((res) => {
        this.nodeList = res.data;
      });
    },
    getList() {
      this.loading = true;
      // 处理查询参数
      let 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;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.$nextTick(() => {
        this.queryParams.page = 1;
        this.getList();
      });
    },

    /** 重置按钮操作 */
    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>
