<template>
  <div>
    <el-card>
      <el-button type="primary" @click="addUser" style="margin-left: 20px;">添加用户</el-button>
      <el-main id="el-main">
        <el-table :data="userList" border style="width: 100%" height="600px">
          <el-table-column prop="user_idcard" label="工号" align="left"></el-table-column>
          <el-table-column prop="user_name" label="用户名" align="left"></el-table-column>
          <el-table-column prop="role_des" label="角色" align="left"></el-table-column>
          <el-table-column prop="user_dept" label="公司" align="left"></el-table-column>
          <el-table-column prop="user_phone" label="联系方式" align="left"></el-table-column>
          <el-table-column prop="project_names" label="参与项目" align="left"></el-table-column>
          <el-table-column prop="user_state" label="状态" align="left">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.user_state == 1">激活</el-tag>
              <el-tag type="danger" v-if="scope.row.user_state == 2">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="left">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="editUser(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="deleteUser(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-pagination background layout="sizes,prev, pager, next,  jumper,->,total" :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize" :total="total" :current-page.sync="currPage" @current-change="handleCurrentChange"
        @size-change="handleSizeChange"></el-pagination>
    </el-card>

    <el-dialog title="添加用户信息" :visible.sync="dialogVisibleAdd" width="30%">
      <el-form :model="userData" label-width="120px" ref="refUserData" :rules="rulesUserData">

        <el-form-item label="选择用户类型" prop="user_type">
          <el-select v-model="userData.user_type" placeholder="请选择" @change="handleChangeUserType" style="width: 100%;">
            <el-option key="1" label="内部用户" value="1"></el-option>
            <el-option key="2" label="外部用户" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择用户公司" v-if="userData.user_type > 1">
          <el-select v-model="userData.user_company" placeholder="请选择" @change="handleChangeCompany"
            style="width: 100%;">
            <el-option v-for="item in companyList" :key="item.company_id" :label="item.company_name"
              :value="item.company_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择添加用户" prop="user_id">
          <el-select v-model="userData.user_id" filterable placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in contactsList"
                       filterable
                       :key="item.contacts_id"
                       :label="item.contacts_name"
              :value="item.contacts_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择参与的项目" v-if="userData.user_type == 2">
          <el-select v-model="userData.user_project" multiple placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in projectList" :key="item.project_id" :label="item.project_name"
              :value="item.project_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="user_role">
          <el-select v-model="userData.user_role" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in roles" :key="item.id" :label="item.role_des" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userData.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="重复密码" prop="againPassword">
          <el-input v-model="userData.againPassword" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="submitAddDialog('refUserData')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑用户信息" :visible.sync="dialogVisibleEdit" width="30%">
      <el-form :model="editUserData" label-width="120px">
        <el-form-item label="角色">
          <el-select v-model="editUserData.user_role" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in roles" :key="item.id" :label="item.role_des" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="editUserData.user_state" placeholder="请选择" style="width: 100%;">
            <el-option key="1" label="正常" value="1"></el-option>
            <el-option key="2" label="禁用" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择参与的项目">
          <el-select v-model="editUserData.user_project" multiple placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in projectList" :key="item.project_id" :label="item.project_name"
              :value="item.project_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="editUserData.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="重复密码">
          <el-input v-model="editUserData.againPassword" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="submitEditDialog()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》 ';
import user from '@/api/user';
import partner from '@/api/partner';
import project from '@/api/project'
export default {
  components: {},
  props: {},
  data() {
    // 密码验证
    const pwdCheck = async (rule, value, callback) => {
      if (value.length < 6) {
        this.changeFlag = 2;
        return callback(new Error('密码不能少于6位！'));
      } else if (value.length > 16) {
        this.changeFlag = 2;
        return callback(new Error('密码最长不能超过16位！'));
      } else {
        this.changeFlag = 1;
        callback()
      }
    }
    // 重复密码验证
    const pwdAgainCheck = async (rule, value, callback) => {
      if (value.length < 1) {
        this.changeAgainFlag = 2;
        return callback(new Error('重复密码不能为空！'));
      } else if (this.userData.password !== this.userData.againPassword) {
        this.changeAgainFlag = 2;
        return callback(new Error('两次输入密码不一致！'));
      } else {
        this.changeAgainFlag = 1;
        callback()
      }
    };
    // 这里存放数据
    return {
      changeFlag: 0,
      changeAgainFlag: 0,
      tableHeight: '0px',
      pageSize: 20,
      currPage: 1,
      total: 0,
      userList: [],
      companyList: [],
      contactsList: [],
      projectList: [],
      dialogTitle: '',
      dialogVisibleEdit: false,
      dialogVisibleAdd: false,
      userData: {
        user_type: '',
        user_company: '',
        user_id: '',
        user_role: '',
        password: '123456',
        againPassword: '123456',

      },
      editUserData: {
        user_id: '',
        user_state: '',
        user_role: '',
        password: '',
        againPassword: '',
        user_project: []
      },
      roles: [],//
      rulesUserData: {
        user_type: [
          { required: true, message: '请选择用户类型', trigger: 'blur' },
        ],
        user_id: [
          { required: true, message: "请选择用户", trigger: "blur" }
        ],
        user_role: [
          { required: true, message: "请选择角色", trigger: "blur" }
        ],
        password: [
          { required: true, validator: pwdCheck, trigger: 'blur' },
        ],
        againPassword: [
          { required: true, validator: pwdAgainCheck, trigger: 'blur' },
        ],
      },
    }
  },
  // 计算属性 类似于 data 概念
  computed: {},
  // 监控 data 中的数据变化
  watch: {},
  mounted() {
    this.getRoles()
    this.getUserInfoList()
    this.get_project_list()
  },
  // 方法集合
  methods: {
    //获取角色
    getRoles() {
      user.getRoles().then(res => {
        this.roles = res.data.data;
      })
    },
    //获取用户信息
    getUserInfoList() {
      user.getUserInfoList({ currPage: this.currPage, pageSize: this.pageSize}).then(res => {
        this.userList = res.data.data.list;
        console.log('userList', this.userList);
        this.total = res.data.data.total;
      })
    },
    handleCurrentChange(val) {
      this.currPage = val;
      this.getUserInfoList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getUserInfoList();
    },
    get_project_list() {
      var param = { state: '' }
      project.GetProjectList(param).then(response => {
        this.projectList = response.data.data
        console.log(this.projectList)
      })
    },
    addUser() {
      this.dialogTitle = '添加用户';
      this.dialogVisibleAdd = true;
      this.userData = {
        user_type: '',
        user_company: '',
        user_id: '',
        user_role: '',
        password: '',
        againPassword: '',
        user_project: ''
      }
    },

    editUser(row) {
      this.dialogVisibleEdit = true;
      console.log(row);
      this.editUserData.user_id = row.id;
      this.editUserData.password = '';
      this.editUserData.againPassword = '';
      this.editUserData.user_state = row.user_state;
      this.editUserData.user_role = row.user_role;
      this.editUserData.user_project = row.user_project ? row.user_project.split(',').map(Number) : [];
    },

    deleteUser(scope) {
      const _this = this;
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        user.deleteUser({ user_id: scope.id }).then(res => {
          let type = res.data.code === 20000 ? 'success' : 'warning';
          this.$message({
            message: res.data.data,
            type: type
          });
          _this.getUserInfoList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    submitAddDialog(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.contactsList.length; ++i) {
            if (this.contactsList[i].contacts_id == this.userData.user_id) {
              this.userData.user_idcard = this.contactsList[i].contacts_idcard;
              break;
            }
          }

          user.addUser(this.userData).then(res => {
            let type = res.data.code === 20000 ? 'success' : 'warning';
            this.$message({
              message: res.data.message,
              type: type
            });
            this.dialogVisibleAdd = false;
            this.getUserInfoList();
          })
        }
        else {
          this.$message({
            type: 'error',
            message: '请检查输入内容是否正确'
          });
        }
      })
    },

    submitEditDialog() {
      if (this.editUserData.password === "") {
        this.$message({
          type: 'error',
          message: '请输入密码！'
        });
      } else {
        user.updateUser(this.editUserData).then(res => {
          let type = res.data.code === 20000 ? 'success' : 'warning';
          this.$message({
            message: res.data.data,
            type: type
          });
          this.dialogVisibleEdit = false;
          this.getUserInfoList();
        })
      }
    },


    handleChangeUserType(value) {

      //获取合作伙伴公司列表
      if (value == 2) {
        //外部客户
        partner.GetPartnerList().then(response => {
          this.companyList = response.data.data;
        })
        this.userData.user_id = ''
        this.userData.user_company = null
        this.contactsList = []
      }
      else {
        //内部员工
        this.handleChangeCompany(value);
      }
    },

    handleChangeCompany(value) {
      //根据类型获取公司员工列表
      var param = { company_id: value };

      if (this.userData.user_type == 2) {
        partner.GetContactsList(param).then(response => {
          console.log(response + '111111111111111111111111')
          this.contactsList = response.data.data
        })
      }
      else {
        user.GetContactsList().then(response => {
          console.log(response)
          this.contactsList = response.data.data
        })
      }
      this.userData.user_id = ''
    }
  },
  // 生命周期 - 创建完成（可以访问当前this 实例）
  created() {
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped></style>
