<template>
  <div class="container lable-manage-page">
    <el-card style="overflow: hidden">
      <div class="top-comtent">
        <div>
          <span>当前标签</span>
          <span>自定义标签</span>
          <span>固定标签</span>
        </div>
        <el-button type="primary" @click="addOfEitdHandler('添加')">添加标签</el-button>
      </div>
      <div ref="lableSortable" class="lable-content">
        <div :class="['lable-item', item.TagType > 0 && 'regular-lable']" v-for="item in lableList" :key="item.TagId">
          <div class="text_oneLine">{{ item.TagName }}</div>
          <div class="lable-img" v-if="item.TagType">
            <img src="~@/assets/img/rai_m/edit_icon_GuDing.png" alt="" @click="addOfEitdHandler('编辑', item)" />
            <img src="~@/assets/img/rai_m/remove_below_GuDing.png" alt="" @click="lableButtonHandel('撤下', item)" />
          </div>
          <div class="lable-img" v-else>
            <img src="~@/assets/img/rai_m/edit_icon.png" alt="" @click="addOfEitdHandler('编辑', item)" />
            <img src="~@/assets/img/rai_m/remove_below.png" alt="" @click="lableButtonHandel('撤下', item)" />
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <div class="lable-select-box">
        <div v-for="(item, index) in tableSelect" :key="item.value" @click="tableSelectHandel(item)" class="item">
          <span :class="['name', tableSelectActive == item.value && 'active']">{{ item.name }}</span>
          <span v-if="index == 0" class="divide">|</span>
        </div>
      </div>
      <el-table border :data="tableList" @sort-change="sortChangeHandle">
        <el-table-column align="center" key="name" prop="TagName" label="标签名称" width=""></el-table-column>
        <el-table-column align="center" key="series" prop="ArticleTypes" label="报告类型" width=""></el-table-column>
        <el-table-column align="center" key="type" prop="ActivityTypes" label="活动类型" width=""></el-table-column>
        <el-table-column align="center" key="industry" prop="Industries" label="相关产业" width=""></el-table-column>
        <el-table-column align="center" key="subject" prop="SubjectNames" label="相关标的" width=""></el-table-column>
        <el-table-column align="center" key="tiem" prop="OnlineTime" label="上线时间" width="180"></el-table-column>
        <el-table-column align="center" key="remove" prop="OfflineTime" label="撤下时间" width="180" v-if="tableSelectActive == 0"></el-table-column>
        <el-table-column align="center" key="pvuv" prop="Sort" label="pv/uv" width="90" sortable="custom">
          <template slot-scope="{ row }">
            <div class="pv-uv-download">
              <span>{{ row.Pv }}/{{ row.Uv }}</span>
              <a :href="exportPvUv(row.TagId)" download>
                <img src="~@/assets/img/rai_m/pvuv_download.png" alt="" />
              </a>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" key="operate" label="操作" width="125" v-if="tableSelectActive == 0">
          <template slot-scope="{ row }">
            <span class="editsty" @click="lableButtonHandel('上线', row)">重新上线 &nbsp;&nbsp;</span>
          </template>
        </el-table-column>
      </el-table>
      <el-col :span="24" class="toolbar">
        <m-page :total="total" :page_no="page_no" @handleCurrentChange="handleCurrentChange" />
      </el-col>
    </el-card>
    <div>
      <el-dialog :title="dlgTitle" @close="handleClose" :visible.sync="dialogVisible" width="566px" :close-on-click-modal="false" :modal-append-to-body="false">
        <div>
          <el-form :model="labelForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
            <el-form-item prop="TagName">
              <el-input style="width: 100%" :maxlength="8" v-model="labelForm.TagName" placeholder="请输入标签名称(8个字以内)"></el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                style="width: 100%"
                v-model="labelForm.ArticleTypes"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入关联的报告类型（选填，可输入多个）"
                :remote-method="remoteMethodArticle"
              >
                <el-option v-for="item in optionsArticle" :key="item.SubCategoryName" :label="item.SubCategoryName" :value="item.SubCategoryName"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select style="width: 100%" multiple v-model="labelForm.ActivityTypes" placeholder="请输入关联的活动类型（选填，可输入多个）">
                <el-option v-for="item in optionsActivity" :label="item.ActivityTypeName" :key="item.ActivityTypeName" :value="item.ActivityTypeName"></el-option
              ></el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                style="width: 100%"
                v-model="labelForm.Industries"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入相关产业（选填，可输入多个）"
                :remote-method="remoteMethodIndustries"
              >
                <el-option v-for="item in optionsIndustries" :key="item.IndustryName" :label="item.IndustryName" :value="item.IndustryName"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                style="width: 100%"
                v-model="labelForm.SubjectNames"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入相关标的（选填，可输入多个）"
                :remote-method="remoteMethodSubject"
              >
                <el-option v-for="item in optionsSubject" :key="item.SubjectName" :label="item.SubjectName" :value="item.SubjectName"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="addTagHandler">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <lable-dlg :showRegularDlg.sync="showRegularDlg" :dataRegular.sync="dataRegular" />
  </div>
