<template>
  <layout
    :isleftshow="false"
    class="row"
    :rightStyle="{ padding: '10px 10px   0' }"
    :leftStyle="{ width: '60%', paddingTop: '10px' }"
  >
    <template slot="page_left">
      <el-form
        :inline="true"
        size="mini"
        @submit.native.prevent
        @keyup.enter.capture="search"
      >
        <el-form-item label="用户名">
          <el-input
            style="width: 120px"
            clearable
            v-model="searchForm.employeeName"
            placeholder="员工姓名/工号/登录名"
          ></el-input>
        </el-form-item>
        <el-form-item label="功能角色">
          <el-select
            style="width: 120px"
            clearable
            filterable
            v-model="searchForm.functionRoleId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in funcRoleList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据角色">
          <el-select
            style="width: 120px"
            clearable
            filterable
            v-model="searchForm.dataRoleId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in dataRoleList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select
            clearable
            :class="{
              green: searchForm.enable === '1',
              red: searchForm.enable === '0',
            }"
            v-model="searchForm.enable"
            style="width: 120px"
            placeholder="请选择"
          >
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="平台">
          <el-select
            style="width: 120px"
            v-model="searchForm.platForm"
            clearable
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="(item, index) in platforms"
              :key="index"
              :label="item.value"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="roleShow('query_system_users')">
          <el-button
            native-type="submit"
            type="primary"
            @click="search()"
            icon="el-icon-search"
          >
            查询
          </el-button>
        </el-form-item>
        <el-form-item v-if="roleShow('add_system_users')">
          <el-button type="success" @click="addDialog(1)"
            >新增</el-button
          >
        </el-form-item>
        <el-form-item
          v-if="roleShow('delete_system_users')"
        >
          <el-button type="danger" @click="deleteSection()"
            >删除</el-button
          >
        </el-form-item>
        <!-- <el-form-item>
            <el-button type="info" @click="addDialog(2)">重置密码</el-button>
        </el-form-item>-->
      </el-form>
      <div class="table_wrap">
        <table-vue
          :sourceData="sourceData"
          ref="multipleTable"
          :selection="true"
          :tableColumns="usersTableColumns"
          @currentChange="currentTabFn"
          :rowClassName="cellClass"
          @selectionChange="selectionChange"
        ></table-vue>
      </div>
      <pagination
        :setValue="setpaginationOptions"
        :options="paginationOptions"
      />
    </template>
    <template slot="page_right">
      <div style="height: 37px"></div>
      <table-vue
        :sourceData="details"
        :tableColumns="tableColumns"
      ></table-vue>
    </template>
    <!-- 弹出层 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="is_title == 1 ? '新增' : '编辑'"
      :visible.sync="dialogVisible"
      width="590px"
    >
      <el-form
        label-position="right"
        label-width="100px"
        size="mini"
        :inline="true"
        :model="addcurrencyform"
        :rules="addrules"
        ref="addcurrencyform"
      >
        <el-form-item
          label="员工姓名"
          prop="employeeId"
          required
        >
          <el-select
            :disabled="is_title == 2"
            v-model="addcurrencyform.employeeId"
            placeholder="请选择员工"
            @change="setempNo"
            style="width: 164px"
            filterable
          >
            <el-option
              v-for="item in employee"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工工号">
          <el-input
            style="width: 164px"
            disabled
            v-model="addcurrencyform.empNumber"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="登录账号"
          prop="loginName"
          required
        >
          <el-input
            style="width: 164px"
            v-model="addcurrencyform.loginName"
            placeholder="请输入登录账号"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <el-select
            style="width: 164px"
            v-model="addcurrencyform.enable"
            placeholder="请选择"
          >
            <el-option label="是" :value="true"></el-option>
            <el-option
              label="否"
              :value="false"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="功能角色"
          prop="funcRoleIds"
          required
        >
          <el-select
            style="width: 164px"
            v-model="addcurrencyform.funcRoleIds"
            placeholder="请选择角色"
            multiple
            filterable
          >
            <el-option
              v-for="item in funcRoleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              {{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据角色" prop="dataRoleIds">
          <el-select
            style="width: 164px"
            v-model="addcurrencyform.dataRoleIds"
            placeholder="请选择角色"
            multiple
            filterable
          >
            <el-option
              v-for="item in dataRoleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              {{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="首页排名" prop="platForm">
          <el-select
            style="width: 164px"
            v-model="addcurrencyform.platForm"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in platforms"
              :key="index"
              :label="item.value"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="同步花费">
          <el-switch
            v-model="addcurrencyform.cost"
            :active-value="true"
            :inactive-value="false"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="dialogVisible = false"
          size="mini"
          style="width: 100px"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          @click="addUser()"
          size="mini"
          style="width: 100px"
        >
          确认
        </el-button>
      </span>
    </el-dialog>
  </layout>
