<template>
  <div class="app-container">
<!--    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">-->
<!--      <el-form-item label="标签名称" prop="titile">-->
<!--        <el-input-->
<!--          v-model="queryParams.titile"-->
<!--          placeholder="请输入标签名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="标签状态" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.sys_normal_disable"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </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="['system:scriptTemplate:add']"
        >添加一级话术</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="scriptName" label="话术名称" width="120"></el-table-column>
      <el-table-column prop="titile" label="话术标题" width="150"></el-table-column>
      <el-table-column prop="content" label="话术内容" width="260"></el-table-column>
<!--      <el-table-column label="类型" align="center" prop="tagType" >-->
<!--        <template slot-scope="scope">-->
<!--          <span v-show="scope.row.tagType == 1">小程序标签</span>-->
<!--          <span v-show="scope.row.tagType == 2">外部标签</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="tagNames" label="小程序标签" width="260"></el-table-column>
      <el-table-column prop="companyTagNames" label="外部标签标签" width="260"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.parentId == 0"
                     size="mini"
                     type="text"
                     icon="el-icon-plus"
                     @click="handleAdd(scope.row)"
                     v-hasPermi="['system:scriptTemplate:add']"
          >添加二级话术</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:scriptTemplate:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:scriptTemplate:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改标签对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0 && !topAdd">
            <el-form-item label="上级话术" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级话术" disabled="disabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-if="topAdd">
            <el-form-item label="话术名称" prop="scriptName">
              <el-input v-model="form.scriptName" placeholder="请输入话术名称" maxlength="50" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!topAdd">
            <el-form-item label="话术标题" prop="titile">
              <el-input v-model="form.titile" placeholder="请输入话术标题" maxlength="50" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="24"  v-if="!topAdd">
            <el-form-item label="话术内容" prop="content">
              <el-input v-model="form.content" type="textarea" placeholder="请输入话术内容" maxlength="500" show-word-limit/>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24"  v-if="!topAdd">-->
<!--            <el-form-item label="标签类型" prop="tagType">-->
<!--              <el-select v-model="form.tagType" >-->
<!--                <el-option label="小程序标签" :value="1" :key="1"></el-option>-->
<!--                <el-option label="外部标签" :value="2" :key="2"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24" v-if="!topAdd">
            <el-form-item label="小程序标签" prop="tagIdArray" label-width="90px">
              <treeselect v-model="form.tagIdArray" :options="chatTagOptions" :multiple="true" :show-count="true" placeholder="请选择小程序标签" :disable-branch-nodes="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!topAdd">
            <el-form-item label="外部标签" prop="companyIdArray" >
              <treeselect v-model="form.companyIdArray" :options="tagOptions" :multiple="true" :show-count="true" placeholder="请选择外部标签" :disable-branch-nodes="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24"  v-if="!topAdd">
            <el-form-item label="跳转类型" prop="type">
              <el-select v-model="form.type">
                <el-option label="无跳转" :value="0" :key="0"></el-option>
                <el-option label="跳转内部链接" :value="1" :key="1"></el-option>
                <el-option label="跳转小程序" :value="4" :key="4"></el-option>
                <el-option label="跳转外部链接" :value="3" :key="3"></el-option>
                <el-option label="导向视频号" :value="5" :key="5"></el-option>
                <el-option label="导向视频号直播间" :value="6" :key="6"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if=" form.type == 1">
            <el-form-item label="内部链接" prop="link">
              <el-input v-model="form.link" placeholder="请输入内部链接" />
            </el-form-item>
          </el-col>
          <el-col :span="24"  v-if=" form.type == 1">
            <el-form-item label="跳转参数" prop="linkParams">
              <el-input v-model="form.linkParams"  placeholder="请输入跳转参数" />
            </el-form-item>
          </el-col>
          <el-col :span="24"  v-if=" form.type == 3">
            <el-form-item label="外部链接" prop="link">
              <el-input v-model="form.link"  placeholder="请输入外部链接" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if=" form.type == 4">
            <el-form-item label="APPID" prop="redirectAppid">
              <el-input v-model="form.redirectAppid" placeholder="请输入小程序APPID" />
            </el-form-item>
          </el-col>
          <el-col :span="24"  v-if=" form.type == 4" label-width="90px">
            <el-form-item label="小程序页面" prop="redirectUrl">
              <el-input v-model="form.redirectUrl"  placeholder="请输入小程序页面" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if=" form.type == 5 || form.type == 6">
            <el-form-item label="视频号ID" prop="videoNo">
              <el-input v-model="form.videoNo" placeholder="请输入视频号ID" />
            </el-form-item>
          </el-col>
          <el-col :span="24"  v-if=" form.type == 5" label-width="90px">
            <el-form-item label="feedId" prop="feedId">
              <el-input v-model="form.feedId"  placeholder="请输入视频号feedId" />
            </el-form-item>
          </el-col>
        </el-row>
      </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>
