<template>
  <el-dialog :visible.sync="visible" title="标签绑定管理" width="1000px"
   @close="handleClose"
   append-to-body
  >
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="企微公司" prop="corpId">
          <el-select v-model="queryParams.corpId" placeholder="企微公司"  size="small" @change="updateCorpId()">
            <el-option
              v-for="dict in myQwCompanyList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="视频ID" prop="videoId">
          <el-input
            v-model="queryParams.videoId"
            placeholder="请输入视频ID"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            disabled
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['shop:tag:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['shop:tag:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['shop:tag:remove']"
          >删除</el-button>
        </el-col>
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="el-icon-download"-->
<!--            size="mini"-->
<!--            :loading="exportLoading"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['shop:tag:export']"-->
<!--          >导出</el-button>-->
<!--        </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="tagList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="企微公司" align="center" prop="corpId" />
        <el-table-column label="视频ID" align="center" prop="videoId" />
        <el-table-column label="看课中-标签组名" align="center" prop="watchingGroupName" />
        <el-table-column label="看课中-标签名" align="center" prop="watchingTgName" />
        <el-table-column label="完课-标签组名" align="center" prop="watchedGroupName" />
        <el-table-column label="完课-标签名" align="center" prop="watchedTgName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['shop:tag:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['shop:tag:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改视频小节看课标签关联对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="企微公司" prop="corpId">
            <el-select v-model="queryParams.corpId" placeholder="企微公司"  size="small" @change="updateCorpId()">
              <el-option
                v-for="dict in myQwCompanyList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="视频ID" prop="videoId">
            <el-input v-model="form.videoId" placeholder="请输入视频ID" disabled/>
          </el-form-item>
          <el-form-item label="看课中-标签组" prop="watchingGroupTgId">
            <el-select
              v-model="form.watchingGroupTgId"
              placeholder="请选择标签组"
              @change="onWatchingGroupChange"
              filterable
            >
              <el-option
                v-for="group in tagGroups"
                :key="group.groupId"
                :label="group.name"
                :value="group.groupId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="看课中-标签" prop="watchingTagId">
            <el-select
              v-model="form.watchingTagId"
              placeholder="请选择看课标签"
              @change="onWatchingTagChange"
              filterable>
              <el-option
                v-for="tag in watchingTagsInGroup"
                :key="tag.tagId"
                :label="tag.name"
                :value="tag.tagId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="完课-标签组" prop="watchedGroupTgId">
            <el-select
              v-model="form.watchedGroupTgId"
              placeholder="请选择标签组"
              @change="onWatchedGroupChange"
              filterable>
              <el-option
                v-for="group in tagGroups"
                :key="group.groupId"
                :label="group.name"
                :value="group.groupId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="完课-标签" prop="watchedTagId">
            <el-select
              v-model="form.watchedTagId"
              placeholder="请选择看课标签"
              @change="onWatchedTagChange"
              filterable>
              <el-option
                v-for="tag in watchedTagsInGroup"
                :key="tag.tagId"
                :label="tag.name"
                :value="tag.tagId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script>
import {addTag, delTag, exportTag, getTag, listTag, updateTag} from "@/api/tag/api";
import {getMyQwCompanyList} from "@/api/qw/user";
import {listTagGroup} from "@/api/qw/tagGroup";

export default {
  name: 'BindLabelsDialog',
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    videoId: {
      type: String,
      required: true,
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.queryParams.videoId = this.videoId;
        this.getList();
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频小节看课标签关联表格数据
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      myQwCompanyList:[],
      // 看课中标签组
      watchingTagsInGroup: [],
      // 完课标签组
      watchedTagsInGroup: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        corpId: null,
        videoId: null,
        watchingGroupId: null,
        watchedGroupId: null,
        watchingTgId: null,
        watchedTgId: null,
        watchingGroupTagId: null,
        watchedGroupTagId: null,
        watchingTagId: null,
        watchedTagId: null,
      },
      tagList: [],
      totalTags: 0,
      pageNum: 1,
      pageSize: 10,
      loadingList: false,
      selection: [],
      formDialogVisible: false,
      isEditing: false,
      form: {
        id: null,
        corpId: null,
        videoId: null,
        watchingGroupId: null,
        watchedGroupId: null,
        watchingTgId:null,
        watchedTgId: null,
        watchingGroupTagId: null,
        watchedGroupTagId: null,
        watchingTagId: null,
        watchedTagId:null
      },
      rules: {
        corpId: [{ required: true, message: '请选择企微公司', trigger: 'change' }],
        videoId: [{ required: true, message: '请输入视频ID', trigger: 'blur' }],
        watchingGroupTgId: [{ required: true, message: '请选择看课中标签组', trigger: 'change' }],
        watchingTagId: [{ required: true, message: '请选择看课中标签', trigger: 'change' }],
        watchedGroupTgId: [{ required: true, message: '请选择完课标签组', trigger: 'change' }],
        watchedTagId: [{ required: true, message: '请选择完课标签', trigger: 'change' }]
      },
      tagGroups: []
    }
  },
  created() {
    getMyQwCompanyList().then(response => {
      this.myQwCompanyList = response.data;
      if(this.myQwCompanyList != null && this.myQwCompanyList.length > 0){
        this.queryParams.corpId = this.myQwCompanyList[0].dictValue;
        this.getList();
      }
    });
  },
  methods: {
    onWatchingTagChange(tagId){
      let find = this.watchingTagsInGroup.find(e=> e.tagId === tagId);
      this.form.watchingTgId = find.id;
    },
    onWatchedTagChange(tagId){
      let find = this.watchedTagsInGroup.find(e=> e.tagId === tagId);
      this.form.watchedTgId = find.id;
    },
    onWatchingGroupChange(groupId){
      let find = this.tagGroups.find(e=> e.groupId===groupId);
      this.watchingTagsInGroup=find.tag || [];
      this.form.watchingGroupId = find.id;
    },
    onWatchedGroupChange(groupId){
      let find = this.tagGroups.find(e=> e.groupId===groupId);
      this.watchedTagsInGroup=find.tag || [];
      this.form.watchedGroupId = find.id;
    },
    updateCorpId(){
      this.getList();
      // 查询所有的标签组
      listTagGroup({
        pageNum: 1,
        pageSize: 1000,
        corpId: this.queryParams.corpId
      }).then((res) => {
        if(res.code === 200) {
          this.tagGroups = res.rows;
        }
      });
    },
    handleClose(){
      this.$emit('update:visible', false);
    },
    /** 查询视频小节看课标签关联列表 */
    getList() {
      this.loading = true;
      listTag(this.queryParams).then(response => {
        this.tagList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$emit('close')
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        corpId: null,
        videoId: null,
        watchingGroupId: null,
        watchedGroupId: null,
        watchingTgId: null,
        watchedTgId: null,
        watchingGroupTagId: null,
        watchedGroupTagId: null,
        watchingTagId: null,
        watchedTagId: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加视频小节看课标签关联";
      this.form.videoId = this.videoId;
      this.form.corpId = this.queryParams.corpId;

      listTagGroup({
        pageNum: 1,
        pageSize: 1000,
        corpId: this.queryParams.corpId
      }).then((res) => {
        if(res.code === 200) {
          this.tagGroups = res.rows;
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      // 先加载标签组数据
      listTagGroup({
        pageNum: 1,
        pageSize: 1000,
        corpId: this.queryParams.corpId
      }).then((res) => {
        if(res.code === 200) {
          this.tagGroups = res.rows;

          // 再获取详情数据
          getTag(id).then(response => {
            this.form = response.data;

            // 根据标签组ID加载对应的标签列表
            if(this.form.watchingGroupTgId) {
              let watchingGroup = this.tagGroups.find(e => e.id === this.form.watchingGroupId);
              if(watchingGroup) {
                this.watchingTagsInGroup = watchingGroup.tag || [];
              }
            }

            if(this.form.watchedGroupTgId) {
              let watchedGroup = this.tagGroups.find(e => e.id === this.form.watchedGroupId);
              if(watchedGroup) {
                this.watchedTagsInGroup = watchedGroup.tag || [];
              }
            }

            this.open = true;
            this.title = "修改视频小节看课标签关联";
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTag(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTag(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除视频小节看课标签关联编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delTag(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有视频小节看课标签关联数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportTag(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
}
</script>
