<template>
  <div v-loading="loading" class="inviteRuleList-wrap">
    <div class="screenBox" style="align-items: center; padding-right: 16px">
      <div class="flex-align-center" style="flex: 1">
        <!-- 搜索配置 -->
        <self-input
          style="width: auto"
          label_name="关键词"
          :hasLabel="false"
          :noMarLeft="true"
          @inputChange="
            (val) => {
              keyword = val;
              init(1);
            }
          "
        />
        <!-- 关联客服 -->
        <serviceSingle
          style="width: auto"
          title="关联客服"
          placeholder="请选择"
          @customerDefine="onChangeUser"
        />
        <!-- 状态 -->
        <selfChannelV2
          v-model="status"
          type="enableStatus"
          title="规则状态"
          :labelWidth="true"
          @change="onChangeStatus"
        />
      </div>
      <el-button type="primary" size="mini" @click="createdMassMsg"
        >新建配置</el-button
      >
    </div>
    <div class="tableInfo">
      <div>
        <div class="flex">
          <div class="totalCustom">
            共有<span>{{ total }}</span
            >条数据
          </div>
        </div>
      </div>
      <div class="flex">
        <el-button type="primary" plain size="mini" @click="init(1, 'export')"
          >导出Excel</el-button
        >
        <!-- 使用说明 -->
        <!--        <instructions style="margin-left: 20px;" doc="employee_bulk_messaging_log"></instructions>-->
      </div>
    </div>
    <!-- table -->
    <el-table
      ref="multipleTable"
      :height="height"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column
        prop="title"
        label="标题"
        show-overflow-tooltip
        align="center"
        min-width="140"
        fixed="left"
      />
      <el-table-column
        prop="user_name"
        label="创建人"
        show-overflow-tooltip
        align="center"
        min-width="140"
      />
      <el-table-column label="拉群类型" align="center" min-width="140">
        <template slot-scope="scope">
          <div>
            {{
              scope.row.join_type == 1
                ? "顺序拉群"
                : scope.row.join_type == 2
                ? "随机拉群"
                : "-"
            }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="配置状态" align="center" min-width="120">
        <template slot-scope="{ row }">
          <el-switch
            v-if="row.status !== ''"
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            disabled
            @click.native="onClickStatus(row)"
          />
          <div v-else>-</div>
        </template>
      </el-table-column>

      <el-table-column
        min-width="140"
        label="操作"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex" style="justify-content: center">
            <div
              class="c-00B38A pointer table_button"
              @click="goDetail(scope.row)"
            >
              编辑
            </div>
            <!-- <el-popconfirm
              @confirm="handleRefresh(scope.row)"
              :title="`确定重置【${scope.row.title}】退群客户的退群时间范围筛选吗？`"
            >
              <div slot="reference" class="c-448AFF pointer table_button">
                重置
              </div>
            </el-popconfirm> -->
            <el-popconfirm
              @confirm="deleEvent(scope.row)"
              :title="`确定删除【${scope.row.title}】？`"
            >
              <div slot="reference" class="c-FF604D pointer table_button">
                删除
              </div>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" v-show="total > 0">
      <el-pagination
        background
        :current-page="page"
        @current-change="handleCurrentChange"
        layout="prev, pager, next"
        :page-count="Number(pages)"
      />
    </div>
    <el-drawer size="1200px" :visible.sync="massMsgFlag" :with-header="false">
      <createData
        v-if="massMsgFlag"
        ref="createMassMsg"
        :rule_id="detail_rule_id"
        :title="detail_rule_id ? '配置详情' : '新建配置'"
        @close="detailClose"
      />
    </el-drawer>
  </div>
</template>
<script>
import createData from "./createData.vue";
import selfInput from "@/components/assembly/screen/input.vue";
import serviceSingle from "@/components/assembly/screen/serviceSingle.vue";
import selfChannelV2 from "@/components/assembly/screen/channelV2.vue";

export default {
  components: {
    selfInput,
    createData,
    serviceSingle,
    selfChannelV2,
  },
  data() {
    return {
      massMsgFlag: false,
      loading: false,
      page: 1,
      pages: 0,
      total: 0,
      page_size: 20,
      tableData: [],
      height: "",
      detail_rule_id: "",
      keyword: "",
      user_id: "",
      status: "",
    };
  },
  created() {
    this.height = document.documentElement.clientHeight - 290;
    this.init(1);
  },
  methods: {
    //删除
    deleEvent(row) {
      this.$loading(this.$loadingConfig);
      this.$axios
        .get(this.URL.BASEURL + this.URL.inviteRule_dele, {
          params: {
            rule_id: row.rule_id,
          },
        })
        .then((res) => {
          this.$loading(this.$loadingConfig).close();
          var res = res.data;
          if (res && res.errno == 0) {
            this.init(1);
          }
          this.$message({
            message: res.err,
            type: "warning",
          });
        });
    },
    //重置
    handleRefresh(row) {
      this.$loading(this.$loadingConfig);
      this.$axios
        .get(this.URL.BASEURL + this.URL.inviteRule_reset, {
          params: {
            rule_id: row.rule_id,
          },
        })
        .then((res) => {
          this.$loading(this.$loadingConfig).close();
          var res = res.data;
          if (res && res.errno == 0) {
            this.$message({
              message: '重置成功',
              type: "success",
            });
            this.init(this.page);
          } else {
            this.$message({
              message: res.err,
              type: "warning",
            });
          }
        });
    },
    detailClose(val) {
      if (val == "update") {
        //编辑
        this.init(this.page);
      } else if (val == "update_new") {
        //复制或者新建
        this.init(1);
        this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
      }
      this.massMsgFlag = false;
    },
    createdMassMsg() {
      this.detail_rule_id = "";
      this.massMsgFlag = true;
    },
    goDetail(data) {
      this.detail_rule_id = data.rule_id;
      this.massMsgFlag = true;
    },
    // 监听点击切换"状态"
    async onClickStatus(row) {
      try {
        await this.$confirm(
          `确定${row.status == 0 ? "启用" : "禁用"}【${row.title}】?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
        this.handleChangeStatus(row);
      } catch (error) {
        console.log(error);
      }
    },
    // 执行“切换状态”
    async handleChangeStatus({ rule_id, status }) {
      try {
        this.loading = true;
        const url = `${this.URL.BASEURL}${this.URL.inviteRule_editStatus}`;
        const params = {
          rule_id,
          status: status == 1 ? 0 : 1,
        };
        const { data: res = {} } = await this.$axios.get(url, { params });
        if (res && res.errno == 0) {
          this.$message.success("操作成功");
          this.init();
        } else if (res.errno != 4002) {
          this.$message.warning(res.err);
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },

    init(page, type) {
      if (type != "export") {
        this.page = page ? page : this.page;
      } else {
        if (this.total == 0) {
          this.$message({
            message: "暂无数据可导出",
            type: "warning",
          });
          return;
        }
      }
      this.loading = true;
      this.$axios
        .get(this.URL.BASEURL + this.URL.inviteRuleList, {
          params: {
            page: type == "export" ? 1 : this.page,
            page_size:
              type == "export"
                ? this.$store.state.exportNumber
                : this.page_size,
            keyword: this.keyword,
            user_id: this.user_id,
            status: this.status,
          },
        })
        .then((res) => {
          var res = res.data;
          this.loading = false;
          if (res && res.errno == 0) {
            if (type == "export") {
              this.exportEvent(res.rst.data);
            } else {
              this.tableData = res.rst.data;
              this.total = res.rst.pageInfo.total;
              this.pages = res.rst.pageInfo.pages;
            }
          } else if (res.errno != 4002) {
            this.$message.warning(res.err);
          }
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    handleCurrentChange(val) {
      this.init(val);
    },
    onChangeUser(val) {
      this.user_id = val ? val.user_id : "";
      this.init(1);
    },
    onChangeStatus(val) {
      this.status = val;
      this.init(1);
    },
    exportEvent(data) {
      let list = data;
      let tHeader = ["标题", "创建人", "拉群类型", "规则状态"];
      let filterVal = ["title", "user_name", "join_type", "status"];
      list.forEach((item) => {
        item.join_type =
          item.join_type == 1
            ? "顺序拉群"
            : item.join_type == 2
            ? "随机拉群"
            : "-";
        item.status =
          item.status == 1 ? "启用" : item.status == 0 ? "禁用" : "-";
      });
      let excelDatas = [
        {
          tHeader: tHeader, // sheet表一头部
          filterVal: filterVal, // 表一的数据字段
          tableDatas: list, // 表一的整体json数据
          sheetName: "", // 表一的sheet名字
        },
      ];
      this.$exportOrder({
        excelDatas,
        name: `邀请入群配置（导出时间：${this.$getDay(0)}）`,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/style/list.scss";
.tableInfo {
  height: 50px;
}
.table_button {
  margin: 0 4px;
  min-width: 26px;
}

.inviteRuleList-wrap {
  /deep/ .el-switch.is-disabled .el-switch__core {
    cursor: pointer;
  }
  /deep/ .el-switch.is-disabled {
    opacity: 1;
  }
}
</style>
