<template>
  <section class="card-height-full card-flex-1 card-flex-column">
    <a-row :gutter="8" class="card-height-full card-flex-1">
      <a-col :xs="24" :sm="24" :md="6" :lg="5" :xl="5" :xxl="4" class="card-flex-column card-height-full card-full-left">
        <a-card :bordered="false" class="card-padding card-flex-1">
          <org-tree ref="orgTree" :orgOptions="orgOptions" @select="clickOrgNode" />
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="24" :md="18" :lg="19" :xl="19" :xxl="20" class="card-flex-column card-height-full card-full-right">
        <a-card class="search-card-class">
          <a-form
            layout="inline"
            labelAlign="right"
            @keydown.enter.native="handleQuery"
          >
            <a-row :gutter="[16, 16]">
              <a-col :md="6" :sm="24">
                <a-form-item label="登入账号">
                  <a-input v-model="queryParam.loginName" placeholder="请输入登入账号" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="手机号">
                  <a-input v-model="queryParam.mobilePhone" placeholder="请输入手机号" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="用户姓名">
                  <a-input v-model="queryParam.userName" placeholder="请输入用户姓名" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                  <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                  <a-button @click="resetQuery"><a-icon type="redo" />重置</a-button>
                  <a @click="toggleAdvanced" style="margin-left: 8px"
                    >{{ advanced ? '收起' : '展开' }}<a-icon :type="advanced ? 'up' : 'down'" />
                  </a>
              </a-col>
            </a-row>
            <a-row v-if="advanced" :gutter="[16, 16]">
              <a-col :md="6" :sm="24">
                <a-form-item label="状态" prop="status">
                  <a-select
                    show-search
                    option-filter-prop="label"
                    placeholder="请选择状态"
                    v-model="queryParam.status"
                    allow-clear
                  >
                    <a-select-option
                      v-for="(d, index) in statusOptions"
                      :key="index"
                      :value="d.dictValue"
                      :label="d.dictLabel"
                      >{{ d.dictLabel }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="创建时间">
                  <a-range-picker
                    v-model="dateRange"
                    valueFormat="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <a-card :bordered="false" class="table-card-class">
          <!-- <a-row :gutter="24">
            <a-col :span="24"> -->
          <!-- 条件搜索 -->
          <!-- <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="用户姓名">
                    <a-input v-model="queryParam.userName" placeholder="请输入" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="手机号">
                    <a-input v-model="queryParam.mobilePhone" placeholder="请输入" allow-clear />
                  </a-form-item>
                </a-col>
                <template v-if="advanced">
                  <a-col :md="8" :sm="24">
                    <a-form-item label="状态" prop="status">
                      <a-select show-search option-filter-prop="label" placeholder="请选择状态" v-model="queryParam.status" style="width: 100%" allow-clear>
                        <a-select-option v-for="(d, index) in statusOptions" :key="index" :value="d.dictValue" :label="d.dictLabel">{{
                          d.dictLabel
                        }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-item label="创建时间">
                      <a-range-picker
                        style="width: 100%"
                        v-model="dateRange"
                        valueFormat="YYYY-MM-DD"
                        format="YYYY-MM-DD"
                        allow-clear
                      />
                    </a-form-item>
                  </a-col>
                </template>
                <a-col :md="(!advanced && 8) || 24" :sm="24">
                  <span
                    class="table-page-search-submitButtons"
                    :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
                  >
                    <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                    <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
                    <a @click="toggleAdvanced" style="margin-left: 8px">
                      {{ advanced ? '收起' : '展开' }}
                      <a-icon :type="advanced ? 'up' : 'down'" />
                    </a>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div> -->
          <!-- 操作 -->
          <div class="table-operations">
            <a-button type="dashed" shape="circle" :loading="loading" icon="reload" @click="getList" cl />
            <a-button type="primary" @click="$refs.createForm.handleAdd()" v-hasPermi="['system:user:add']">
              <a-icon type="plus" />新增
            </a-button>
            <!-- <a-button
                type="primary"
                :disabled="single"
                @click="$refs.createForm.handleUpdate(undefined, ids)"
                v-hasPermi="['system:user:edit']"
              >
                <a-icon type="edit" />修改
              </a-button> -->
            <a-button class="delete-btn" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">
              <a-icon type="delete" />删除
            </a-button>
          </div>
          <!-- 增加修改 -->
          <!-- 创建/编辑用户,单独封装了组件 -->
          <create-form
            ref="createForm"
            :orgOptions="orgOptions"
            :statusOptions="statusOptions"
            :sexOptions="sexOptions"
            @ok="getList"
            @select-tree="getTreeselect"
          />
          <!-- 批量删除 -->
          <delete-form ref="DeleteFormRef" @delete-users="deleteUsers" />
          <!-- 修改密码抽屉 -->
          <reset-password ref="resetPassword" />
          <!-- 数据展示 -->
          <a-table
            :loading="loading"
            :scroll="{ x: '1400px', y: innerHeight }"
            rowKey="userId"
            :columns="columns"
            :data-source="list"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :pagination="false"
          >
            <span slot="status" slot-scope="text, record">
              <a-popconfirm
                ok-text="确认"
                cancel-text="取消"
                :icon="false"
                @confirm="confirmHandleStatus(record)"
                @cancel="cancelHandleStatus(record)"
              >
                <template slot="title">
                  <p style="margin: 0 auto">确认{{ record.status === '1' ? '启用' : '关闭' }}该用户?</p>
                </template>
                <a-switch checked-children="开" un-checked-children="关" :checked="record.status == 0" />
              </a-popconfirm>
            </span>
            <span slot="orgs" slot-scope="text, record">
              <span v-for="(item,index) in record.orgs" :key="index">
                {{item.orgName}}
              </span>
            </span>
            <span slot="createTime" slot-scope="text, record">
              {{ record.createTime }}
            </span>
            <span slot="operation" slot-scope="text, record">
              <a @click="$refs.createForm.handleUpdate(record, undefined)" v-hasPermi="['system:user:edit']">
                <!-- <a-icon type="edit" /> -->
                修改
              </a>
              <a-divider type="vertical" v-if="record.userId !== 1" v-hasPermi="['system:user:remove']" />
              <a
                @click="handleDelete(record)"
                v-if="record.userId !== 1"
                v-hasPermi="['system:user:remove']"
                class="reset-or-delete-link"
              >
                <!-- <a-icon type="delete" /> -->
                删除
              </a>
              <a-divider type="vertical" v-hasPermi="['system:user:resetPwd']" />
              <a
                @click="$refs.resetPassword.handleResetPwd(record)"
                v-hasPermi="['system:user:resetPwd']"
                class="reset-or-delete-link"
              >
                <!-- <a-icon type="key" /> -->
                重置
              </a>
            </span>
          </a-table>
          <!-- 分页 -->
          <a-pagination
            show-size-changer
            show-quick-jumper
            :current="queryParam.pageNum"
            :total="total"
            :page-size="queryParam.pageSize"
            :showTotal="(total) => `共 ${total} 条`"
            @showSizeChange="onShowSizeChange"
            @change="changeSize"
          />
          <!-- </a-col>
          </a-row> -->
        </a-card>
      </a-col>
    </a-row>
  </section>
</template>

<script>
import { listUser, delUser, exportUser, changeUserStatus } from '@/api/system/user'
import { addDateRange } from '@/utils/util'
import { treeselect } from '@/api/system/org'
import ResetPassword from './modules/ResetPassword'
import CreateForm from './modules/CreateForm'
import DeleteForm from './modules/DeleteForm'
import config from '@/config/defaultSettings'
import OrgTree from './modules/OrgTree'
import { mixin, mixinDevice } from '@/utils/mixin'
export default {
  name: 'User',
  mixins: [mixin, mixinDevice],
  components: {
    ResetPassword,
    CreateForm,
    OrgTree,
    DeleteForm,
  },
  data() {
    return {
      list: [],
      selectedRowKeys: [],
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      loading: false,
      total: 0,
      // 状态数据字典
      statusOptions: [],
      sexOptions: [],
      // 组织树选项
      orgOptions: [
        {
          value: '0',
          label: '',
          children: [],
        },
      ],
      // 日期范围
      dateRange: [],
      queryParam: {
        pageNum: 1,
        pageSize: 20,
        userName: undefined,
        mobilePhone: undefined,
        status: undefined,
        orgId: undefined,
      },
      columns: [
        {
          title: '用户编号',
          dataIndex: 'userId',
          align: 'center',
        },
        {
          title: '登入账号',
          dataIndex: 'loginName',
          align: 'center',
        },
        {
          title: '手机号',
          dataIndex: 'mobilePhone',
          align: 'center',
        },
        {
          title: '用户姓名',
          dataIndex: 'userName',
          align: 'center',
        },
        {
          title: '组织',
          dataIndex: 'orgs',
          scopedSlots: { customRender: 'orgs' },
          align: 'center',
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
          align: 'center',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
          align: 'center',
          width: 180,
          fixed: 'right',
        },
      ],
    }
  },
  filters: {},
  computed: {
    innerHeight() {
      const h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
      return h - 365
    },
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.result
    })
    this.getDicts('sys_user_sex').then((response) => {
      this.sexOptions = response.result
    })
  },
  methods: {
    /** 查询定时任务列表 */
    getList() {
      this.loading = true
      listUser(addDateRange(this.queryParam, this.dateRange)).then((response) => {
        this.list = response.result.data
        this.total = response.result.totalCount
        this.loading = false
      })
    },
    /** 查询组织下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.orgOptions = response.result
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParam = {
        pageNum: 1,
        pageSize: 20,
        userName: undefined,
        mobilePhone: undefined,
        status: undefined,
        orgId: undefined,
      }
      this.handleQuery()
    },
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = selectedRowKeys
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    clickOrgNode(orgId) {
      this.queryParam.orgId = orgId
      this.getList()
    },
    /* 任务状态修改 */
    confirmHandleStatus(row) {
      const text = row.status === '1' ? '启用' : '关闭'
      row.status = row.status === '0' ? '1' : '0'
      changeUserStatus(row.userId, row.status)
        .then(() => {
          this.$message.success(text + '成功', 3)
        })
        .catch(function () {
          this.$message.error(text + '异常', 3)
        })
    },
    cancelHandleStatus(row) {},
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this
      const userIds = row.userId || this.ids
      if (row.userId) {
        this.$confirm({
          title: '确认删除所选中数据?',
          content: '当前选中编号为' + userIds + '的数据',
          onOk() {
            return that.deleteUsers(userIds)
          },
          onCancel() {},
        })
      } else {
        this.$refs.DeleteFormRef.openDeleteForm(userIds)
      }
    },
    deleteUsers(userIds) {
      delUser(userIds).then(() => {
        this.onSelectChange([], [])
        this.getList()
        this.$message.success('删除成功', 3)
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk() {
          return exportUser(that.queryParam).then((response) => {
            that.download(response.msg)
            that.$message.success('导出成功', 3)
          })
        },
        onCancel() {},
      })
    },
  },
}
</script>
<style lang="less" scoped>
.table-operations {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 5px;
 
}
.ant-pagination{
  display: flex;
  justify-content: flex-end;
  margin-bottom: 5px;
  margin-top: 5px;
}

/deep/ .ant-card-body {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.ant-card-body .ant-table-wrapper {
  flex: 1;
}
</style>
