<!-- 运营管理 定制频道-->

<template>
  <div class="app-container">
    <!-- 新增 -->
    <el-button
      type="primary"
      icon="el-icon-plus"
      size="mini"
      @click="getDialog('新增')"
      v-hasPermi="['operation:channel:add']"
    >
      新增频道配置
    </el-button>
    <!-- 列表 -->
    <el-table :data="tableData" v-loading="loading">
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="频道配置名称" prop="name" align="center" />
      <el-table-column
        label="部署形式"
        prop="type"
        align="center"
        :formatter="typeFormatter"
      />
      <el-table-column
        label="设备"
        prop="deviceIds"
        align="center"
        :formatter="devFormatter"
        show-overflow-tooltip
      />

      <!-- <el-table-column label="序号" align="center">
        <template slot-scope="scope">
          <div v-if="editData.currentEditIndex !== scope.$index">
            <span style="margin-right: 8px">
              {{ scope.row.indexNum }}
              <!-- {{ scope.$index + 1 }} -->
              <!-- {{ scope.row.sort || "" }} -->
            </span>
            <svg-icon
              icon-class="edit"
              @click.native="handleEditClick(scope.row, scope.$index)"
            />
          </div>
          <el-input
            v-else
            v-model="scope.row.indexNum"
            size="mini"
            style="width: 60px"
            type="number"
            @blur="onNumberBlur(scope.row, scope.$index)"
            @keyup.enter.native="onNumberBlurEnter(scope.row, scope.$index)"
            placeholder="序号"
            ref="numberInput"
          />
        </template>
      </el-table-column> -->

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="getDialog('查看', scope.row, scope.$index, true)"
            >查看</el-button
          >
          <el-button
            type="text"
            @click="getDialog('编辑', scope.row, scope.$index)"
            v-hasPermi="['operation:channel:edit']"
            >编辑</el-button
          >
          <el-button
            v-if="scope.$index !== 0"
            type="delete"
            @click="getDelete(scope.row)"
            v-hasPermi="['operation:channel:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="title"
      width="950px"
      :before-close="cancel"
    >
      <el-form label-width="auto">
        <el-form-item
          v-if="index !== 1"
          label="频道配置名称："
          style="width: 300px"
        >
          <el-input
            v-model="dialogForm.name"
            placeholder="请输入规则名称"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item v-if="index !== 1" label="关联设备：">
          <el-select
            v-model="ids"
            filterable
            multiple
            placeholder="请选择关联设备"
            :disabled="disabled"
          >
            <el-option
              v-for="item in devOptions"
              :key="item.clientTypeId"
              :value="item.clientTypeId.toString()"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="title !== '新增'"
          label="内容列表："
          style="height: 500px; overflow-y: auto"
        >
          <el-table
            :data="list"
            v-loading="dialog_loading"
            lazy
            :default-sort="{ prop: 'sort' }"
          >
            <el-table-column
              label="序号"
              prop="sort"
              align="center"
              width="100px"
            />
            <el-table-column
              label="频道数"
              prop="channelId"
              align="center"
              width="100px"
            />
            <el-table-column
              label="频道名称"
              prop="aliasName"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column label="频道封面" align="center" width="100px">
              <template slot-scope="scope">
                <el-image :src="scope.row.pic"></el-image>
              </template>
            </el-table-column>
            <el-table-column
              label="频道简介"
              prop="description"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="edit(scope, true)"
                  >查看</el-button
                >
                <el-button type="text" @click="edit(scope)" :disabled="disabled"
                  >编辑</el-button
                >
                <el-button
                  v-if="scope.row.sort > 3"
                  type="text"
                  icon="el-icon-caret-top"
                  @click="getChange(scope.row.id, scope.row.sort - 1)"
                  :disabled="disabled"
                />
                <el-button
                  v-if="scope.row.sort > 2 && scope.row.sort < 12"
                  type="text"
                  icon="el-icon-caret-bottom"
                  @click="getChange(scope.row.id, scope.row.sort + 1)"
                  :disabled="disabled"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" v-if="index !== 1">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="getSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
