<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="24" :xs="24" style="margin-top: 20px; margin-bottom: 20px; text-align: right;">
        <!-- <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div> -->

        <!-- </el-tab-pane> -->
        <el-button type="primary" @click="handleExport">短 信 设 置</el-button>
      </el-col>
      <el-col :span="24" :xs="24">
         <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="选择用户">
               <!-- <div>
                <el-input
                    v-model="deptName"
                    placeholder="请输入用户名称"
                    clearable
                    size="small"
                    prefix-icon="el-icon-search"
                    style="margin-bottom: 20px"
                  />
                </div> -->
                <!-- <div class="head-container" >
                  <div align="right">
                         <el-checkbox v-model="checked" @change="checkedAll"/> 全选/反选
                  </div>
                  <el-tree
                    show-checkbox
                    node-key="code"
                    :data="userList"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    ref="tree"
                    default-expand-all
                    @node-click="handleNodeClick"
                  />
                </div> -->
                <!-- <treeselect :normalizer="normalizer" :multiple="true" v-model="deptNamety" @select="djieskle" @deselect="deselect" :options="userList"  placeholder="请选择归属部门" /> -->
                  <el-select v-model="deptNamety" :multiple ="true" clearable placeholder="请选择用户" @visible-change = "visiblechange" @change="changetr" @blur="blurkde" filterable>
                     <div style="margin-left: 20px;">
                       <el-checkbox v-model="checked" @change="checkedAll"/> 全选/反选
                     </div>
                      <el-option
                        ref="tree"
                        v-for="item in userList"
                        :key="item.userId"
                        :label="item.nickName"
                        :value="item.userId">
                      </el-option>
                    </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选择模板">
                  <el-select v-model="deptNametytwo"  clearable placeholder="请选择模板" @visible-change = "visiblechange" @change="changetrtwo" @blur="blurkde" filterable>
                      <el-option
                        v-for="item in smsset"
                        :key="item.id"
                        :label="item.signName"
                        :value="item.id">
                      </el-option>
                    </el-select>
              </el-form-item>
            </el-col>
          </el-row>
           <el-row>
             <el-col :span="24">
               <el-form-item label="编辑内容" class="jeiouq">
                 <el-input v-model="form.content" type="textarea" placeholder="请输入内容" ></el-input>
               </el-form-item>
             </el-col>
           </el-row>
         </el-form>
      </el-col>
      <el-col :span="24" :xs="24">
        <div  class="dialog-footer" style="text-align: right; margin-top: 30px;">
          <el-button type="primary" @click="submitForm">发 送 短 信</el-button>

        </div>
      </el-col>
      <!--用户数据-->
        </el-row>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, exportUser, resetUserPwd, changeUserStatus, importTemplate,addPhoen,listOueng } from "@/api/system/user";
import { listSendMessage } from "@/api/system/sendMessage";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      checked:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 模板数据
      smsset:null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      deptNamety:'',
      deptNametytwo:'',
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "nickName",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],

      },
      huej:[]
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    // this.getTreeselect();
    this.getListsms()
    // this.getDicts("sys_normal_disable").then(response => {
    //   this.statusOptions = response.data;
    // });
    // this.getDicts("sys_user_sex").then(response => {
    //   this.sexOptions = response.data;
    // });
    // this.getConfigKey("sys.user.initPassword").then(response => {
    //   this.initPassword = response.msg;
    // });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listOueng(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          // this.userList = this.handleTree(response.rows, "id");
          this.total = response.total;
          this.loading = false;
          // console.log(this.userList)
          //
        }
      );
    },
    /** 查询模板列表 */
    getListsms() {
     this.loading = true;
     listSendMessage(this.queryParams).then(response => {
       this.smsset = response.rows;
       // this.total = response.total;
       this.loading = false;
     });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    checkedAll(){
      let juegf = []
            if (this.checked) {
              for(var i = 0 ; i < this.userList.length; i++ ){
                juegf.push(this.userList[i].userId)
                console.log(juegf)
              }
              this.deptNamety = juegf
              this.form.userList = this.userList
                //全选
                // this.$refs.tree.setCheckedNodes(this.userList);
                console.log(this.userList)
            }else{
                //取消选中
                this.deptNamety = ''
                this.form.userList = []
                // this.$refs.tree.setCheckedKeys([]);
            }
    },
    // 筛选节点
    filterNode(value, data) {
      // console.log(value,data)
      if (!value) return true;
      return data.nickName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      // this.queryParams.deptId = data.id;
      // this.getList();
      console.log(data)
    },
    // 下拉框出现/隐藏时触发
    visiblechange(val){
     console.log(val)
    },
    djieskle(node, instanceId) {
      // this.personnel(node.id);
     // let huej = []
      this.huej.push(node)
      this.form.userList = this.huej
      console.log(node, instanceId);
      console.log(this.form.userList);
    },
    deselect(node, instanceId){
      if(this.form.userList !== undefined){
        for (let i = this.form.userList.length - 1; i >= 0; i--) {
          if (this.form.userList[i].userId == node.userId) {
            this.form.userList.splice(i, 1);
          }
        }
      }
      console.log(this.form.userList);
     console.log(node, instanceId);
    },

    changetr(val){
      console.log(this.deptNamety)
      let name = []
      let huej = []
      name = val
      // for(var i = 0 ; i <this.userList.length; i++ ){
      //   if(this.userList[i].userId == name[i]){

      //   }
      // }
      var flag;
      for (var i in name) {
        flag = true;
        for (var j in this.userList) {
          if (this.userList[j].userId == name[i]) {
            // flag = false;
            huej.push(this.userList[j])
            // break;
          }
        }
        // if (flag) {
        //   this.userList.push(name[i]);
        // }
      }
      this.form.userList = huej
      if(this.form.userList.length == 0){
        this.form.userList == undefined
      }
      // this.userList
      console.log(val)
      console.log(huej)
    },
    normalizer(node) {
      // if (node.children && !node.children.length) {
      //   delete node.children;
      // }
      return {
        id: node.userId,
        label: node.nickName,
      };
    },
    changetrtwo(val){
      console.log(val)
      this.form.textMessageId = val
    },
    blurkde(val){
     // console.log(val)
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeUserStatus(row.userId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      getUser().then(response => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            this.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function() {
      if(this.form.userList == undefined){
        this.msgSuccess("请选择用户");
        return  false
      }

      if(this.form.textMessageId == undefined){
        this.msgSuccess("请选择短信模板");
        return  false
      }


      if(this.form.content == undefined){
        this.msgSuccess("请输入短信内容");
        return  false
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
            addPhoen(this.form).then(response => {
              if(response.data =='发送失败的人' || response.data == undefined){
                this.msgSuccess('操作成功');
              }else{
                this.msgSuccess(response.data);
              }

              this.open = false;
              // this.getList();
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(userIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$router.push({
        path: '../../phone/smsstee',
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style lang="scss">
  .jeiouq{
    .el-textarea__inner{
      height: 200px ;
    }
  }
  .el-tag.el-tag--info{
    color: #333;
  }
  .el-select{
    width: 100%;
  }
</style>
