<template>
  <div class="app-container">
          <el-button type="primary" @click="handleAddUser" icon="el-icon-plus">新增</el-button>
        <el-table
          :data="userList"
          style="width: 100%;margin-top:10px;"
          border
          fit
          v-loading="listLoading"
          highlight-current-row
          max-height="600"
        >
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column label="账户">
            <template slot-scope="scope">{{ scope.row.username }}</template>
          </el-table-column>
          <el-table-column label="姓名">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column label="角色">
            <template slot-scope="scope">
              <el-tag v-for="item in scope.row.roles_" v-bind:key="item" effect="plain">
                {{item}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="所属省份/单位">
            <template slot-scope="scope">
              {{ scope.row.pname }}
              {{ scope.row.bcompany_name }}
            </template>
          </el-table-column>
          <el-table-column label="创建日期">
            <template slot-scope="scope">
              <span>{{ scope.row.date_joined }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleUpdate(scope)"
                icon="el-icon-edit"
                :disabled="!checkPermission(['user_update'])"
                v-if="!scope.row.is_superuser"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope)"
                icon="el-icon-delete"
                :disabled="!checkPermission(['user_delete'])"
                v-if="!scope.row.is_superuser"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

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

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='update'?'编辑管理员':'新增管理员'">
      <el-form
        :model="user"
        label-width="80px"
        label-position="right"
        :rules="rule1"
        ref="userForm"
      >
        <el-form-item label="账户" prop="username">
          <el-input v-model="user.username" placeholder="账户" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="user.roles" multiple placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="省份" prop="pname">
              <el-select placeholder="请选择" clearable v-model="user.pname" style="width:100%">
    <el-option
      v-for="item in poptions"
      :key="item.label"
      :label="item.label"
      :value="item.label"
      style="width:100%"
      >
    </el-option>
  </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="bcompany">
          <el-input placeholder="单位" v-model="user.bcompany_name" readonly>
            <el-button slot="append" icon="el-icon-search" @click="dgcVisiable=true"></el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUser('userForm')">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="选择企业"
      :visible.sync="dgcVisiable"
      :close-on-click-modal="false"
      width="80%"
      :append-to-body="true"
    >
      <Companychose ref="Companychose" @handleChose="chooseComplete"></Companychose>
    </el-dialog>
  </div>
</template>
<script>
import { getUserList, createUser, deleteUser, updateUser} from "@/api/user";
import { getRoles } from "@/api/role"
import checkPermission from "@/utils/permission";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { provinceAndCityData } from 'element-china-area-data'
import Companychose from "@/views/crm/companychose";

const defaultUser = {
  id: "",
  username: "",
  password: "",
  is_superuser:false
};
export default {
  components: { Pagination, Companychose },
  data() {
    return {
      user: defaultUser,
      roles:[],
      userList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      dialogVisible: false,
      rule1: {
        username: [{ required: true, message: "请输入账号", trigger: "change" }],
      },
      filterOrgText: "",
      treeLoding: false,
      orgData: [],
      dialogType:'create',
      dialogVisible:false,
      poptions: provinceAndCityData,
      dgcVisiable:false
    };
  },
  computed: {},
  created() {
    this.getList();
    this.getRoles()
  },
  methods: {
    checkPermission,
    getRoles() {
      getRoles().then(response => {
        this.roles = response.data
      });
    },
    getList() {
      this.listLoading = true;
      getUserList(this.listQuery).then(response => {
        this.userList = response.data.results;
        this.total = response.data.count;
        this.listLoading = false;
      });
    },
    handleAddUser() {
      this.user = Object.assign({}, defaultUser);
      this.dialogVisible = true;
      this.dialogType = 'create'
      this.$nextTick(() => {
        this.$refs["userForm"].clearValidate();
      });
    },
    handleUpdate(scope){
      this.user = Object.assign({}, scope.row);
      this.dialogVisible = true;
      this.dialogType = 'update'

    } ,
    chooseComplete(val){
      this.dgcVisiable = false;
      if (val) {
        this.user.bcompany_name = val.name;
        this.user.bcompany = val.id;
      }
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error"
      })
        .then(async () => {
          await deleteUser(scope.row.id);
          this.userList.splice(scope.row.index, 1);
          this.$message({
            type: "success",
            message: "成功删除!"
          });
        })
        .catch(err => {
          console.error(err);
        });
    },
    async confirmUser(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
            const isEdit = this.dialogType === "update";
          if (isEdit) {
            updateUser(this.user.id, this.user).then(res => {
                this.getList();
                this.dialogVisible = false;
                this.$message({
                  message: "编辑成功",
                  type: "success",
                });
            });
          } else {
            createUser(this.user).then(res => {
                this.getList();
                this.dialogVisible = false;
                this.$message({
                  message: "新增成功",
                  type: "success"
                });
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
