<script setup>
import { ref, onMounted } from "vue";
import Sortable from "sortablejs";
import mPage from "@/components/mPage.vue";
import { raiInterface } from "@/api/api.js";
import LableDlg from "./components/lableDlg.vue";
import { ElMessage,ElMessageBox } from "element-plus";

const labelForm = ref({
  TagName: "",
  ArticleTypes: "", //关联的报告系列
  ActivityTypes: [],
  Industries: "", //关联产业列表
  SubjectNames: "",
});
const rules = ref({
  TagName: [{ required: true, message: "请输入标签名称", trigger: "blur" }],
});
const dialogVisible = ref(false);

const tableSelect = ref([
  {
    name: "当前标签数据",
    value: 1,
  },
  {
    name: "已撤下的标签",
    value: 0,
  },
]);

const page_no = ref(1);
const total = ref(0);
const pageSize = ref(10);
const lableList = ref([]);
const tableList = ref([]);
// 获取表格列表
async function getDataList() {
  const res = await raiInterface.getLableTagList({
    Status: tableSelectActive.value,
    PageSize: pageSize.value,
    CurrentIndex: page_no.value,
    SortParam: "pv",
    SortType: sortType.value,
  });
  if (res.Ret === 200) {
    total.value = res.Data.Paging.Totals;
    tableList.value = res.Data.List || [];
  }
}
// 获取标签列表
async function getLableTagList() {
  const res = await raiInterface.getLableTagListCustom();
  if (res.Ret === 200) {
    lableList.value = res.Data || [];
  }
}

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

// 表格的切换点击事件
function tableSelectHandel(item) {
  if (tableSelectActive.value !== item.value) {
    page_no.value = 1;
    tableSelectActive.value = item.value;
    getDataList();
  }
}
// 重新上线    // 撤下标签
function lableButtonHandel(type, item) {
  ElMessageBox.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) {
        getLableTagList();
        getDataList();
        ElMessage({
          type: "success",
          message: "操作成功!",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}
// 分页的事件
function handleCurrentChange(page) {
  page_no.value = page;
  getDataList();
}

const tableSelectActive = ref(1);
const optionsSubject = ref([]);
const dlgTitle = ref("添加");
const showRegularDlg = ref(false);
const dataRegular = ref({});
const sortType = ref("");
const lableSortable = ref(null);
// 拖拽的事件
function setupSortable() {
  const sortableInstanceIs = Sortable.create(lableSortable.value, {
    ghostClass: "sortable-ghost", // drop placeholder的css类名
    sort: true,
    onEnd(obj) {
      const { newIndex, oldIndex } = obj;
      // const newList = _.cloneDeep(lableList.value);
      const newList = lableList.value;
      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,
      };
      postLableTagMove(params);
    },
  });
}
// 拖拽的事件
async function postLableTagMove(params) {
  const res = await raiInterface.postLableTagMove(params);
  if (res.Ret === 200) {
    getLableTagList();
    getDataList();
    ElMessage.success("移动成功");
  }
}
// 添加或者编辑标签
function addOfEitdHandler(type, item) {
  if (item && item.TagType > 0) {
    dataRegular.value = item;
    showRegularDlg.value = true;
    return;
  }
  dlgTitle.value = type;
  if (item) {
    const { TagName, ArticleTypes, ActivityTypes, Industries, SubjectNames, TagId } = item;
    labelForm.value.TagName = TagName;
    labelForm.value.ArticleTypes = ArticleTypes ? ArticleTypes.split(",") : [];
    labelForm.value.ActivityTypes = ActivityTypes ? ActivityTypes.split(",") : [];
    labelForm.value.Industries = Industries ? Industries.split(",") : [];
    labelForm.value.SubjectNames = SubjectNames ? SubjectNames.split(",") : [];
    labelForm.value.TagId = TagId;
  }
  dialogVisible.value = true;
}
// pv uv  下载
function exportPvUv(id) {
  const url = import.meta.env.VITE_APP_API_ROOT + `/cygx/tag/PvExport?TagId=${id}&${localStorage.getItem("auth") || ""}`;
  return url;
}
// 添加标签
function addTagHandler() {
  ruleForm.value.validate(async (valid) => {
    if (valid) {
      let { ArticleTypes, ActivityTypes, Industries, SubjectNames } = labelForm.value;
      if (!ArticleTypes.length && !ActivityTypes.length && !SubjectNames.length && !Industries.length) return ElMessage.error("请至少填写一个关联项");
      let params = {
        TagName: labelForm.value.TagName,
        ArticleTypes: ArticleTypes ? ArticleTypes.join(",") : "",
        ActivityTypes: ActivityTypes ? ActivityTypes.join(",") : "",
        Industries: Industries ? Industries.join(",") : "",
        SubjectNames: SubjectNames ? SubjectNames.join(",") : "",
        TagId: dlgTitle.value == "添加" ? 0 : labelForm.value.TagId,
      };
      const res = await raiInterface.postLableTagSave(params);
      if (res.Ret === 200) {
        handleClose();
        getLableTagList();
        getDataList();
        ElMessage.success("操作成功");
      }
    } else {
      console.log("error submit!!");
      return false;
    }
  });
}

const optionsArticle = ref([]);
const optionsActivity = ref([]);
const optionsIndustries = ref([]);
// 关闭弹框
function handleClose() {
  optionsArticle.value = [];
  optionsIndustries.value = [];
  optionsSubject.value = [];
  labelForm.value = {
    TagName: "",
    ArticleTypes: "", //关联的报告系列
    ActivityTypes: [],
    Industries: "", //关联产业列表
    SubjectNames: "",
  };
  dialogVisible.value = false;
  ruleForm.value.resetFields();
}

const ruleForm = ref(null);
// 搜索所有的报告系列
async function remoteMethodArticle(query) {
  if (query !== "") {
    const res = await raiInterface.getLableTagSubCategoryName({
      KeyWord: query,
    });
    if (res.Ret === 200) {
      optionsArticle.value = res.Data || [];
    }
  } else {
    optionsArticle.value = [];
  }
}
// 产业
async function remoteMethodIndustries(query) {
  if (query !== "") {
    const res = await raiInterface.getLableTagIndustrialManagement({
      KeyWord: query,
    });
    if (res.Ret === 200) {
      optionsIndustries.value = res.Data.List || [];
    }
  } else {
    optionsIndustries.value = [];
  }
}
// 标的
async function remoteMethodSubject(query) {
  if (query !== "") {
    const res = await raiInterface.industrialSubjectSearch({
      KeyWord: query,
    });
    if (res.Ret === 200) {
      optionsSubject.value = res.Data.List || [];
    }
  } else {
    optionsSubject.value = [];
  }
}
function sortChangeHandle(column) {
  sortType.value = column.order == "descending" ? "desc" : column.order == "ascending" ? "asc" : "";
  getDataList();
}
onMounted(() => {
  setupSortable();
  getDataList();
  getLableTagList();
  activityType();
});
</script>

<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 #default="{ 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 #default="{ 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" v-model="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>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="addTagHandler">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <lable-dlg :showRegularDlg="showRegularDlg" :dataRegular="dataRegular" />
  </div>
</template>

<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>
