<template>
  <div>
    <d2-container>
      <!-- <template slot="header">首页/数据查询</template> -->
      <div class="main">
        <div class="zt_right">
          <!-- <template slot="header">首页/数据查询</template> -->
          <div class="nav">当前所在位置:首页>用户管理</div>
          <div class="right_main">
            <div class="right_title">
              <i class="fa fa-bar-chart" aria-hidden="true" style="padding-right: 5px"></i>
              用户管理
            </div>
            <div class="right_table">
              <el-form :inline="true" :model="formInline" class="demo-form-inline" id="formLabel">
                <div class="float-left">
                  <!-- <el-form-item label="直属库名称">
                    <el-select v-model="formInline.orgId" placeholder="请选择">
                      <el-option v-for="item in ckLists" :key="item.id" :label="item.orgName" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item> -->

                  <!-- <el-form-item label="角色名称">
                      <el-select v-model="formInline.userRole" placeholder="请选择">
                    <el-option
                      v-for="item in roleLists"
                      :key="item.enumCode"
                      :label="item.enumName"
                      :value="item.enumCode"
                    >
                    </el-option>
                      </el-select>
                  </el-form-item> -->
                  <el-form-item label="角色名称">
                    <el-select v-model="formInline.userRole" placeholder="请选择角色">
                      <el-option v-for="item in roleLists" :key="item.enumCode" :label="item.enumName" :value="item.enumCode">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="姓名">
                    <el-input placeholder="请输入" v-model="formInline.userName"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-refresh-left" @click="reset">重置</el-button>
                  </el-form-item>
                </div>
                <div class="float-right">
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-plus" @click="addClick(1)">新建用户</el-button>
                  </el-form-item>
                </div>
              </el-form>
              <el-table :data="userList" ref="dataTreeList" style="width: 100%" :header-cell-style="{ background: '#0064b9', color: '#c9f5fa' }" row-key="id" border :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }">
                <el-table-column align="center" label="序号" type="index" width="100px" :index="indexMethod" show-overflow-tooltip></el-table-column>
                <el-table-column prop="userId" label="用户ID" align="center">
                </el-table-column>
                <el-table-column prop="userName" label="姓名" align="center">
                </el-table-column>

                <el-table-column prop="userRoleName" label="角色" align="center">
                </el-table-column>
                <el-table-column prop="orgName" label="所属仓库" align="center">
                </el-table-column>
                <el-table-column prop="manageStoreName" label="管理仓房" align="center">
                </el-table-column>
                <el-table-column prop="userPhone" label="联系方式" align="center">
                </el-table-column>
                </el-table-column>
                <el-table-column prop="userState" label="用户状态" align="center">
                  <template slot-scope="scope">
                    <div v-if="scope.row.userState=='1'">
                      <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:green"></span>
                      <span>启用</span>

                    </div>
                    <div v-if="scope.row.userState=='0'">
                      <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:red"></span>
                      <span>停用</span>
                    </div>
                  </template>
                </el-table-column>
                </el-table-column>
                <!-- <el-table-column prop="buildTime" label="创建时间" align="center" width="180px;">
                </el-table-column> -->
                <el-table-column fixed="right" label="操作" width="300" align="center">
                  <template slot-scope="scope">
                    <el-button @click="edit(scope.row,2)" type="editbtn" class="fa fa-edit" size="mini">编辑</el-button>
                    <el-button @click="deleted(scope.row)" type="delebtn" class="fa fa-remove" size="mini">删除</el-button>

                    <!-- <el-switch
                    id="switchBtn"
                    style="margin-left:10px;"
                      v-model="scope.row.userState"
                      :active-value="'1'"
                      active-text="启用"
                      :inactive-value="'0'"
                      inactive-text="禁用"
                     
                    >
                    </el-switch> -->
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="1" :page-sizes="[10, 20, 30, 40]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
      <!-- //用户弹框 -->
      <el-dialog :title="title" :visible.sync="userDialog" id="dialogStyle" :rules="rules">
        <el-form :model="form" :rules="rules" ref="formData">
          <!-- <el-form-item label="用户ID" :label-width="formLabelWidth" prop="userId">
            <el-input v-model="form.userId" autocomplete="off"></el-input>
          </el-form-item> -->
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="userName">
            <el-input v-model="form.userName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth" prop="userRole">
            <el-select v-model="form.userRole" placeholder="请选择角色">
              <el-option v-for="item in roleLists" :key="item.enumCode" :label="item.enumName" :value="item.enumCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属仓库" :label-width="formLabelWidth" prop="orgId">
            <el-select v-model="form.orgId" placeholder="请选择" @change="ckChange">
              <el-option v-for="item in ckLists" :key="item.id" :label="item.orgName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="管理仓房" :label-width="formLabelWidth" prop="manageStore">
            <el-select v-model="form.manageStore" placeholder="请选择">
              <el-option v-for="item in cfLists" :key="item.id" :label="item.orgName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系方式" :label-width="formLabelWidth" prop="userPhone">
            <el-input v-model="form.userPhone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="userPassword">
            <el-input v-model="form.userPassword" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户状态:" :label-width="formLabelWidth" id="switchLabel">
            <el-switch v-model="form.userState" active-text="启用" inactive-text="禁用"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="quxiao()">取 消</el-button>
          <el-button type="primary" @click="defined('formData')">确 定</el-button>
        </div>
      </el-dialog>
    </d2-container>
  </div>
