<template>
  <div class="wraper">
    <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>
        <el-button
          native-type="submit"
          type="primary"
          @click="search()"
          icon="el-icon-search"
        >
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="addDialog(1)"
          >新增</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" v-loading="loading">
      <table-vue
        :sourceData="sourceData"
        ref="multipleTable"
        :tableColumns="usersTableColumns"
        @currentChange="currentTabFn"
        :rowClassName="cellClass"
        @selectionChange="selectionChange"
      ></table-vue>
    </div>
    <div class="pagination">
      <el-pagination
        layout="sizes, total, prev, pager, next, jumper"
        background
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="sizeChange"
        @current-change="onCurrentChange"
      >
      </el-pagination>
    </div>

    <!-- 弹出层 -->
    <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="account"
          required
        >
          <el-input
            style="width: 164px"
            v-model="addcurrencyform.account"
            placeholder="请输入登录账号"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="" required>
          <el-input
            style="width: 164px"
            v-model="addcurrencyform.realName"
            placeholder="请输入登录账号"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <div style="width: 164px" placeholder="请选择">
            <el-radio
              :label="true"
              v-model="addcurrencyform.enable"
              >是</el-radio
            >
            <el-radio
              :label="false"
              v-model="addcurrencyform.enable"
              >否</el-radio
            >
          </div>
        </el-form-item>
        <el-form-item label="功能角色" prop="funcRoleIds">
          <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>
      <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>
  </div>
</template>
<script>
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: [],
      total: 0,
      pageSize: 100,
      currentPage: 1,
      loading: false,
    }
  },
  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: 'account',
          width: '',
          align: 'left',
          render: (item) => (
            <span>
              <i
                class="circle"
                style={{
                  backgroundColor: item.enable
                    ? 'green'
                    : 'red',
                }}
              ></i>
              {item.account}
            </span>
          ),
        },
        {
          label: '姓名',
          key: 'realName',
          width: '',
        },

        { label: '功能角色', key: 'functionNames' },
        { label: '数据角色', key: 'dataNames' },

        {
          label: '相关操作',
          key: '',
          fixed: 'right',
          width: '',
          render: (item) => (
            <div>
              <span title="编辑" class="icon-view ">
                <i
                  class="el-icon-edit-outline"
                  style="color:#E6A23C"
                  onClick={(e) =>
                    this.addDialog(2, item, e)
                  }
                ></i>
              </span>
              <span title="重置密码" class="icon-view ">
                <i
                  style="color:#67C23A"
                  class="el-icon-refresh-left"
                  onClick={(e) => this.resetPwd(e, item)}
                ></i>
              </span>
              <span title="删除" class="icon-view ">
                <i
                  style="color:#F56C6C"
                  class="el-icon-delete"
                  onClick={(e) => this.deleteSection(item)}
                ></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: {
    onCurrentChange() {},
    sizeChange() {},
    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()
    },
    authorizationDel(item, e) {
      e && e.stopPropagation()
      this.$confirm('确定删除选中的信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {})
        .catch(() => {})
    },

    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) {
      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
      }
    },
    // 修改新增
    async addDialog(i, v = null, e) {
      e && e.stopPropagation()
      if (i === 2) {
        if (v) this.formId = v.id
        if (!this.formId) {
          return this.$message('请勾选至少一条记录')
        }
        axios
          .get('platform/user/get', {
            params: {
              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() {
      this.loading = true
      const { pageSize, currentPage } =
        this.paginationOptions
      axios
        .post('platform/user/list_page', {
          pageSize,
          currentPage,
          ...this.searchForm,
        })
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            this.sourceData = res.data.records
            this.paginationOptions.total = res.data.total
          } 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.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', {
              params: {
                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>
.wraper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table_wrap {
  flex: 1;
}
.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>