</template>

<script>
import Sortable from "sortablejs";
import mPage from "@/components/mPage.vue";
import { raiInterface } from "@/api/api.js";
import LableDlg from "./components/lableDlg.vue";
export default {
  name: "",
  components: { mPage, LableDlg },
  props: {},
  data() {
    return {
      labelForm: {
        TagName: "",
        ArticleTypes: "", //关联的报告系列
        ActivityTypes: [],
        Industries: "", //关联产业列表
        SubjectNames: "",
      },
      rules: {
        TagName: [{ required: true, message: "请输入标签名称", trigger: "blur" }],
      },
      dialogVisible: false,
      page_no: 1,
      total: 0,
      pageSize: 10,
      lableList: [],
      tableList: [],
      tableSelect: [
        {
          name: "当前标签数据",
          value: 1,
        },
        {
          name: "已撤下的标签",
          value: 0,
        },
      ],
      tableSelectActive: 1,
      optionsArticle: [],
      optionsActivity: [],
      optionsIndustries: [],
      optionsSubject: [],
      dlgTitle: "添加",
      showRegularDlg: false,
      dataRegular: {},
      sortType: "",
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.setupSortable();
    this.getDataList();
    this.getLableTagList();
    this.activityType();
  },
  methods: {
    // 获取表格列表
    async getDataList() {
      const res = await raiInterface.getLableTagList({
        Status: this.tableSelectActive,
        PageSize: this.pageSize,
        CurrentIndex: this.page_no,
        SortParam: "pv",
        SortType: this.sortType,
      });
      if (res.Ret === 200) {
        this.total = res.Data.Paging.Totals;
        this.tableList = res.Data.List || [];
      }
    },
    // 获取标签列表
    async getLableTagList() {
      const res = await raiInterface.getLableTagListCustom();
      if (res.Ret === 200) {
        this.lableList = res.Data || [];
      }
    },

    // 获取活动类型
    async activityType() {
      const res = await raiInterface.getActivityType({
        IsGetAll: true,
      });
      if (res.Ret === 200) {
        this.optionsActivity = res.Data.List;
      }
    },

    // 表格的切换点击事件
    tableSelectHandel(item) {
      if (this.tableSelectActive !== item.value) {
        this.page_no = 1;
        this.tableSelectActive = item.value;
        this.getDataList();
      }
    },
    // 重新上线    // 撤下标签
    lableButtonHandel(type, item) {
      this.$confirm(type == "撤下" ? "确定要撤下此标签吗?" : "确定要重新上线此标签吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await raiInterface.getLableTagEnable({
            Status: item.Status == 0 ? 1 : 0,
            TagId: item.TagId,
          });
          if (res.Ret === 200) {
            this.getLableTagList();
            this.getDataList();
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 分页的事件
    handleCurrentChange(page) {
      this.page_no = page;
      this.getDataList();
    },
    // 拖拽的事件
    setupSortable() {
      const _this = this;
      const sortableInstanceIs = Sortable.create(this.$refs.lableSortable, {
        ghostClass: "sortable-ghost", // drop placeholder的css类名
        sort: true,
        onEnd(obj) {
          const { newIndex, oldIndex } = obj;
          const newList = _.cloneDeep(_this.lableList);
          let PrevTagId = 0;
          let NextTagId = 0;
          if (newIndex === 0) {
            PrevTagId = 0;
            NextTagId = newList[newIndex].TagId;
          } else if (newIndex === newList.length - 1) {
            PrevTagId = newList[newIndex].TagId;
            NextTagId = 0;
          } else {
            if (newIndex > oldIndex) {
              NextTagId = newList[newIndex + 1].TagId;
              PrevTagId = newList[newIndex].TagId;
            } else {
              NextTagId = newList[newIndex].TagId;
              PrevTagId = newList[newIndex - 1].TagId;
            }
          }
          let params = {
            TagId: newList[oldIndex].TagId,
            PrevTagId,
            NextTagId,
          };
          _this.postLableTagMove(params);
        },
      });
    },
    // 拖拽的事件
    async postLableTagMove(params) {
      const res = await raiInterface.postLableTagMove(params);
      if (res.Ret === 200) {
        this.getLableTagList();
        this.getDataList();
        this.$message.success("移动成功");
      }
    },
    // 添加或者编辑标签
    addOfEitdHandler(type, item) {
      if (item && item.TagType > 0) {
        this.dataRegular = item;
        this.showRegularDlg = true;
        return;
      }
      this.dlgTitle = type;
      if (item) {
        const { TagName, ArticleTypes, ActivityTypes, Industries, SubjectNames, TagId } = item;
        this.labelForm.TagName = TagName;
        this.labelForm.ArticleTypes = ArticleTypes ? ArticleTypes.split(",") : [];
        this.labelForm.ActivityTypes = ActivityTypes ? ActivityTypes.split(",") : [];
        this.labelForm.Industries = Industries ? Industries.split(",") : [];
        this.labelForm.SubjectNames = SubjectNames ? SubjectNames.split(",") : [];
        this.labelForm.TagId = TagId;
      }
      this.dialogVisible = true;
    },
    // pv uv  下载
    exportPvUv(id) {
      const url = process.env.API_ROOT + `/cygx/tag/PvExport?TagId=${id}&${localStorage.getItem("auth") || ""}`;
      return url;
    },
    // 添加标签
    addTagHandler() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { ArticleTypes, ActivityTypes, Industries, SubjectNames } = this.labelForm;
          if (!ArticleTypes.length && !ActivityTypes.length && !SubjectNames.length && !Industries.length) return this.$message.error("请至少填写一个关联项");
          let params = {
            TagName: this.labelForm.TagName,
            ArticleTypes: ArticleTypes ? ArticleTypes.join(",") : "",
            ActivityTypes: ActivityTypes ? ActivityTypes.join(",") : "",
            Industries: Industries ? Industries.join(",") : "",
            SubjectNames: SubjectNames ? SubjectNames.join(",") : "",
            TagId: this.dlgTitle == "添加" ? 0 : this.labelForm.TagId,
          };
          const res = await raiInterface.postLableTagSave(params);
          if (res.Ret === 200) {
            this.handleClose();
            this.getLableTagList();
            this.getDataList();
            this.$message.success("操作成功");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 关闭弹框
    handleClose() {
      this.optionsArticle = [];
      this.optionsIndustries = [];
      this.optionsSubject = [];
      this.labelForm = {
        TagName: "",
        ArticleTypes: "", //关联的报告系列
        ActivityTypes: [],
        Industries: "", //关联产业列表
        SubjectNames: "",
      };
      this.dialogVisible = false;
      this.$refs.ruleForm.resetFields();
    },
    // 搜索所有的报告系列
    async remoteMethodArticle(query) {
      if (query !== "") {
        const res = await raiInterface.getLableTagSubCategoryName({
          KeyWord: query,
        });
        if (res.Ret === 200) {
          this.optionsArticle = res.Data || [];
        }
      } else {
        this.optionsArticle = [];
      }
    },
    // 产业
    async remoteMethodIndustries(query) {
      if (query !== "") {
        const res = await raiInterface.getLableTagIndustrialManagement({
          KeyWord: query,
        });
        if (res.Ret === 200) {
          this.optionsIndustries = res.Data.List || [];
        }
      } else {
        this.optionsIndustries = [];
      }
    },
    // 标的
    async remoteMethodSubject(query) {
      if (query !== "") {
        const res = await raiInterface.industrialSubjectSearch({
          KeyWord: query,
        });
        if (res.Ret === 200) {
          this.optionsSubject = res.Data.List || [];
        }
      } else {
        this.optionsSubject = [];
      }
    },
    sortChangeHandle(column) {
      this.sortType = column.order == "descending" ? "desc" : column.order == "ascending" ? "asc" : "";
      this.getDataList();
    },
  },
};
</script>
<style scoped lang="scss">
.lable-manage-page {
  .top-comtent {
    display: flex;
    align-items: center;
    justify-content: space-between;
    div {
      :nth-child(2),
      :nth-child(3) {
        font-size: 12px;
        font-weight: 400;
        text-align: center;
        display: inline-block;
        width: 80px;
        height: 30px;
        line-height: 30px;
        background: #ecf5ff;
        border: 1px solid #b3d8ff;
        color: #409eff;
        border-radius: 4px;
        margin-left: 10px;
      }
      :nth-child(3) {
        background-color: #fff8e4;
        border: 1px solid #ffd9c2;
        color: #e37318;
      }
    }
    span {
      font-weight: 500;
      font-size: 16px;
    }
  }
  .lable-content {
    display: flex;
    flex-wrap: wrap;
    padding: 30px 0;
    width: 105%;
    .lable-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 205px;
      height: 40px;
      background: #ecf5ff;
      border: 1px solid #b3d8ff;
      color: #409eff;
      border-radius: 4px;
      margin: 0 30px 20px 0;
      padding: 0 10px;
      cursor: move;
      box-sizing: border-box;
      .lable-img {
        width: 38px;
        flex-shrink: 0;
        display: flex;
        justify-content: space-between;
        cursor: pointer;
        img {
          width: 14px;
          height: 14px;
        }
      }
    }
    .sortable-ghost {
      width: 100px;
      height: 1px;
      border: 2px solid #409eff;
      overflow: hidden;
    }
    .regular-lable {
      background-color: #fff8e4 !important;
      border: 1px solid #ffd9c2;
      color: #e37318;
    }
  }
  .pv-uv-download {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 14px;
      height: 14px;
      margin-left: 10px;
    }
  }
  .lable-select-box {
    display: flex;
    margin-bottom: 20px;
    .item {
      display: flex;
      line-height: 40px;
      cursor: pointer;
      .name {
        width: 120px;
        height: 40px;
        text-align: center;
      }
      .divide {
        padding: 0 20px;
      }
    }
    .active {
      background: #409eff;
      border-radius: 4px;
      color: #fff;
    }
  }
}
</style>
