<template>
  <div class="main-container-text">
    <div class="title">用户管理</div>
    <div class="header">
      <el-input v-model="user_code" clearable placeholder="请输入工号" />
      <el-input v-model="real_name" clearable placeholder="请输入姓名" />
      <el-select v-model="role_id" clearable placeholder="请输入角色" :value="manageer">
        <el-option
          v-for="item in roleData"
          :key="item.role_id"
          :label="item.role_name"
          :value="item.role_id"
        />
      </el-select>
      <el-select v-model="is_enabled" clearable placeholder="账号状态" :value="manageer">
        <el-option label="启用" :value="1" />
        <el-option label="未启用" :value="0" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button type="primary" plain @click="handleAddUser"><i class="el-icon-plus" />新增用户</el-button>
      <div class="header-right">
        <el-button icon="el-icon-delete" circle @click="handleDelTem" />
        <el-button icon="el-icon-refresh" circle @click="handleRefresh" />
      </div>
    </div>
    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中"
      :data="tableData"
      :header-cell-style="headerStyle"
      height="69vh"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        prop="user_code"
        label="工号"
        align="center"
      />
      <el-table-column
        prop="real_name"
        label="姓名"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.real_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色"
        align="center"
      />
      <el-table-column
        prop="sex"
        label="性别"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.sex === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="mobile"
        label="联系电话"
        align="center"
        width="130"
      />
      <el-table-column
        show-overflow-tooltip
        prop="email"
        label="电子邮箱"
        align="center"
        width="130"
      />
      <el-table-column
        prop="create_date"
        label="创建时间"
        align="center"
        width="150"
      />
      <el-table-column
        prop="is_enabled"
        label="状态"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_enabled === 1?'success':'danger'">{{
              scope.row.is_enabled === 1 ? '启用' : '未启用'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作"
        align="center"
        width="300"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" @click="handleFace(scope.$index, scope.row)">录入人脸</el-button>
          <el-button size="mini" @click="handleRole(scope.$index, scope.row)">
            <svg-icon icon-class="分配权限" />
            分配功能权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="my-pagination" style="text-align: center">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page.sync="page"
        :total="total"
        :page-size.sync="page_size"
        @current-change="pageChange"
      />
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :title="userFormTitle"
      :visible.sync="dialogVisible"
      width="38%"
      @close="userFormDialogClose"
    >
      <UserForm
        :propsformdata="userFormData"
        :roledata="roleData"
        @handlesubmit="handleUserSubmit"
        @handlecancel="handleUserFormCancel"
      />
    </el-dialog>
    <el-dialog
      title="分配用户权限"
      :close-on-click-modal="false"
      :visible.sync="roleDialogVisible"
      width="30%"
      @close="handleClose"
    >
      <el-tabs
        v-model="activeName"
        v-loading="tabsLoading"
        element-loading-text="拼命加载中"
      >
        <el-tab-pane label="后台管理" name="first">
          <el-checkbox
            v-model="checkAll_drug_module_id"
            :indeterminate="isIndeterminate_drug_module_id"
            @change="(val) => handleCheckAllChange(val,'drug_module_id')"
          >全选
          </el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group
            v-model="formData.drug_module_id"
            @change="(val) => handleCheckedCitiesChange(val,'drug_module_id')"
          >
            <el-checkbox v-for="item in drug_module_idOptions" :key="item.module_id" :label="item.module_id">
              {{ item.module_name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-tab-pane>
        <el-tab-pane label="终端管理" name="second">
          <el-checkbox
            v-model="checkAll_client_module_id"
            :indeterminate="isIndeterminate_client_module_id"
            @change="(val) =>handleCheckAllChange(val,'client_module_id')"
          >全选
          </el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group
            v-model="formData.client_module_id"
            @change="(val) =>handleCheckedCitiesChange(val,'client_module_id')"
          >
            <el-checkbox v-for="item in client_module_idOptions" :key="item.module_id" :label="item.module_id">
              {{ item.module_name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-tab-pane>
        <el-tab-pane label="标准品管理" name="data">
          <el-checkbox
            v-model="checkAll_standard_module_id"
            :indeterminate="isIndeterminate_standard_module_id"
            @change="(val) =>handleCheckAllChange(val,'standard_module_id')"
          >全选
          </el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group
            v-model="formData.standard_module_id"
            @change="(val) =>handleCheckedCitiesChange(val,'standard_module_id')"
          >
            <el-checkbox v-for="item in standard_module_idOptions" :key="item.module_id" :label="item.module_id">
              {{ item.module_name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-tab-pane>
        <el-tab-pane label="耗材管理" name="third">
          <el-checkbox
            v-model="checkAll_consumables_module_id"
            :indeterminate="isIndeterminate_consumables_module_id"
            @change="(val) =>handleCheckAllChange(val,'consumables_module_id')"
          >全选
          </el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group
            v-model="formData.consumables_module_id"
            @change="(val) =>handleCheckedCitiesChange(val,'consumables_module_id')"
          >
            <el-checkbox v-for="item in consumables_module_idOptions" :key="item.module_id" :label="item.module_id">
              {{ item.module_name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-tab-pane>
        <el-tab-pane label="仪器管理" name="fourth">
          <el-checkbox
            v-model="checkAll_instrument_module_id"
            :indeterminate="isIndeterminate_instrument_module_id"
            @change="(val) =>handleCheckAllChange(val,'instrument_module_id')"
          >全选
          </el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group
            v-model="formData.instrument_module_id"
            @change="(val) =>handleCheckedCitiesChange(val,'instrument_module_id')"
          >
            <el-checkbox v-for="item in instrument_module_idOptions" :key="item.module_id" :label="item.module_id">
              {{ item.module_name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <div style="text-align: center">
          <el-button @click="roleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmitForm">确 定</el-button>
        </div>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="录入人脸"
      destroy-on-close
      :visible="dialogFaceVisible"
      width="400px"
      @close="handleFaceCancel"
    >
      <div>
        <div class="face-content">
          <img v-if="play" id="video" width="200px" height="200px" :src="play" alt="">
        </div>
        <div class="name">程小红</div>
        <div class="code">工号：779</div>
        <div class="result">
          请稍后，<br>
          正在为您录入人脸信息..
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UserForm from '@/components/UserForm'
import {
  add,
  add_user_power,
  del, faceStart,
  faceStop, faceAdd,
  get_module_list,
  get_role_name_list,
  get_user_list,
  get_user_power_list,
  update
} from '@/api/user/user'
import stringify from '@/utils/stringify'
import { throttle, web_stream as webStream } from '@/utils'

export default {
  name: 'User',
  components: { UserForm },
  data() {
    return {
      // 全选相关
      checkAll_drug_module_id: false,
      isIndeterminate_drug_module_id: true,
      checkAll_client_module_id: false,
      isIndeterminate_client_module_id: true,
      checkAll_standard_module_id: false,
      isIndeterminate_standard_module_id: true,
      checkAll_consumables_module_id: false,
      isIndeterminate_consumables_module_id: true,
      checkAll_instrument_module_id: false,
      isIndeterminate_instrument_module_id: true,

      tableData: [],
      manageer: null,
      headerStyle: { 'background': '#E6E6E6' },
      dialogVisible: false,
      userFormTitle: '',
      userFormData: {},
      multipleSelection: [],
      // 分配用户权限
      roleDialogVisible: false,
      activeName: 'first',
      page: 1,
      page_size: 15,
      total: 0,
      user_code: '',
      real_name: '',
      role_id: '',
      is_enabled: '',
      loading: false,
      roleData: [],
      tabsLoading: false,
      drug_module_idOptions: [],
      client_module_idOptions: [],
      standard_module_idOptions: [],
      consumables_module_idOptions: [],
      instrument_module_idOptions: [],
      formData: {
        user_id: undefined,
        drug_module_id: [],
        client_module_id: [],
        standard_module_id: [],
        consumables_module_id: [],
        instrument_module_id: []
      },
      // 人脸识别
      dialogFaceVisible: false,
      videoObj: null,
      web_stream: null,
      img_list: [],
      play: null,
      rflag: false
    }
  },
  created() {
    this.getList()
    this.getRoleList()
    this.getModelList()
  },
  beforeDestroy() {
    this.handleCancel()
  },
  methods: {
    getModelList() {
      get_module_list().then(res => {
        this.drug_module_idOptions = res.data.sys_manage
        this.client_module_idOptions = res.data.client_manage
        this.standard_module_idOptions = res.data.standard_manage
        this.consumables_module_idOptions = res.data.consumables_manage
        this.instrument_module_idOptions = res.data.instrument_manage
      })
    },
    getRoleList() {
      get_role_name_list().then(
        res => (this.roleData = res.data)
      )
    },
    getList() {
      const data = {
        page: this.page,
        page_size: this.page_size,
        user_code: this.user_code,
        real_name: this.real_name,
        role_id: this.role_id,
        is_enabled: this.is_enabled
      }
      this.loading = true
      get_user_list(stringify(data)).then(res => {
        this.total = res.data.total_count
        this.tableData = res.data.data_list
      }).finally(() => (this.loading = false))
    },
    pageChange(page) {
      this.page = page
      this.getList()
    },
    handleCheckAllChange(val, t) {
      this.formData[t] = val ? this[t + 'Options'].map(item => item.module_id) : []
      this['isIndeterminate_' + t] = false
    },
    handleCheckedCitiesChange(value, t) {
      const checkedCount = value.length
      this.$set(this, 'checkAll_' + t, checkedCount === this[t + 'Options'].length)
      this['isIndeterminate_' + t] = checkedCount > 0 && checkedCount < this[t + 'Options'].length
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleUserSubmit(formdata) {
      const data = {
        ...this.userFormData,
        ...formdata
      }
      data.is_enabled = data.is_enabled ? 1 : 0
      data.role_name = this.roleData.find(item => item.role_id === data.role_id).role_name
      if (this.userFormTitle === '新增用户') {
        add(stringify(data)).then(res => {
          this.$message.success(res.msg)
          this.dialogVisible = false
          this.getList()
        })
      } else {
        update(stringify(data)).then(res => {
          this.$message.success(res.msg)
          this.dialogVisible = false
          this.getList()
        })
      }
    },
    userFormDialogClose() {
      this.userFormData = {}
    },
    handleUserFormCancel() {
      this.dialogVisible = false
      this.userFormData = {}
    },
    handleAddUser() {
      this.userFormTitle = '新增用户'
      this.dialogVisible = true
    },
    handleEdit(index, row) {
      this.userFormTitle = '编辑用户'
      const data = JSON.parse(JSON.stringify(row))
      data.is_enabled = data.is_enabled !== 0
      this.userFormData = data
      this.dialogVisible = true
    },
    handleFace(index, row) {
      this.$forceUpdate()
      faceStart().then(res => {
        setTimeout(() => {
          this.play = process.env.VUE_APP_FACE_API + '/face/play/'
        }, 200)
      })
      this.rflag = true
      this.dialogFaceVisible = true
      this.web_stream = webStream.get(process.env.VUE_APP_FACE_API + '/face/play/', (data) => {
        if (data.length > 41) {
          const buffer = Buffer.allocUnsafe(data.byteLength - 41)
          data.copy(buffer, 0, 37)
          this.img_src = buffer.toString('base64')
          const count = Math.floor(Math.random() * 10 + 1)
          //  随机抽样
          if (count < 3) {
            this.img_list.push('data:image/png;base64,' + this.img_src)
          }
          if (this.img_list.length > 10 && this.rflag) {
            const data = {
              'images': this.img_list,
              'user_id': row.user_id
            }
            faceAdd(data).then((res) => {
              this.rflag = false
            })
            this.img_list = []
          }
        }
      })
    },
    handleRole(index, row) {
      this.roleDialogVisible = true
      this.tabsLoading = true
      this.formData.user_id = row.user_id
      get_user_power_list(stringify({ 'user_id': row.user_id })).then(res => {
        // client_manage: [{have: 1, module_code: "MyDrug", module_id: "43272548-116f-11ed-8d0e-f47b094925e5",…},…]
        // consumables_manage: []
        // drug_manage: [{have: 1, module_code: "DrugScanBarCode", module_id: "4327254a-116f-11ed-8d11-f47b094925e5",…},…]
        // instrument_manage: []
        // standard_manage

        this.formData.consumables_module_id = res.data.consumables_manage.filter(item => item.have === 1).map(item => item.module_id)
        this.formData.drug_module_id = res.data.drug_manage.filter(item => item.have === 1).map(item => item.module_id)
        this.formData.instrument_module_id = res.data.instrument_manage.filter(item => item.have === 1).map(item => item.module_id)
        this.formData.standard_module_id = res.data.standard_manage.filter(item => item.have === 1).map(item => item.module_id)
        this.formData.client_module_id = res.data.client_manage.filter(item => item.have === 1).map(item => item.module_id)
      }).finally(() => {
        this.tabsLoading = false
      })
    },
    handleDelTem() {
      if (this.multipleSelection.length !== 1) {
        this.$message.warning('请选择1个需要删除的用户')
        return
      }
      this.$confirm(`确定要删除用户 ${this.multipleSelection[0].real_name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>
        del(stringify({ 'user_id': this.multipleSelection[0].user_id })).then(
          res => {
            this.$message.success({
              type: 'success',
              message: res.msg
            })
            this.multipleSelection = []
            this.getList()
          }
        )
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleRefresh() {
      this.getList()
    },
    handleSearch() {
      this.getList()
    },
    // 提交-分配用户权限form
    handleSubmitForm() {
      const data = JSON.parse(JSON.stringify(this.formData))
      data.drug_module_id = JSON.stringify(data.drug_module_id)
      data.client_module_id = JSON.stringify(data.client_module_id)
      data.standard_module_id = JSON.stringify(data.standard_module_id)
      data.consumables_module_id = JSON.stringify(data.consumables_module_id)
      data.instrument_module_id = JSON.stringify(data.instrument_module_id)
      add_user_power(stringify(data)).then(
        res => {
          this.$message.success(res.msg)
          this.roleDialogVisible = false
        }
      )
    },
    // 关闭时清空
    handleClose() {
      this.formData = {
        user_id: undefined,
        drug_module_id: [],
        client_module_id: [],
        standard_module_id: [],
        consumables_module_id: [],
        instrument_module_id: []
      }
    },
    handleFaceCancel: throttle(function() {
      faceStop().then(
        res => {
          console.log(res)
        }
      )
      this.dialogFaceVisible = false
      this.web_stream.destroy()
      this.play = null
      this.rflag = false
    }, 1000),
    handleCancel() {
      this.play = null
      this.rflag = false
      this.dialogFaceVisible = false
      if (this.web_stream) {
        this.web_stream.destroy()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.main-container-text {
  min-height: calc(100vh - 110px);
  padding: 1rem;
  margin: 1rem;
  background: white;

  .title {
    font-size: 20px;
    font-weight: bold;
    color: #000000;
  }

  .header {
    margin: 1rem 0 1rem 0;

    .el-input {
      width: 12.5rem;
      margin-right: 1rem;
    }

    .el-select {
      width: 12.5rem;
      margin-right: 1rem;
    }

    .header-right {
      float: right;
    }
  }

  #video {
    border-radius: 50%;
    border: 1px solid #707070;
  }

  .face-content {
    text-align: center;
    width: 100%;
  }

  .name {
    text-align: center;
    font-size: 30px;
    font-weight: 400;
    color: #000000;
  }

  .code {
    text-align: center;
    font-size: 20px;
    font-weight: 400;
    color: #409EFF;
    margin-top: 1rem;
  }

  .result {
    margin-top: 1rem;
    text-align: center;
    color: #C0C4CC;
    font-size: 24px;
    font-weight: 400;
  }
}

</style>
