<template>
  <div class="app-container">
    <div class="search">
     <el-input v-model="table.parammaps.name" placeholder="用户名称" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.parammaps.employee_name" placeholder="员工姓名" style="width: 180px;" class="filter-item" clearable />
      <el-select v-model="table.parammaps.is_show" placeholder="是否启用" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="item in enableList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-date-picker v-model="table.parammaps.inputDatetime" class="inputDatetime filter-item" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 250px;" />
      <el-button class="successBorder" @click="handleSearch">查询</el-button>
      <el-button class="successBorder" @click="handleRefresh">重置</el-button>
      </el-upload>
    </div>
    <div class="operation">
      <el-button v-if="isAdd" icon="el-icon-plus" class="success" @click="handleCreate">新增</el-button>
    </div>
    <div class="table">
      <el-table
        :key="table.tableKey"
        v-loading="table.listLoading"
        element-loading-text="给我一点时间"
        :data="table.list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable table-fixed"
      >
        <el-table-column type="selection" align="center" width="50" />
        <el-table-column label="序号" min-width="130px" align="center" prop="id" />
        <el-table-column label="用户名称" min-width="120px" align="center" prop="name" />
        <el-table-column label="员工姓名" min-width="120px" align="center" prop="employee_name" />
        <el-table-column label="手机号" min-width="120px" align="center" prop="phone" />
        <el-table-column label="角色" min-width="120px" align="center" prop="role_name" />
        <el-table-column label="创建时间" min-width="120px" align="center" prop="created_at_format" />
        <el-table-column label="创建人" min-width="120px" align="center" prop="create_user" />
        <el-table-column label="是否启用" min-width="110px" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_show" :disabled="!isEnable"  active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="2" @change="handleEnableChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <a class="correcting" v-if="isResetpassword" size="mini" style="width: 80px;" @click="handleResetPassword(row)">重置密码</a>
            <span v-if="isEdit" class="centerSpan">|</span>
            <el-button v-if="isEdit" class="miniSuccess" icon="el-icon-edit-outline" @click="handleUpdate(row)" />
            <span  v-if="isDelete"class="centerSpan">|</span>
            <el-button v-if="isDelete" class="miniDanger" icon="el-icon-delete" @click="handleRowDelete(row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.page" :limit.sync="table.page_size" @pagination="getList" />
    </div>
    <!-- 新增/编辑 -->
    <el-dialog :title="textMap[edit.dialogStatus]" :visible.sync="edit.dialogFormVisible" :close-on-click-modal="false"
      width="50%">
      <div class="edit">
        <div class="content">
          <el-form ref="editTemp" :rules="rules" :model="edit" label-position="right" label-width="115px"
            style="width: 90%;margin:0 auto 30px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户名称:" prop="name">
                  <el-input ref="name" v-model="edit.name" placeholder="请输入用户名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="员工姓名:" prop="employee_name">
                  <el-input ref="employee_name" v-model="edit.employee_name" placeholder="请输入员工姓名" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="手机号:" prop="phone">
                  <el-input ref="phone" v-model="edit.phone" placeholder="请输入手机号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="选择角色:" prop="checkedRole">
                  <el-checkbox :indeterminate="edit.isIndeterminateRole" v-model="edit.checkAllRole"
                    @change="handleRoleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="edit.checkedRole" @change="handleCheckedRoleChange">
                    <el-checkbox v-for="(item,index) in edit.roleList" :label="item.id"
                      :key="index">{{item.name}}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="是否启用" prop="is_show">
              <el-switch ref="is_show" v-model="edit.is_show" :disabled="edit.dialogStatus=='update'" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="2" />
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom: 40px;">
          <el-button class="cancelClose cancelClose" @click="edit.dialogFormVisible = false;getList(); ">关闭</el-button>
          <el-button class="save" :disabled="isokDisable"
            @click="edit.dialogStatus == 'add' ? createData():updateData()">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { postJson,getJson,delJson,exportFile,importFile,checkButtons } from '@/api/common'