</template>
<script>
import api from "@/api";
export default {
  name: "userManagement",
  data() {
    let checkPhone=(rule,value,callback)=>{
      if(!value){
        return callback(new Error("手机号不能为空"));

      }else{
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        if(reg.test(value)){
          callback();
        }else{
          return callback(new Error("请输入正确的手机号"))
        }
      }
    }
    return {
      //编辑接口携带每行的id
      rowId: null,
      btnType: null,
      // 弹框标题初始化
      title: "",
      options: [],
      roleOptions: [],
      //验证规则
      rules: {
        userId: [{ required: true, message: "请输入用户ID", trigger: "blur" }],
        userName: [
          { required: true, message: "请输入用户姓名", trigger: "blur" },
        ],
        userPassword: [
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        userRole: [
          { required: true, message: "请选择用户角色", trigger: "blur" },
        ],
        orgId: [
          { required: true, message: "请选择所属仓库", trigger: "blur" },
        ],
        manageStore: [
          { required: true, message: "请选择管理仓房", trigger: "blur" },
        ],
        // userPhone: [
        //   { required: true, message: "请输入联系方式", trigger: "blur" },
        // ],
         userPhone: [
          {validator:checkPhone, trigger: "blur" },
        ],
      },

      orgName: null,
      userRoleName: null,
      manageStoreName: null,

      //弹框值初始化
      form: {
        userId: "",
        userName: "",
        userRole: "",
        orgId: "",
        manageStore: "",
        userPhone: "",
        userState: true,
        userPassword: "",
      },

      //查询条件
      formInline: {
        orgId: "",
        userRole: "",
        userName: "",
      },
      // 新增时角色下拉菜单
      roleLists: [],
      // 新增时仓库下拉菜单
      ckLists: [],
      // 新增时仓房下拉菜单
      cfLists: [],
      //新增时管理仓房所传参数
      parentId: null,
      // 表格字段
      userList: [],

      userDialog: false,
      formLabelWidth: "120px",

      pagination: {
        // 每页显示的条数
        pageSize: 10,
        // 当前页
        curPage: 1,
        // 总数
        total: 20,
      },
    };
  },

  mounted() {
    this.getList();
    this.ckList();
    setTimeout(() => {
      this.roleList();
    }, 100);
  },
  methods: {
    //获取列表数据
    getList() {
      console.log("....");
      var condition = {
        orgId: this.formInline.orgId,
        userRole: this.formInline.userRole,
        userName: this.formInline.userName,
      };
      condition = JSON.stringify(condition);
      var data = {
        pageIndex: this.pagination.curPage,
        pageSize: this.pagination.pageSize,
        condition: condition,
      };
      api
        .userList(data)
        .then((res) => {
          if (res.code == 200) {
            this.userList = res.data.records;
            this.pagination.pageSize = res.data.size;
            this.pagination.total = res.data.total;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //新增时角色下拉选

    roleList() {
      var condition = {
        enumName: "",
        enumCode: 210000,
      };
      condition = JSON.stringify(condition);
      var data = {
        condition: condition,
      };
      api
        .dataDic(data)
        .then((res) => {
          if (res.code == 200) {
            //  this.roleLists = res.data;
            res.data.forEach((ele) => {
              if (ele.enumCode === "210000") {
                console.log(ele, "ele.enumCode");
                this.roleLists = ele.children;
                console.log(this.roleLists, "this.roleLists");
              }
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //新增或编辑时仓房/仓库下拉选
    ckList() {
      var data = {
        storeTypeCode: 300002,
      };

      api
        .ckList(data)
        .then((res) => {
          if (res.code == 200) {
            var that = this;
            // this.ckLists = res.data;
            that.ckLists = res.data;
            console.log(this.ckLists, "....");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    cfList() {
      var data = {
        parentId: this.form.orgId,
      };
      api
        .ckList(data)
        .then((res) => {
          if (res.code == 200) {
            this.cfLists = res.data;
            res.data.forEach((item) => {
              var obj = {};
              if (item.storeTypeCode === this.this.form.orgId) {
                console.log(item, "item...");
                (obj.orgName = item.orgName), (obj.id = item.id);
                this.cfLists.push(obj);
              }
            });

            console.log(this.cfLists);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //仓库值改变时
    ckChange(val) {
      console.log(val, "/////");
      // this.parentId = val;
      this.cfList();
    },

    //新增接口
    addList() {
      console.log(this.roleLists, ";;;");
      console.log(this.ckLists, ";;;");
      console.log(this.cfLists, ";;;");

      this.roleLists.forEach((item) => {
        console.log(this.form.userRole, "item...");
        if (item.enumCode === this.form.userRole) {
          this.userRoleName = item.enumName;
        }
      });
      this.ckLists.forEach((item) => {
        if (item.id === this.form.orgId) {
          this.orgName = item.orgName;
        }
      });
      this.cfLists.forEach((item) => {
        if (item.id === this.form.manageStore) {
          this.manageStoreName = item.orgName;
        }
      });
      var data = {
        orgName: this.orgName,
        userRoleName: this.userRoleName,
        manageStoreName: this.manageStoreName,
        userId: this.form.userId,
        userName: this.form.userName,
        userPassword: this.form.userPassword,
        userRole: this.form.userRole,
        orgId: String(this.form.orgId),
        manageStore: String(this.form.manageStore),
        userPhone: this.form.userPhone,
        userState: this.form.userState === true ? "1" : "0",
      };
      console.log(data, "data...");
      api
        .addUser(data)
        .then((res) => {
          if (res.code == 200) {
            // this.$nextTick(() => {
            //   this.$refs["formData"].resetFields();
            // });
            this.$message.success("新增成功");
            this.getList();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //编辑接口
    editList() {
      this.roleLists.forEach((item) => {
        console.log(this.form.userRole, "item...");
        if (item.enumCode === this.form.userRole) {
          this.userRoleName = item.enumName;
        }
      });
      this.ckLists.forEach((item) => {
        if (item.id === this.form.orgId) {
          this.orgName = item.orgName;
        }
      });
      this.cfLists.forEach((item) => {
        if (item.id === this.form.manageStore) {
          this.manageStoreName = item.orgName;
        }
      });
      var data = {
        orgName: this.orgName,
        userRoleName: this.userRoleName,
        manageStoreName: this.manageStoreName,

        id: this.rowId,
        userId: this.form.userId,
        userName: this.form.userName,
        userPassword: this.form.userPassword,
        userRole: this.form.userRole,
        orgId: String(this.form.orgId),
        manageStore: String(this.form.manageStore),
        userPhone: this.form.userPhone,
        userState: this.form.userState === true ? "1" : "0",
      };
      api
        .editUser(data)
        .then((res) => {
          if (res.code == 200) {
            // this.$nextTick(() => {
            //   this.$refs["formData"].resetFields();
            // });
            this.$message.success("新增成功");
            this.getList();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    search() {
      console.log(this.formInline.roleName, "'''");
      this.getList();
    },
    reset() {
      this.formInline = {};
      this.getList();
    },
    //表格序号
    indexMethod(index) {
      return (
        (this.pagination.curPage - 1) * this.pagination.pageSize + index + 1
      );
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getList();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.curPage = val;
      this.getList();
    },
    detail() {},
    //新建用户
    addClick(type) {
      this.btnType = type;

      this.userDialog = true;
      this.title = "新建用户";
      this.$nextTick(() => {
        this.$refs["formData"].resetFields();
        this.$set(this.form,"userPassword",null);
       this.$set(this.form,"userName",null)
        this.$set(this.form,"userRole",null)
        this.$set(this.form,"userId",null)
        this.$set(this.form,"orgId",null)
        this.$set(this.form,"manageStore",null)
        this.$set(this.form,"userPhone",null)
         this.$set(this.form,"userState",true)
      });
      

      // this.form.userState = true;
    console.log(this.form,";;;;")
      this.ckList();
    },
    //编辑用户
    edit(row, type) {
      this.btnType = type;
      this.userDialog = true;
      this.title = "修改用户";
      this.$nextTick(() => {
        this.$refs["formData"].resetFields();
        this.rowId = row.id;
      this.$set(this.form,"userPassword",null);
       this.$set(this.form,"userName",row.userName)
        this.$set(this.form,"userRole",row.userRole)
        this.$set(this.form,"userId",row.userId)
        this.$set(this.form,"orgId",parseInt(row.orgId))
        this.$set(this.form,"manageStore",parseInt(row.manageStore))
        this.$set(this.form,"userPhone",row.userPhone)
         this.$set(this.form,"userState",row.userState==="1"?true:false)
      });
      // this.form = JSON.parse(JSON.stringify(row));

      console.log(row, "编辑行");

      
      // this.form = {
      //   userPassword: "",
      //   userName: row.userName,
      //   userRole: row.userRole,
      //   userId: row.userId,
      //   orgId: parseInt(row.orgId),
      //   manageStore: parseInt(row.manageStore),
      //   userPhone: row.userPhone,
      //   userState: row.userState,
      // };
      this.cfList();
      // this.form.userState = row.userState === true ? "1" : "0";
      console.log(this.form, "this.form..");
      if (this.form.userState === "1") {
        this.form.userState = true;
      } else {
        this.form.userState = false;
      }
      this.ckList();
    },
    //删除用户
    deleted(row) {
      console.log(row, "////");
      this.$confirm("删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let id = row.id;

          api
            .deleteUser(id)
            .then((res) => {
              if (res.code && res.code == 200) {
                this.$message.success("删除成功");
                this.getList();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //点弹框确定按钮
    defined(formData) {
      console.log(this.btnType, "////");
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.btnType == 1) {
            this.addList();
            this.userDialog = false;
          } else {
            this.editList();
            this.userDialog = false;
          }
        }
      });
    },

    //点击取消按钮
    quxiao() {
      // this.$nextTick(() => {
      //   this.$refs["formData"].resetFields();
      // });
      this.userDialog = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.main {
  height: 100%;
  display: flex;
 
  .zt_right {
    width:100%;
    // margin-left: 20px;
    // width: calc(100% - 250px);
    .nav {
      padding: 10px 0 10px 10px;
      color: #fff;

      font-size: 14px;

      background: #004a93;
    }
    // .right_main {
    //   border: 1px solid #67a7df;
    //   background: #112f5d;

    //   margin-top: 10px;
    //   .right_title {
    //     color: #fff;
    //     border-bottom: 1px solid #67a7df;
    //     padding: 10px;
    //     font-size: 14px;
    //   }
    //   .right_table {
    //     padding: 20px;
    //   }
    // }
  }
}
.float-left {
  float: left;
}
.float-right {
  float: right;
}
#dialogStyle .el-select {
  width: 100%;
}
</style>
