<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="账号" prop="loginName">
        <el-input
          v-model="queryParams.loginName"
          placeholder="请输入账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="org">
        <el-input
          v-model="queryParams.org"
          placeholder="请输入部门"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地区" prop="areaId2">
        <el-cascader
          v-model="queryParams.areaId2"
          placeholder="请选择省份/地市/区县"
          :options="cityList"
          @change="areaIdChange"
          clearable
          :props="{ checkStrictly: true }"
          size="small"
        ></el-cascader>
        <!-- <el-select
          v-model="queryParams.areaId"
          placeholder="请选择省份/地市/区县"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in cityList"
            :key="dict.system"
            :label="dict.systemName"
            :value="dict.system"
          />
        </el-select> -->
      </el-form-item>
      <el-form-item style="float: right">
        <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="marginBottom10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-document-copy"
          size="mini"
          :disabled="multiple"
          @click="handleCopy"
          >批量权限复制</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
    </el-row>
    <el-alert
      v-show="!multiple"
      :title="'已选择' + delList.length + '项'"
      class="marginBottom10"
      :closable="false"
      show-icon
      type="warning"
    >
    </el-alert>
    <el-table
      v-loading="loading"
      :data="tableList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column label="用户名" align="center" prop="userName" width="150"/>
      <el-table-column label="账号" align="center" prop="loginName" width="150"/>
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" :show-overflow-tooltip="true"/>
      <el-table-column label="省份" align="center" prop="provinceName" width="80"/>
      <el-table-column label="地市" align="center" prop="cityName" />
      <el-table-column label="区县" align="center" prop="areaName" />
      <el-table-column
        label="部门"
        align="center"
        prop="org"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete fontRed"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加和编辑弹出框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      append-to-body
      width="600px"
    >
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        label-position="right"
        label-width="150px"
      >
        <div v-if="dialogTitle != '批量复制权限'">
          <el-form-item label="账号" prop="loginName">
            <el-input
              v-model="form.loginName"
              placeholder="请输入账号"
              :style="dialogTitle == '用户添加' ? 'width: 60%' : 'width: 100%'"
              :disabled="isDisabled"
            ></el-input>
            <el-button
              type="primary"
              @click="searchUserList"
              v-if="dialogTitle == '用户添加'"
              >查询用户信息</el-button
            >
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
              :disabled="isDisabledEmail"
            ></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <span>{{ form.phone }}</span>
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <span>{{ form.userName }}</span>
          </el-form-item>
          <el-form-item label="省份" prop="provinceName">
            <span>{{ form.provinceName }}</span>
          </el-form-item>
          <el-form-item label="地市" prop="cityName">
            <span>{{ form.cityName }}</span>
          </el-form-item>
          <el-form-item label="区县" prop="areaName">
            <span>{{ form.areaName }}</span>
          </el-form-item>
          <el-form-item label="组织" prop="orgName">
            <span>{{ form.orgName }}</span>
          </el-form-item>
        </div>
        <div v-if="dialogTitle != '用户详情'">
          <div class="formTitle">权限分配</div>
          <el-form-item label="要复制的账号" prop="loginNameCopy">
            <el-input
              v-model="form.loginNameCopy"
              placeholder="请输入要复制的账号"
              style="width: 70%"
              :disabled="isDisabled2"
            ></el-input>
            <el-button type="primary" @click="copyPermissions"
              >复制权限</el-button
            >
          </el-form-item>
        </div>

        <div class="formTitle">流程与黑点库</div>
        <el-form-item label="需配置的权限模块" prop="modelList">
          <el-checkbox-group
            v-model="modelList"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(item, index) in checkBoxList"
              :label="item.roleName"
              :key="index"
              >{{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in form.roles"
          :label="item.roleName"
          :key="index"
          :prop="'roles.' + index + '.cityId'"
          :rules="{
            required: true,
            message: '请选择地市',
            trigger: 'change',
          }"
        >
          <el-cascader
            ref="refCity"
            v-model="item.cityId"
            placeholder="请选择省份/地市/区县"
            :options="formCityList"
            @change="formareaIdChange(item.cityId, index)"
            clearable
            :disabled="isDisabled2"
            :props="{ checkStrictly: true }"
            style="width: 100%"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" v-if="this.dialogTitle != '用户详情'">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTopUserByLoginName,
  getroleAll,
  getCityAreaList,
  getTreeProvinceCity,
  getRoleByLoginName,
  getUserList,
  getUserAdd,
  getUserUpdate,
  getUserDel,
  getUserDetail,
  getRoleCopy,
} from "../../../common/js/home";
export default {
  name: "Module",
  components: {},
  data() {
    return {
      loading: false,
      cityList: [],
      queryParams: {
        current: 1,
        pageSize: 10,
        loginName: null,
        userName: null,
        org: null,
        areaId: null,
        areaId2: null,
      },
      tableList: [],
      total: 0,
      multiple: true,
      delList: [],
      dialogFormVisible: false,
      dialogTitle: "",
      form: {
        // 添加、详情、赋权表单，选中需赋权的列表
        roles: [
          // {
          //   cityId:'',
          //   cityName:''
          // }
        ],
      },
      isDisabled: true,
      isDisabled2: true,
      isDisabledEmail: true,
      props: { multiple: true },
      // 表单校验
      rules: {
        loginName: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
      },
      checkBoxList: [],
      modelList: [],
      formCityList: [],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.init();
    this.getList();
  },
  methods: {
    init() {
      getCityAreaList().then((res) => {
        this.cityList = res.data;
      });
      // 查询所有角色-添加、详情表单里面所用
      getroleAll().then((response) => {
        this.checkBoxList = response.data;
      });
      // 查询所有角色-添加、详情表单里面选择地市
      getTreeProvinceCity().then((re) => {
        this.formCityList = re.data;
      });
    },
    getList() {
      this.loading = true;
      getUserList(this.queryParams).then((res) => {
        this.loading = false;
        this.tableList = res.data.list;
        this.total = res.data.total;
      });
    },
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    // 查询条件地区选择
    areaIdChange(val) {
      console.log('val: ', val);
      this.queryParams.areaId = val[val.length - 1];
    },
    // 重置
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.areaId = '';
      this.queryParams.current = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      // console.log("val-----111: ", val);
      this.delList = val;
      if (val.length != 0) {
        this.multiple = false;
      } else {
        this.multiple = true;
      }
    },
    // 添加
    handleAdd() {
      this.modelList = [];
      this.resetForm("form");
      this.form = {
        roles: [],
      };
      this.dialogTitle = "用户添加";
      this.dialogFormVisible = true;
      this.isDisabled = false;
      this.isDisabledEmail = false;
      this.isDisabled2 = false;
    },
    // 复制权限
    handleCopy() {
      this.modelList = [];
      this.resetForm("form");
      this.form = {
        roles: [],
      };
      this.dialogTitle = "批量复制权限";
      this.dialogFormVisible = true;
      this.isDisabled2 = false;
    },
    userInfo(params) {
      this.modelList = [];
      getUserDetail(params).then((res) => {
        if (res.code == "1") {
          this.form = res.data;
          this.$nextTick(() => {
            this.form.roles.map((item) => {
              // item.cityId2 = item.cityId;
              this.modelList.push(item.roleName);
            });
            // console.log('this.form.roles: ', this.form.roles);
            // this.modelList = ['投诉预测']
            // console.log("this.modelList: ", this.modelList);
          });
        }
      });
    },
    // 编辑
    handleEdit(val) {
      // console.log("val8888: ", val);
      this.modelList = [];
      this.dialogTitle = "用户编辑";
      this.dialogFormVisible = true;
      this.isDisabled = true;
      this.isDisabledEmail = false;
      this.isDisabled2 = false;
      this.userInfo({ userId: val.userId });
      // this.$refs['form'].clearValidate();
    },
    // 详情
    handleDetail(val) {
      // console.log("val: ", val);
      this.modelList = [];
      this.dialogTitle = "用户详情";
      this.dialogFormVisible = true;
      this.isDisabled = true;
      this.isDisabledEmail = true;
      this.isDisabled2 = true;
      this.userInfo({ userId: val.userId });
      // this.$refs['form'].clearValidate();
    },
    // 查询用户信息
    searchUserList() {
      // console.log("this.form.loginName: ", this.form.loginName);
      let params = {
        loginName: this.form.loginName,
      };
      getTopUserByLoginName(params).then((res) => {
        if (res.code == "1") {
          this.form = {
            ...this.form,
            ...res.data,
          };
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      });
    },
    //复制权限
    copyPermissions() {
      let params = {
        loginName: this.form.loginNameCopy,
      };
      getRoleByLoginName(params).then((res) => {
        if (res.code == "1") {
          this.form.roles = res.data;
          this.$nextTick(() => {
            this.form.roles.map((item) => {
              this.modelList.push(item.roleName);
            });
            // this.modelList = ['投诉预测']
            // console.log("this.modelList: ", this.modelList);
          });
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      });
    },
    // 表单查询条件地区选择
    formareaIdChange(val, index) {
      // console.log("index111: ", index);
      // console.log("val111: ", val);
      if(val){
        this.form.roles[index].cityId = val[val.length - 1];
        this.form.roles[index].cityName =
          this.$refs["refCity"][index].getCheckedNodes()[0].label;
      }
      // console.log(this.$refs["refCity"].getCheckedNodes()[0].label)
      // console.log("this.form.roles: ", this.form.roles);
    },
    // 选择需配置的权限
    handleCheckedCitiesChange(val) {
      // console.log("val000: ", val);
      // this.form.roles = val;
      val.map((item) => {
        this.checkBoxList.map((item2) => {
          if (item2.roleName == item) {
            this.form.roles.push(item2);
            this.form.roles = [...new Set(this.form.roles)];
            let obj = {};
            this.form.roles = this.form.roles.reduce((cur, next) => {
              obj[next.roleName]
                ? ""
                : (obj[next.roleName] = true && cur.push(next));
              return cur;
            }, []); //设置cur默认类型为数组，并且初始值为空的数组
            // console.log("this.form.roles: ", this.form.roles);
          }
        });
        this.form.roles.map((item3, index3) => {
          if (val.indexOf(item3.roleName) < 0) {
            // console.log("item3: ", item3.roleName);
            this.form.roles.splice(index3, 1);
            // console.log("this.form.roles----: ", this.form.roles);
          }
        });
      });
    },
    //删除
    handleDelete(val) {
      // console.log("val: ", val);
      let params = {
        userIds: [],
      };
      if (val.userId) {
        params.userIds[0] = val.userId;
      } else {
        // console.log(" this.delList", this.delList);
        this.delList.map((item) => {
          params.userIds.push(item.userId);
        });
      }
      // console.log("params: ", params);
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          getUserDel(params).then((res) => {
            if (res.message == "成功") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: "删除失败",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.dialogTitle == "用户编辑") {
            getUserUpdate(this.form).then((response) => {
              if (response.code == "1") {
                this.$message({
                  type: "success",
                  message: "用户修改成功",
                });
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            });
          }
          if (this.dialogTitle == "用户添加") {
            getUserAdd(this.form).then((response) => {
              if (response.code == "1") {
                this.$message({
                  type: "success",
                  message: "用户新增成功",
                });
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            });
          }
          if (this.dialogTitle == "批量复制权限") {
            this.form.userIds = [];
            this.delList.map((item) => {
              this.form.userIds.push(item.userId);
            });
            // console.log('this.form: ', this.form);
            getRoleCopy(this.form).then(response=>{
              if (response.code == "1") {
                this.$message({
                  type: "success",
                  message: "批量授权成功",
                });
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            })
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.formTitle {
  height: 40px;
  line-height: 40px;
  font-weight: bold;
}
</style>