</template>

<script>
// import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/wechatTab";
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/system/scriptTemplate";
import { tagTreeSelect } from "@/api/system/wechatTab";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {left, right} from "core-js/internals/array-reduce";

export default {
  name: "Dept",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data() {
    return {
      topAdd: true,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      treeList: [],
      // 表格树数据
      deptList: [],
      // 标签树选项
      deptOptions: [],
      tagOptions: [],
      chatTagOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        titile: undefined,
        status: undefined
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        titile: [
          { required: true, message: "话术标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "话术内容不能为空", trigger: "blur" }
        ],
        scriptName: [
          { required: true, message: "话术名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "标签类型不能为空", trigger: "blur" }
        ],
        link: [
          { required: true, message: "跳转链接不能为空", trigger: "blur" }
        ],
        linkParams: [
          { required: true, message: "跳转链接参数不能为空", trigger: "blur" }
        ],
        redirectAppid: [
          { required: true, message: "小程序appid不能为空", trigger: "blur" }
        ],
        redirectUrl: [
          { required: true, message: "小程序页面不能为空", trigger: "blur" }
        ],
        videoNo: [
          { required: true, message: "视频号ID不能为空", trigger: "blur" }
        ],
        feedId: [
          { required: true, message: "视频号feedId不能为空", trigger: "blur" }
        ],

        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    right,
    left,
    /** 查询标签列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.deptList = this.handleTree(response.data, "id");
        this.deptOptions = this.deptList;
        this.loading = false;
      });
    },
    // tagChange(){
    //   if (this.form.id) {
    //     // this.form.tagIdArray = [];
    //   } else {
    //     // this.form.tagIdArray = [];
    //   }
    // },
    /** 转换标签数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.scriptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        titile: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
        type: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.id;
        if (row.id) {
          this.topAdd = false;
          this.title = "添加二级话术";
          // this.form.type = 0;
        } else {
          this.topAdd = true;
          this.title = "添加一级话术";
        }
      }
      this.open = true;
      listTemplate().then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(row.parentId == 0) {
        this.topAdd = true;
      } else {
        this.topAdd = false;
      }
      this.reset();
      getTemplate(row.id).then(response => {
        this.form = response.data;
        // if (this.form.tagIds) {
        //   this.form.tagIdArray = this.form.tagIds.split(',');
        //   console.log('结果是==>',this.form.tagIdArray)
        // }
        this.open = true;
        this.title = "修改话术";
      });
      // listDeptExcludeChild(row.id).then(response => {
      //   this.deptOptions = this.handleTree(response.data, "id");
      // });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      tagTreeSelect({type: 2}).then(response => {
        this.tagOptions = response.data;
      });
      tagTreeSelect({type: 1}).then(response => {
        this.chatTagOptions = response.data;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let tip;
      let title;
      if(row.titile == null) {
        tip = row.scriptName
        title = '话术标题';
      } else {
        tip = row.titile
        title = '话术名称';
      }

      this.$modal.confirm('是否确认删除' + title + '为"' + tip + '"的数据项？').then(function() {
        return delTemplate(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
