<template>
  <div class="basics-set bgw flex flexc">
    <TabHeader icon="el-icon-notebook-2" label="样表基础设置"></TabHeader>
    <div class="pd15 flex1 auto-scroll">
      <div class="header">
        <span class="mr15 title">热门搜索词汇</span>
        <span class="tips"
          >点击热门词汇，自动检索。系统默认展示搜索量最多的10个词，每个词展示6个汉字，支持手动修改。</span
        >
      </div>
      <!-- 标签 -->
      <div class="mt20">
        <template v-for="item in baseSetInfo.hotwords">
          <el-tooltip
            class="item"
            effect="dark"
            :key="item.id"
            :content="item.hotwords"
            v-if="item.hotwords && item.hotwords.length > 6"
            placement="top-start"
          >
            <el-tag
              :key="item.id"
              size="small"
              closable
              :disable-transitions="false"
              @close="handleClose(item.hotwords)"
            >
              {{ `${item.hotwords.slice(0, 6)}...` }}
            </el-tag>
          </el-tooltip>
          <el-tag
            :key="item.id"
            size="small"
            v-else
            closable
            :disable-transitions="false"
            @close="handleClose(item.hotwords)"
          >
            {{ item.hotwords }}
          </el-tag>
        </template>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="mini"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="mini" @click="showInput"
          >+ 添加词汇
        </el-button>
      </div>
      <div class="mt20">
        <div class="header">
          <span class="mr15 title">首页应用</span>
          <span class="tips">最多显示4个应用。</span>
        </div>
        <div class="mt20 flex">
          <div>
            <template v-for="item in showApps">
              <el-tag
                style="cursor: pointer"
                :key="item.id"
                size="medium"
                closable
                :disable-transitions="false"
                @close="handleCloseApp(item.id)"
                @click="handleEditApp(item)"
              >
                {{ item.appName }}
              </el-tag>
            </template>
          </div>
          <el-button class="button-new-tag" size="mini" @click="openSiteApp"
            >+ 添加应用
          </el-button>
        </div>
      </div>
      <div class="mt50">
        <el-button size="small" @click="handleReset">重 置</el-button>
        <el-button size="small" type="primary" @click="handleOk"
          >确 定
        </el-button>
      </div>
    </div>
    <!-- 添加应用 -->
    <el-dialog
      :title="isEdit ? '编辑应用' : '添加应用'"
      :visible.sync="showAddApp"
      width="30%"
      @close="closeSiteApp"
    >
      <div>
        <el-form
          ref="form"
          :model="form"
          size="medium"
          :rules="rules"
          label-width="80px"
        >
          <div v-if="!isEdit">
            <el-form-item label="站点应用" prop="appId">
              <el-select
                size="medium"
                v-model="form.appId"
                placeholder="请选择应用"
                filterable
                clearable
                multiple
              >
                <el-option
                  v-for="v in selectOptions"
                  :key="v.id"
                  :label="v.appName"
                  :value="v.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item v-else label="应用名称">
            <el-input :value="form.appName" disabled> </el-input>
          </el-form-item>
          <el-form-item label="排序" prop="order">
            <el-input-number
              v-model="form.order"
              controls-position="right"
              :min="0"
            ></el-input-number>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetAddApp">重 置</el-button>
        <el-button type="primary" @click="saveApp">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBaseSetInfo,
  saveBaseSet,
  getAppList,
  delApp,
  batchSaveApp,
} from "@/api/baseSet";
import { getSiteAppList } from "@/api/siteInfo";
import local from "@/utils/local";
import TabHeader from "@/components/TabHeader.vue";
export default {
  components: {
    TabHeader,
  },
  data() {
    return {
      siteId: local.getLocal("sampleSiteId")
        ? local.getLocal("sampleSiteId")
        : "",
      inputVisible: false,
      inputValue: "",
      newSourceEnumData: {},
      baseSetInfo: {
        hotwords: [],
        newsSource: "1",
        printDisplay: "20",
      },
      siteApps: [], // 站点应用列表
      showApps: [], // 终端显示应用列表
      showAddApp: false,
      isEdit: false, // 是否是编辑应用
      form: {
        appId: [], // 应用id
        order: 0, // 排序
      },
      rules: {
        appId: [{ required: true, message: "请选择应用", trigger: "change" }],
      },
    };
  },
  computed: {
    selectOptions() {
      return this.siteApps.filter((item) => {
        return !this.showApps.some((v) => v.appId === item.id);
      });
    },
  },
  created() {
    this.getBaseSetInfo();
    this.getSiteAppList();
    this.getAppList();
  },
  methods: {
    // 获取基础设置
    async getBaseSetInfo() {
      let res = await getBaseSetInfo({
        siteId: this.siteId,
      });
      if (res.data.code === 1) {
        this.newSourceEnumData = res.data.dict.newsSource;
        if (res.data.data.data.length > 0) {
          this.baseSetInfo.hotwords = res.data.data.data[0].hotwordList
            .filter((v) => v.hotwords)
            .slice(0, 10);
          this.baseSetInfo.printDisplay = res.data.data.data[0].printDisplay;
          this.baseSetInfo.newsSource = res.data.data.data[0].newsSource + "";
        }
      }
    },
    // 获取站点应用
    async getSiteAppList() {
      let res = await getSiteAppList({
        page: 1,
        size: -1,
        type: 1, // 终端应用
        siteId: this.siteId,
      });
      if (res.data.code === 1) {
        let { data } = res.data.data;
        this.siteApps = data;
      }
    },

    // 获取填单应用
    async getAppList() {
      let res = await getAppList({
        page: 1,
        size: -1,
      });
      if (res.data.code === 1) {
        let { data } = res.data.data;
        this.showApps = data.sort((a, b) => {
          return a.order - b.order;
        });
      }
    },
    // 重置添加app表单
    resetAddApp() {
      this.$refs.form.resetFields();
    },

    // 打开站点应用弹窗
    openSiteApp() {
      if (this.showApps.length >= 4) {
        this.$message.warning("最多添加4个应用！");
        return;
      }
      Object.assign(this.form, this.$options.data().form);
      this.form.id && this.$delete(this.form, "id");
      this.isEdit = false;
      this.showAddApp = true;
    },
    // 关闭站点应用弹窗
    closeSiteApp() {
      this.resetAddApp();
      this.showAddApp = false;
    },

    // 编辑应用
    handleEditApp(row) {
      this.showAddApp = true;
      setTimeout(() => {
        this.form = { ...row, appId: [row.appId], order: row.order ?? 0 };
        this.isEdit = true;
      }, 10);
    },

    // 保存终端应用
    saveApp() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // let curApp = this.siteApps.find((item) => {
          //   return item.id === this.form.appId;
          // });
          if (
            !this.isEdit &&
            this.showApps.length + this.form.appId.length > 4
          ) {
            this.$message.warning("最多添加4个应用！");
            return;
          }
          let appList = this.siteApps.filter((item) => {
            return this.form.appId.some((v) => v === item.id);
          });
          let curApp = appList.map((v) => {
            let obj = {
              siteId: this.siteId,
              appName: v.appName,
              appId: v.id,
              appCode: v.appCode,
              order: this.form.order,
            };
            if (this.form.id) {
              obj.id = this.form.id;
            }
            return obj;
          });
          // let obj = {
          //   siteId: this.siteId,
          //   appName: curApp.appName,
          //   appId: this.form.appId,
          //   appCode: curApp.appCode,
          //   order: this.form.order,
          // };
          // if (this.form.id) {
          //   obj.id = this.form.id;
          // }
          let res = await batchSaveApp(curApp);
          let { code } = res.data;
          if (code === 1) {
            this.$message.success("保存成功");
            this.getAppList();
            this.closeSiteApp();
          }
        }
      });
    },

    // 删除终端应用
    handleCloseApp(id) {
      this.$confirm("确定要删除吗？", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        cancelButtonClass: "btn-custom-cancel",
        type: "warning",
      }).then(async () => {
        let res = await delApp({ id });
        let { code, msg } = res.data;
        if (code === 1) {
          this.$message.success(msg);
          this.getAppList();
        }
      });
    },
    handleClose(tag) {
      //删除当前词汇
      this.baseSetInfo.hotwords = this.baseSetInfo.hotwords.filter(
        (i) => i.hotwords != tag
      );
    },

    showInput() {
      if (this.baseSetInfo.hotwords.length >= 10) {
        this.$message.warning("最多添加10个热门词汇！");
        return;
      }
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue.replaceAll(" ", "");
      if (inputValue) {
        let list = this.baseSetInfo.hotwords.filter(
          (i) => i.hotwords === inputValue
        );

        if (list.length == 0) {
          let obj = {};
          obj.hotwords = inputValue;
          obj.siteId = this.siteId;
          obj.searchCount = 0;
          obj.wordsSource = 1;
          this.baseSetInfo.hotwords.push(obj);
        }
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 确定
    async handleOk() {
      let res = await saveBaseSet({
        ...this.baseSetInfo,
        hotwordList: this.baseSetInfo.hotwords,
        siteId: this.siteId,
      });
      let { code, msg } = res.data;
      if (code === 1) {
        this.$message.success(msg);
      } else {
        this.getBaseSetInfo();
      }

      //保存热门词汇
    },
    // 重置
    handleReset() {
      this.baseSetInfo.hotwords = [];
      this.baseSetInfo.printDisplay = "";
    },
  },
};
</script>

<style lang="less" scoped>
.basics-set {
  width: 100%;
  height: 100%;
  .title {
    font-size: 15px;
    color: #000;
  }
}

.header {
  .tips {
    font-size: 14px;
    color: #999;
  }
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.el-tag {
  cursor: default;
}

:deep(.el-input__suffix) {
  display: flex;
  justify-content: center;
  align-items: center;
}
:deep(.el-select) {
  width: 100%;
}
</style>