import Cookies from 'js-cookie'
import { parseTime } from '@/utils/index.js'
import { MessageBox } from 'element-ui'
import Pagination from '@/components/Pagination'
import { validatePhone } from '@/utils/validate'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import localDownloadUtil from "@/utils/localDownloadUtil.js";
export default {
  name: 'User',
  components: { Pagination },
  data() {
    return {
      enableList: [{ id: 1, name: '是' }, { id: 2, name: '否' }], // 是否启用
      table: {
        page: 1,
        page_size: parseInt(Cookies.get('pageCount')),
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        parammaps: {
          name: '',employee_name:'',is_show:'',inputDatetime:[]
        }
      },
      edit: {
        dialogStatus: '',
        dialogFormVisible: false,
        temp: {

        },
        name:'',
        employee_name:'',
        phone:'',
        // 牧场
        roleOptions: [],
        checkAllRole: false,
        checkedRole: [],
        roleList: [],
        isIndeterminateRole: false
      },
      rules: {
        name: [{
          required: true,
          message: '必填',
          trigger: 'blur'
        }],
        employee_name: [{
          required: true,
          message: '必填',
          trigger: 'blur'
        }],
        phone: [{ validator: validatePhone,required: true, trigger: 'blur' }],
        checkedRole: [
          { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
        ],
      },
      textMap: {
        add: '新增',
        update: '编辑'
      },
      dataForm: {
          name: "",
          file: null,
      },
      isokDisable: false,
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      isAdd:'',isEdit:'',isResetpassword:'',isDelete:'',isEnable:'',
    }
  },

  created() {
    this.getButton()
    this.getList()
    this.getRoleList()
  },

  methods: {
    getButton(){
      const add = 'systemManagement:user:add'
      this.isAdd = checkButtons(add)
      const edit = 'systemManagement:user:edit'
      this.isEdit = checkButtons(edit)
      const resetpassword = 'systemManagement:user:resetpassword'
      this.isResetpassword = checkButtons(resetpassword)
      const del = 'systemManagement:user:delete'
      this.isDelete = checkButtons(del)
      const enable = 'systemManagement:user:enable'
      this.isEnable = checkButtons(enable)
    },
    getList(){
      this.table.listLoading = true
      let page = this.table.page
      let page_size = this.table.page_size
      let url = 'api/v1/system/user/list' + '?page=' + page + '&page_size=' + page_size
      let data = {
        "name":this.table.parammaps.name,
        "employee_name":this.table.parammaps.employee_name
      }
      if(this.table.parammaps.is_show !== ''){
        data.is_show = this.table.parammaps.is_show
      }
      if(this.table.parammaps.inputDatetime !== null && this.table.parammaps.inputDatetime.length > 0){
        data.created_start_time = this.table.parammaps.inputDatetime[0].getTime() / 1000
        data.created_end_time = this.table.parammaps.inputDatetime[1].getTime()  / 1000 + 86400
      }
      postJson(url, data).then(response => {
        if (response.code == 200) {
          this.table.list = response.data.list
          this.table.total = response.data.total
          this.table.pageNum = response.data.page
          this.table.pageSize = response.data.page_size
        } else {
          this.table.list = []
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 1000)
      })
    },
    getRoleList(){
      let page = 1
      let page_size = 100
      let url = 'api/v1/system/role/list' + '?page=' + page + '&page_size=' + page_size
      let data = {}
      postJson(url, data).then(response => {
        if (response.code == 200) {
          this.edit.roleOptions = []
          for (let i = 0; i < response.data.list.length; i++) {
            this.edit.roleOptions.push(response.data.list[i].id)
          }
          this.edit.roleList = response.data.list
        }
      })
    },
    handleEnableChange(index, row) {
      let url = 'api/v1/system/user/is_show'
      let data = {
        "user_id":row.id,
        "is_show":row.is_show
      }
      postJson(url,data).then(response => {
        if(response.code == 200){
          this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
          this.getList()
        }
      })
    },

    handleSearch() {
      this.table.page = 1
      this.getList()
    },
    handleRefresh() {
      console.log('点击了重置')
      this.table.parammaps.name = ''
      this.table.parammaps.employee_name = ''
      this.table.parammaps.is_show = ''
      this.table.parammaps.inputDatetime = []
      this.table.parammaps.created_start_time = ''
      this.table.parammaps.created_end_time = ''
      this.table.page = 1
      this.getList()
    },

    handleCreate() {
      this.edit.name = '',
      this.edit.employee_name = ''
      this.edit.phone = ''
      this.edit.is_show = 1
      this.edit.dialogStatus = 'add'
      this.edit.dialogFormVisible = true
      this.edit.isIndeterminateRole = false
      this.edit.checkedRole = []
    },

    handleRoleCheckAllChange(val) {
      this.edit.checkedRole = val ? this.edit.roleOptions : [];
      this.edit.isIndeterminateRole = false;
    },
    handleCheckedRoleChange(value) {
      let checkedCount = value.length;
      this.edit.checkAllRole = checkedCount === this.edit.roleList.length;
      this.edit.isIndeterminateRole = checkedCount > 0 && checkedCount < this.edit.roleList.length;
    },
    createData(row) {
      this.$refs['editTemp'].validate((valid) => {
        if (valid) {
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)
          let roles = []
          for(let i=0;i<this.edit.roleList.length;i++){
            for(let j=0;j<this.edit.checkedRole.length;j++){
              if(this.edit.roleList[i].id == this.edit.checkedRole[j]){
                let obj = {}
                obj.id = this.edit.roleList[i].id
                obj.name = this.edit.roleList[i].name
                roles.push(obj)
              }
            }
          }
          let url = 'api/v1/system/user/add'
          let data = {
            'name': this.edit.name,
            "employee_name": this.edit.employee_name,
            "phone": this.edit.phone,
            "is_show": this.edit.is_show,
            "roles": roles,
            "create_user": Cookies.get('username')
          }
          console.log(data)
          postJson(url, data).then(response => {
            if (response.code == 200) {
              this.$notify({
                title: '',
                message: '成功',
                type: 'success',
                duration: 2000
              })
              this.edit.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },

    handleUpdate(row) {
      this.edit.dialogStatus = 'edit'
      let url = 'api/v1/system/user/details/'
      let data = row.id
      getJson(url, data).then(response => {
        if (response.code == 200) {
          this.edit.name = response.data.name
          this.edit.employee_name = response.data.employee_name
          this.edit.phone = response.data.phone
          this.edit.is_show = response.data.is_show
          this.edit.checkedRole = response.data.role_ids
          this.edit.id = response.data.id
        }
        if (this.edit.checkedRole.length == this.edit.roleList.length) {
          this.edit.isIndeterminateRole = false
          this.edit.checkAllRole = true
        } else {
          this.edit.isIndeterminateRole = true
          this.edit.checkAllRole = false
        }
        this.edit.dialogFormVisible = true
      })
    },

    updateData() {
      this.$refs['editTemp'].validate((valid) => {
        if (valid) {
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)
          let roles = []
          for(let i=0;i<this.edit.roleList.length;i++){
            for(let j=0;j<this.edit.checkedRole.length;j++){
              if(this.edit.roleList[i].id == this.edit.checkedRole[j]){
                let obj = {}
                obj.id = this.edit.roleList[i].id
                obj.name = this.edit.roleList[i].name
                roles.push(obj)
              }
            }
          }
          let url = 'api/v1/system/user/edit'
          let data = {
            "id":this.edit.id,
            'name': this.edit.name,
            "employee_name": this.edit.employee_name,
            "phone": this.edit.phone,
            "is_show": this.edit.is_show,
            "roles": roles,
            "create_user": Cookies.get('username')
          }
          console.log(data)
          postJson(url, data).then(response => {
            if (response.code == 200) {
              this.$notify({
                title: '',
                message: '成功',
                type: 'success',
                duration: 2000
              })
              this.edit.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },

    handleRowDelete(row) {
      console.log('点击了行内删除')
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'api/v1/system/user/'
        let data = row.id
        delJson(url, data).then(response => {
          if (response.code == 200) {
            this.$notify({
              title: '',
              message: '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      })
    },

    handleResetPassword(row) {
      MessageBox.confirm('是否确认将此用户密码重置为默认密码123456？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'api/v1/system/user/rest_password/' + row.id
        let data = {}
        postJson(url, data).then(response => {
          if (response.code == 200) {
            this.$notify({
              title: '',
              message: '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      })
    }
  }
}
</script>