change,
channelPage,
create,
devList,
editPage,
getRemove,
page,
} from "@/api/operation/channel";
import { dialogCallBack } from "@/utils/DialogUtil";
export default {
  name: "OperationChannel",
  data() {
    return {
      editData: {
        currentEditIndex: -1,
        currentEditSort: 1,
      },
      // 遮罩层
      loading: false,
      dialog_loading: false,
      // 列表
      tableData: [],
      list: [],
      // 弹窗
      dialogVisible: false,
      title: "",
      // 设备
      devOptions: [],
      allDevOptions: [],
      // 表单
      form: {
        pageNum: 1,
        pageSize: 10,
      },
      index: 0,
      dialogForm: {},
      ids: [],
      // 频道规则Id
      obj: {},
      // 部署形式
      typeOptions: [
        {
          value: 0,
          label: "注册用户-默认",
        },
        {
          value: 1,
          label: "绑定特定设备",
        },
      ],
      // 只读
      disabled: false,
    };
  },
  watch: {
    ids(val) {
      this.dialogForm.deviceIds = val.join(",");
    },
  },
  mounted() {
    this.getDevList();
    this.getList();
  },
  methods: {
    // 列表
    getList() {
      this.loading = true;
      page(this.form).then((res) => {
        if (res.code === 0) {
          var data = res.data;
          for (var i = 0; i < data.length; i++) {
            data[i].indexNum = i + 1;
          }
          this.tableData = data;
          this.loading = false;
        }
      });
    },

    // 全部设备
    getDevList() {
      devList(1).then((res) => {
        if (res.code === 0) {
          this.allDevOptions = [];
          res.data.map((i) => {
            this.allDevOptions.push({
              value: i.clientTypeId,
              label: i.name,
            });
          });
        }
      });
    },

    // 编辑
    edit(e, boolean) {
      this.dialogVisible = false;
      this.$router.push({
        path: `/operation/channel/detail`,
        query: {
          channelId: e.row.id,
          audioType: e.row.channelType,
          index: e.$index,
          boolean: boolean,
        },
      });
    },

    // 删除
    getDelete(row) {
      var that = this;
      dialogCallBack(that, function () {
        that
          .$confirm(`是否删除${row.name}?`, "提示：", {
            type: "warning",
          })
          .then(() => {
            getRemove(row.id).then((res) => {
              if (res.code === 0) {
                that.$message.success("删除成功！");
                that.getList();
              }
            });
          });
      });
    },

    // 弹窗
    getDialog(title, row, index, boolean) {
      this.dialogVisible = true;
      this.title = title;
      this.index = index + 1;
      this.obj = row;
      this.disabled = boolean;
      // 新增 / 编辑时的设备
      devList(0).then((res) => {
        if (res.code === 0) {
          this.devOptions = res.data;
          if (this.title !== "新增") {
            this.devOptions.unshift.apply(this.devOptions, row.deviceList);
          }
        }
      });

      if (title !== "新增") {
        this.dialogForm = row;
        if (this.index !== 1) {
          this.ids = this.dialogForm.deviceIds.split(",");
        }
        this.getPage(row);
      }
    },

    // 十二频道
    getPage(row) {
      channelPage(row.id).then((res) => {
        if (res.code === 0) {
          this.list = res.data;
          this.dialog_loading = false;
        }
      });
    },

    // 创建
    getSubmit() {
      if (this.title === "编辑") {
        editPage(this.dialogForm).then((res) => {
          if (res.code === 0) {
            this.$message.success("修改成功！");
            this.dialogVisible = false;
            this.getList();
          }
        });
      } else {
        create({
          name: this.dialogForm.name,
          deviceIds: this.dialogForm.deviceIds,
          type: 1,
        }).then((res) => {
          if (res.code === 0) {
            this.$message.success("新增成功！");
            this.dialogVisible = false;
            this.getList();
          }
        });
      }
    },

    // 点击编辑图标显示输入框
    handleEditClick(row, index) {
      this.editData.currentEditIndex = index;
      this.editData.currentEditSort = row.indexNum;
      this.$nextTick(() => {
        this.$refs.numberInput.focus();
      });
    },

    onNumberBlurEnter(row, index) {
      this.editData.currentEditIndex = -1;
    },

    // 输入框失去焦点时隐藏
    onNumberBlur(row, index) {
      var newSort = row.indexNum;

      if (newSort === "") {
        row.indexNum = this.editData.currentEditSort;
        this.$message.warning("序号不能为空");
        return;
      }

      if (newSort <= 0) {
        row.indexNum = this.editData.currentEditSort;
        this.$message.warning("序号必须大于0");
        return;
      }

      if (newSort === this.editData.currentEditSort) {
        this.editData.currentEditIndex = -1;
        return;
      }

      ///删除第index个元素

      this.tableData.splice(index, 1);
      this.tableData.splice(newSort - 1, 0, row);

      for (var i = 0; i < this.tableData.length; i++) {
        this.tableData[i].indexNum = i + 1;
      }
      this.editData.currentEditIndex = -1;

      // 检查序号是否重复
      // const isDuplicate = this.tableData.some(
      //   (item, i) => i !== index && item.sortIndex === newSort
      // );

      // if (isDuplicate) {
      //   this.$message.warning("序号已存在");
      // } else {
      //   // 更新到tableData
      //   this.$set(this.tableData, index, {
      //     ...row,
      //     sortIndex: newSort,
      //   });
      //   console.log(
      //     "序号修改成功:",
      //     newSort,
      //     "row.sortIndex",
      //     row.sortIndex,
      //     "this.tableData",
      //     this.tableData[index].sortIndex
      //   );
      // 隐藏编辑框
      //   this.editData.currentEditIndex = -1;
      // }
    },

    // 排序
    getChange(id, sort) {
      change({
        id: id,
        sort: sort,
      }).then((res) => {
        if (res.code === 0) {
          this.$message.success("修改成功！");
          this.getPage(this.obj);
        }
      });
    },

    // 取消
    cancel() {
      this.dialogVisible = false;
      this.ids = [];
      this.dialogForm = {};
      this.getList();
    },

    // 字典翻译
    typeFormatter(row) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    devFormatter(row) {
      return row.deviceIds
        ? row.deviceIds
            .split(",")
            .map((i) => this.selectDictLabel(this.allDevOptions, i))
            .join(",")
        : "";
    },
  },
};
</script>
