<template>
  <div style="padding: 20px" class="app-container">
    <div>
      <div class="header">
        <h3>添加新推送</h3>
      </div>

      <span style="color: orange"
        >*选择用户,推送消息附带红包，红包数量需与用户人数一致</span
      >
    </div>
    <el-form ref="form" :rules="rules" :model="form" label-width="150px">
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="主题名称"
            style="margin-top: 30px"
            prop="topicName"
          >
            <el-input
              type="text"
              placeholder="请输入内容"
              v-model="form.topicName"
              maxlength="10"
              show-word-limit
              style="width: 300px"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="推送红包" style="margin-top: 30px">
            <span style="color: orange"
              >设置钱请确认该账户钱包余额是否满足,此次营销所需金额，如不满足请先去充值</span
            >
          </el-form-item>
          <el-form-item
            label="红包个数"
            prop="redEnvelopeNum"
            style="margin-left: 70px"
          >
            <el-input-number
              v-model="form.redEnvelopeNum"
              style="width: 150px"
              :controls="false"
              max="100"
              min="0"
            ></el-input-number
            >个
          </el-form-item>
          <el-form-item
            label="单个金额"
            prop="singleAmount"
            style="margin-left: 70px"
          >
            <el-input-number
              v-model="form.singleAmount"
              style="width: 150px"
              :controls="false"
              max="100"
              min="0"
            ></el-input-number
            >元
          </el-form-item>
          <el-form-item
            label="红包时效"
            prop="redEnvelopePeriod"
            style="margin-left: 70px"
          >
            <el-input-number
              v-model="form.redEnvelopePeriod"
              style="width: 150px"
              :controls="false"
              max="100"
              min="0"
            ></el-input-number
            >天
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="推送消息"
            style="margin-top: 30px"
            prop="pushMessage"
          >
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入内容"
              v-model="form.pushMessage"
              :show-word-limit="true"
              style="width: 500px"
              maxlength="100"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="选择用户" style="margin-top: 30px">
            <el-button type="primary" size="small" @click="selectProDuct"
              >选择用户</el-button
            >
          </el-form-item>
          <div style="margin-left: 30px">
            已选{{ multipleSelection.length }}人
            <el-button size="small" style="margin-left: 10px" @click="addRemove"
              >批量移除</el-button
            >
          </div>

          <el-table
            :data="tableData"
            style="width: 100%; margin-left: 30px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="用户ID" align="center" prop="id" />
            <el-table-column label="用户头像" align="center">
              <template slot-scope="scope">
                <el-image
                  style="width: 60px; height: 60px"
                  :src="scope.row.headUrl"
                  :preview-src-list="[scope.row.headUrl]"
                >
                </el-image>
              </template>
            </el-table-column>

            <el-table-column label="用户昵称" align="center" prop="nick" />
            <el-table-column
              label="浏览记录"
              align="center"
              prop="browseRecord"
            />
            <el-table-column
              label="距离"
              align="center"
              width="120"
              prop="distance"
            />
            <el-table-column
              label="下单记录"
              align="center"
              prop="orderRecord"
            />
            <el-table-column
              label="近期推送记录"
              align="center"
              prop="topicName"
            />
            <el-table-column
              v-if="showButton"
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              width="100"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="remove(scope.row, scope.$index)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNo"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
        <el-col
          :span="24"
          style="text-align: center; margin-top: 20px"
          v-if="showButton"
        >
          <el-button @click="cancel">取消</el-button>
          <el-button @click="submitForm" type="primary">保存</el-button>
        </el-col>
      </el-row>
    </el-form>
    <userDialog
      ref="productDialog"
      @productDialogInfo="productDialogInfo"
    ></userDialog>
  </div>
</template>

<script>
import * as markApi from "@/api/marketing/index";
import { getGoodsListPage } from "@/api/manage/product";
import userDialog from "./components/user-dialog.vue";
export default {
  components: { userDialog },
  data() {
    return {
      showButton: true,
      form: {
        pushMessage: null,
        redEnvelopeNum: null,
        redEnvelopePeriod: null,
        singleAmount: null,
        topicName: null,
        selectUserId: "",
      },
      rules: {
        proportion: [
          { required: true, message: "请输入分享奖励比例", trigger: "blur" },
        ],
      },
      tableData: [],
      multipleSelection: [],
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        isShare: 1,
        spuIds: null,
      },
    };
  },
  mounted() {},
  methods: {
    cancel() {
      this.$confirm("是否确认取消,所填写的信息将会消失?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("tagsView/delView", this.$route); //关闭当前页
          this.$router.replace({ path: "/marketing/marketing/list" });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    addRemove() {
      if (this.multipleSelection.length < 1) {
        this.$message.error("请先选择要移除的商品！");
        return false;
      }
      let ids = [];
      this.multipleSelection.forEach((e) => {
        ids.push(e.id);
      });
      let idlist = JSON.parse(this.form.selectGoodsIds);
      const diff1 = idlist.filter((item) => !ids.includes(item));
      this.$confirm("是否移除已选商品,移除后, 该商品不可获得分享奖励", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          batchRemove({
            id: this.$route.query.item.id,
            removeGoodsIds: JSON.stringify(ids),
            selectGoodsIds: JSON.stringify(diff1),
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("移除成功！");
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    remove(row, index) {
      let ids = JSON.parse(this.form.selectGoodsIds);
      ids.forEach((e, index) => {
        if (e == row.id) {
          ids.splice(index, 1);
        }
      });
      this.$confirm(
        "是否移除已选商品,移除后, 该商品不可使用获得分享奖励",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          batchRemove({
            id: this.$route.query.item.id,
            removeGoodsIds: JSON.stringify([row.id]),
            selectGoodsIds: JSON.stringify(ids),
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("移除成功！");
              this.tableData.splice(index, 1);

              // this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    productDialogInfo(list) {
      this.tableData = [...this.tableData, ...list];
      this.tableData = this.tableData.filter((item, index, self) => {
        return self.findIndex((t) => t.id === item.id) === index;
      });
    },
    selectProDuct() {
      this.$refs.productDialog.openDialog();
    },
    submitForm() {
      if (this.tableData.length < 1) {
        this.$message.error("请选择可以推送的用户！");
        return;
      }
      let ids = [];
      this.tableData.forEach((e) => {
        ids.push(e.id);
      });
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm("是否确认保存新增?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.form.selectUserId = ids;
              markApi.aiMarketingSave(this.form).then((res) => {
                if (res.code == 200) {
                  this.$message.success("保存成功！");
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.$router.replace({ path: "/marketing/marketing/list" });
                  this.getList();
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        } else {
          return false;
        }
      });
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      getGoodsListPage(this.queryParams).then((res) => {
        this.tableData = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      });
    },
  },
};
</script>

<style scoped>
.header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
</style>