</template>
<script>
import { getOptionData } from '../../utils/commonUtil'
import axios from '../../common/api/axios'
import { mapState } from 'vuex'
import tableVue from '@/common/components/base/tableView.vue'
export default {
  name: 'system_users',
  components: {
    tableVue,
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (this.is_title === 1 && value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    const confirmPass = (rule, value, callback) => {
      if (this.is_title === 1 && value === '') {
        callback(new Error('确认密码不能为空'))
      } else if (
        this.is_title === 1 &&
        value !== this.addcurrencyform.password
      ) {
        callback(new Error('2次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      is_title: 1,
      select: '',
      sourceData: [],
      searchForm: {
        employeeName: '',
        enable: '1',
        platform: '',
      },
      dialogVisible: false,
      addcurrencyform: {
        id: '',
        loginName: '',
        password: '',
        confirmpwd: '',
        remark: '',
        enable: true,
        employeeId: '',
        roleId: '',
        funcRoleIds: [],
        platform: '',
      },
      addcurrencyform2: null,
      formId: null,
      addrules: {
        password: [
          { validator: validatePass, trigger: 'blur' },
        ],
        confirmpwd: [
          { validator: confirmPass, trigger: 'blur' },
        ],
        loginName: [
          {
            required: true,
            message: '请输入登录账号',
            trigger: 'blur',
          },
        ],
        employeeName: [
          {
            required: true,
            message: '请选择员工',
            trigger: 'change',
          },
        ],
        roleId: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'change',
          },
        ],
      },
      roleList: [],
      paginationOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0,
      },
      details: [],
      roleOptions: [],
      platforms: [],
    }
  },
  created() {
    this.getList(1)
    this.addcurrencyform2 = JSON.parse(
      JSON.stringify(this.addcurrencyform),
    )
    axios.get('sysRole/role_option')
      .then((res) => {
        if (res.code === 200) {
          this.roleOptions = res.data
        }
      })
      .catch((err) => {
        console.log(err)
      })
    axios.get('sysRole/all_list').then((res) => {
      this.roleList = res.data
    })
    axios.get('platform/user/employeePlatformList')
      .then((res) => {
        this.platforms = res.data
      })
      .catch((err) => {
        console.log(err)
      })
  },
  computed: {
    ...mapState(['reqMenu', 'employee']),
    usersTableColumns() {
      return [
        {
          label: '登录账户',
          key: 'loginName',
          width: 105,
          align: 'left',
          render: (item) => (
            <span>
              <i
                class="circle"
                style={{
                  backgroundColor: item.enable
                    ? 'green'
                    : 'red',
                }}
              ></i>
              {item.loginName}
            </span>
          ),
        },
        {
          label: '员工姓名',
          key: 'employeeName',
          width: 60,
        },

        { label: '员工工号', key: 'empNumber', width: 60 },
        { label: '功能角色', key: 'functionNames' },
        { label: '数据角色', key: 'dataNames' },
        { label: '平台', key: 'platFormTxt' },
        { label: '上次登录IP', key: 'lastIp' },
        {
          label: '上次登录时间',
          key: 'lastLoginTime',
          width: 130,
        },
        {
          label: '同步花费',
          width: 60,
          key: 'lastLoginTime',
          render: (item) => (
            <el-switch
              value={item.cost}
              onInput={(v) => this.spentChange(v, item)}
              active-value={true}
              inactive-value={false}
            ></el-switch>
          ),
        },
        {
          label: '锁定设备',
          key: 'enable',
          width: 60,
          render: (item) => (
            <span
              style="cursor: pointer"
              onClick={() => this.bindChange(item)}
            >
              {item.bindStatus ? (
                <svg
                  t="1616060540114"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="1989"
                  width="20"
                  height="20"
                  fill="#1afa29"
                >
                  <path
                    d="M800.421 436.525h-63.661v-148.673c0-124.507-100.762-225.757-224.732-225.757-123.98 0-224.857 101.25-224.857 225.766v148.662h-63.593c-30.667 0-55.532 24.952-55.532 55.752v407.048c0 30.848 24.865 55.82 55.532 55.82h576.9c30.667 0 55.465-24.97 55.465-55.82v-407.048c0-30.802-24.855-55.752-55.532-55.752zM543.203 706.409v88.88c-0.016 4.026-3.264 7.287-7.282 7.325h-47.733c-4.039-0.022-7.307-3.287-7.334-7.322v-88.882c-22.423-11.518-37.953-34.602-37.953-61.659 0-38.288 30.945-69.425 69.070-69.425 38.183 0 69.138 31.136 69.138 69.415 0.057 27.067-15.473 50.152-37.905 61.659zM650.514 436.525h-276.989v-144.986c0-76.691 62.196-139.146 138.552-139.146 76.366 0 138.447 62.454 138.447 139.146v144.986z"
                    p-id="1990"
                  ></path>
                </svg>
              ) : (
                <svg
                  t="1616061412578"
                  class="icon"
                  viewBox="0 0 1067 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="2133"
                  width="20"
                  height="20"
                >
                  <path
                    d="M116.587 440.171h564.044c29.993 0 54 24.755 54 55.687v408.335c0 30.931-24.007 55.687-54 55.687h-564.044c-30.003 0-54-24.755-54-55.687v-408.335c0-30.931 23.997-55.687 54-55.687zM368.607 712.397v86.618c0 6.187 5.997 6.187 5.997 6.187h48.003c6.007 0 6.007-6.187 6.007-6.187v-86.618c23.997-12.372 36-37.118 36-61.864 0-37.128-30.003-68.059-66.003-68.059s-66.013 30.931-66.013 68.049c0 30.941 12.003 49.5 36 61.872z"
                    p-id="2134"
                    fill="red"
                  ></path>
                  <path
                    d="M900.705 297.099c0-74.236-61.864-142.295-142.295-142.295-74.245 0-142.295 61.864-142.295 142.295v148.491h-80.431v-154.677c0-123.736 98.991-228.913 228.913-228.913 123.736 0 228.922 98.991 228.922 228.913v148.491h-86.618l-6.187-142.295z"
                    p-id="2135"
                    fill="red"
                  ></path>
                </svg>
              )}
            </span>
          ),
        },
        {
          label: '授权设备数量',
          key: 'authNum',
          width: 90,
          render: (item) =>
            item.authNum < 0 ? 0 : item.authNum,
        },
        {
          label: '相关操作',
          key: '',
          fixed: 'right',
          width: 80,
          render: (item) => (
            <div>
              {item.loginName !== 'admin' &&
                this.roleShow('update_system_users') && (
                  <span
                    title="编辑"
                    class="icon-view icon-edit-view"
                  >
                    <i
                      class="el-icon-edit"
                      onClick={(e) =>
                        this.addDialog(2, item, e)
                      }
                    ></i>
                  </span>
                )}
              {this.roleShow('reset_password') && (
                <span
                  title="重置密码"
                  class="icon-view icon-tools-view"
                >
                  <i
                    class="el-icon-refresh-left"
                    onClick={(e) => this.resetPwd(e, item)}
                  ></i>
                </span>
              )}
            </div>
          ),
        },
      ]
    },
    tableColumns() {
      return [
        { label: '访问IP', key: 'ip' },
        { label: '设备名称', key: 'deviceName' },
        { label: '授权状态', key: 'auditStatusTxt' },
        { label: '授权类型', key: 'authTypeTxt' },
        {
          label: '最后登录时间',
          key: 'lastLoginTime',
          width: 130,
        },
        {
          label: '操作',
          key: '',

          render: (item) => (
            <div>
              {this.roleShow('authorization') &&
                item.auditStatus === 0 && (
                  <span
                    class="icon-view icon-tools-view"
                    title="授权"
                  >
                    <i
                      class="el-icon-s-check"
                      onClick={(e) =>
                        this.authorization(item, e)
                      }
                    ></i>
                  </span>
                )}
              <span
                class="icon-view icon-del-view"
                title="删除"
              >
                <i
                  class="el-icon-delete"
                  onClick={(e) =>
                    this.authorizationDel(item, e)
                  }
                ></i>
              </span>
            </div>
          ),
        },
      ]
    },
    funcRoleList() {
      if (this.roleList.length > 0) {
        return this.roleList.filter(
          (item) => item.type === 'FUNCTION_ROLE',
        )
      }
      return []
    },
    dataRoleList() {
      if (this.roleList.length > 0) {
        return this.roleList.filter(
          (item) => item.type === 'DATA_ROLE',
        )
      }
      return []
    },
  },
  methods: {
    spentChange(v, item) {
      axios.post('platform/user/update', {
        ...item,
        cost: v,
      }).then(() => {
        this.getList()
      })
    },
    cellClass({ row }) {
      if (row.authAuditFlag === 1) {
        return 'first'
      } else {
        return ''
      }
    },
    selectionChange(selection) {
      if (selection.length > 0) {
        this.select = selection
      }
    },
    authorization(item, e) {
      e && e.stopPropagation()
      axios.post('sysDeviceInfo/auditApply', {
        id: item.id,
      }).then((res) => {
        this.$message.success(res.message)
        this.getList()
      })
    },
    authorizationDel(item, e) {
      e && e.stopPropagation()
      this.$confirm('确定删除选中的信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          axios.post('sysDeviceInfo/delApply', {
            id: item.id,
          }).then((res) => {
            this.$message.success(res.message)
            this.getList()
          })
        })
        .catch(() => {})
    },
    getRoleList(userId) {
      axios.post('sysDeviceInfo/getList', { userId }).then(
        (res) => {
          this.details = res.data
        },
      )
    },
    resetPwd(e, row) {
      e && e.stopPropagation()
      this.$confirm('确认要重置密码？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          axios.post('platform/user/resetPassword/' + row.id).then(
            (res) => {
              this.$alert(
                '重置成功\n\r 新密码为：' +
                  res.data.passWord,
              )
            },
          )
        })
        .catch(() => {})
    },
    enableChange(val, row) {
      axios.post('platform/user/setEnableStatus', {
        enable: val,
        userId: row.id,
      }).then((res) => {
        this.$message.success(res.message)
        this.getList()
      })
    },
    bindChange(row) {
      if (!this.roleShow('lock_device')) {
        this.$message.warning('暂无操作权限')
        return
      }

      axios.post('platform/user/setBindingStatus', {
        bindStatus: !row.bindStatus,
        userId: row.id,
      }).then((res) => {
        this.$message.success(res.message)
        this.getList()
      })
    },
    setempNo(id) {
      for (const iterator of this.employee) {
        if (iterator.id === id) {
          this.addcurrencyform.empNumber =
            iterator.empNumber
          break
        }
      }
    },
    search() {
      this.currentPage = 1
      this.getList(1)
    },
    currentTabFn(val) {
      if (val.row) {
        this.formId = val.row.id
        this.getRoleList(val.row.id)
      }
    },
    // 修改新增
    async addDialog(i, v = null, e) {
      e && e.stopPropagation()
      console.log('addDialog')
      getOptionData(['employee'])

      if (i === 2) {
        if (v) this.formId = v.id
        if (!this.formId) {
          return this.$message('请勾选至少一条记录')
        }
        axios.get('platform/user/axios.get', {
          id: v.id,
        }).then((res) => {
          const funcRoleIds = []
          const dataRoleIds = []
          if (res.data.roleIds) {
            const roleIds =
              res?.data?.roleIds.split(',') || []
            for (const iterator of roleIds) {
              const item = this.roleList.find(
                (item) => item.id === iterator,
              )
              if (item) {
                if (item.type === 'FUNCTION_ROLE') {
                  funcRoleIds.push(Number(iterator))
                } else {
                  dataRoleIds.push(Number(iterator))
                }
              }
            }
          }

          this.addcurrencyform = {
            ...res.data,
            funcRoleIds,
            dataRoleIds,
          }
          this.dialogVisible = true
        })
      } else {
        this.addcurrencyform = JSON.parse(
          JSON.stringify(this.addcurrencyform2),
        )
        this.dialogVisible = true
      }
      this.is_title = i
      this.$nextTick(() => {
        this.$refs.addcurrencyform &&
          this.$refs.addcurrencyform.clearValidate()
      })
    },
    addUser() {
      if (this.is_title === 1) {
        this.addSection()
      } else {
        this.upSection()
      }
    },
    setpaginationOptions(opt) {
      for (const key in opt) {
        this.paginationOptions[key] = opt[key]
      }
      this.getList()
    },
    // 查询
    getList() {
      const { pageSize, currentPage } =
        this.paginationOptions
      axios.post('platform/user/list_page', {
        pageSize,
        currentPage,
        ...this.searchForm,
      }).then((res) => {
        if (res.code === 200) {
          this.sourceData = res.data.records
          this.paginationOptions.total = res.data.total
          if (this.sourceData.length > 0) {
            this.$nextTick(() => {
              let row
              if (this.formId) {
                row = this.sourceData.find(
                  (item) => item.id === this.formId,
                )
              } else {
                row = this.sourceData[0]
              }
              this.getRoleList(row.id)
            })
          }
        } else {
          this.$alert(res.message, '错误提示', {
            dangerouslyUseHTMLString: true,
          })
        }
      })
    },

    // 修改
    upSection() {
      const url = 'platform/user/update'
      this.$refs.addcurrencyform.validate((valid) => {
        if (valid) {
          const data = JSON.parse(
            JSON.stringify(this.addcurrencyform),
          )
          let roleIds =
            this.addcurrencyform.funcRoleIds.concat(
              this.addcurrencyform.dataRoleIds,
            )
          roleIds = roleIds.join()
          data.roleIds = roleIds
          axios.post(url, data).then((res) => {
            if (res.code === 200) {
              this.dialogVisible = false
              this.$message({
                message: '修改成功',
                type: 'success',
              })
              this.getList(this.currentPage)
            } else {
              this.$alert(res.message, '错误提示', {
                dangerouslyUseHTMLString: true,
              })
            }
          })
        }
      })
    },
    // 新增
    addSection() {
      const url = 'platform/user/add'
      this.$refs.addcurrencyform.validate((valid) => {
        if (valid) {
          const data = JSON.parse(
            JSON.stringify(this.addcurrencyform),
          )
          let roleIds =
            this.addcurrencyform.funcRoleIds.concat(
              this.addcurrencyform.dataRoleIds,
            )
          roleIds = roleIds.join()
          data.roleIds = roleIds
          axios.post(url, data).then((res) => {
            if (res.code === 200) {
              this.dialogVisible = false
              this.$alert(
                '添加成功\n\r 用户密码为：' +
                  res.data.passWord,
              )
              // this.$message({
              //   message: "添加成功",
              //   type: "success"
              // });
              this.getList(this.currentPage)
            } else {
              this.$alert(res.message, '错误提示', {
                dangerouslyUseHTMLString: true,
              })
            }
          })
        }
      })
    },
    // 删除
    deleteSection(v) {
      let arr = []
      if (v) arr.push(v)
      else arr = this.select
      const leng = arr.length
      if (leng === 0) {
        return this.$message('请勾选至少一条记录')
      }
      let ids = []
      ids = arr.map((v) => {
        return v.id
      })
      ids = ids.join()
      this.$confirm('确定删除选中的信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          axios.get('platform/user/delete', {
            ids: ids,
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.getList(this.currentPage)
            } else {
              this.$alert(res.message, '错误提示', {
                dangerouslyUseHTMLString: true,
              })
            }
          })
        })
        .catch(() => {})
    },
  },
}
</script>
<style scoped>
.circle {
  display: inline-block;
  height: 10px;
  width: 10px;
  border-radius: 5px;
  margin-right: 5px;
}
.my-table >>> .first {
  background-color: red !important;
  color: #fff !important;
}
</style>
