<template>
  <admin-layout>
    <admin-todo-list title="筛选条件" filters icon="filter">
      <template #options>
        <a-button type="dashed" @click="resetQuery" icon="reload">重置</a-button>
        <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
      </template>
      <HSearchForm label="账号">
        <a-input placeholder="输入账号模糊查询" v-model="queryParam.username" />
      </HSearchForm>
      <HSearchForm label="性别">
        <a-select v-model="queryParam.sex" placeholder="请选择性别" style="width: 100%">
          <a-select-option value="">请选择</a-select-option>
          <a-select-option value="1">男</a-select-option>
          <a-select-option value="2">女</a-select-option>
        </a-select>
      </HSearchForm>
      <HSearchForm label="真实名字">
        <a-input placeholder="请输入真实名字" v-model="queryParam.realname" />
      </HSearchForm>
      <HSearchForm label="手机号码">
        <a-input placeholder="请输入手机号码查询" v-model="queryParam.phone" />
      </HSearchForm>
      <HSearchForm label="状态">
        <a-select v-model="queryParam.status" placeholder="请选择" style="width: 100%">
          <a-select-option value="">请选择</a-select-option>
          <a-select-option value="1">正常</a-select-option>
          <a-select-option value="2">冻结</a-select-option>
        </a-select>
      </HSearchForm>
    </admin-todo-list>

    <admin-todo-list title="数据列表" icon="table">
      <template #options>
        <a-button v-if="isDisabledAuth('user:add')" @click="handleAdd" type="primary" icon="plus">添加用户</a-button>
        <a-button
          v-if="isDisabledAuth('user:export')"
          type="primary"
          icon="download"
          @click="handleExportXls('用户信息')"
        >
          导出
        </a-button>
        <a-button v-if="isDisabledAuth('user:getSuperCode')" @click="handleValid" type="primary" icon="security-scan">
          通用验证码
        </a-button>
        <!--<a class="ml20" @click="downloadTheTemplate('用户模板')">模板下载</a>&nbsp;&nbsp;-->
        <!--<a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
        <!--<a-button type="primary" icon="import">导入</a-button>-->
        <!--</a-upload>-->
        <a-dropdown
          v-if="
            selectedRowKeys.length > 0 &&
            (isDisabledAuth('user:batchDel') || isDisabledAuth('user:batchFreeze') || isDisabledAuth('user:batchThaw'))
          "
        >
          <a-menu slot="overlay" @click="handleMenuClick">
            <a-menu-item key="1" v-if="isDisabledAuth('user:batchDel')">
              <a-icon type="delete" @click="batchDel" />
              删除
            </a-menu-item>
            <a-menu-item key="2" v-if="isDisabledAuth('user:batchFreeze')">
              <a-icon type="lock" @click="batchFrozen('2')" />
              冻结
            </a-menu-item>
            <a-menu-item key="3" v-if="isDisabledAuth('user:batchThaw')">
              <a-icon type="unlock" @click="batchFrozen('1')" />
              解冻
            </a-menu-item>
          </a-menu>
          <a-button class="ml10">
            批量操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </template>
      <a-table
        ref="table"
        bordered
        size="small"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="pagination"
        :loading="tableLoading"
        :scroll="{ x: 1280 }"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handlePaginationChange"
      >
        <template slot="avatarslot" slot-scope="text, record">
          <div class="anty-img-wrap">
            <a-avatar shape="square" :src="getAvatarView(record.avatar)" icon="user" />
          </div>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="isDisabledAuth('user:edit')" class="mr5" @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown
            class="mr5"
            v-if="
              isDisabledAuth('user:details') ||
              isDisabledAuth('user:password') ||
              isDisabledAuth('user:del') ||
              (record.status === 1 && isDisabledAuth('user:freeze')) ||
              (record.status === 2 && isDisabledAuth('user:thaw')) ||
              isDisabledAuth('user:agent')
            "
          >
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item v-if="isDisabledAuth('user:details')">
                <a href="javascript:;" @click="handleView(record)">详情</a>
              </a-menu-item>
              <a-menu-item v-if="isDisabledAuth('user:password')">
                <a href="javascript:;" @click="handleChangePassword(record.username)">密码</a>
              </a-menu-item>

              <a-menu-item v-if="isDisabledAuth('user:del')">
                <a-popconfirm placement="left" title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item v-if="record.status === 1 && isDisabledAuth('user:freeze')">
                <a-popconfirm
                  placement="left"
                  title="确定冻结吗?"
                  @confirm="() => handleFrozen(record.id, 2, record.username)"
                >
                  <a>冻结</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item v-if="record.status === 2 && isDisabledAuth('user:thaw')">
                <a-popconfirm
                  placement="left"
                  title="确定解冻吗?"
                  @confirm="() => handleFrozen(record.id, 1, record.username)"
                >
                  <a>解冻</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item v-if="isDisabledAuth('user:agent')">
                <a href="javascript:;" @click="handleAgentSettings(record.username)">代理人</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </admin-todo-list>

    <user-modal ref="modalEditRef" @ok="handleOk"></user-modal>
    <user-modal ref="modalViewRef" @ok="handleOk"></user-modal>

    <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>

    <sys-user-agent-modal ref="sysUserAgentModal"></sys-user-agent-modal>
  </admin-layout>
</template>

<script>
import UserModal from './modules/user/UserModal'
import PasswordModal from './modules/user/PasswordModal'
import { frozenBatch } from './api/services/user'
import { PageListMixin } from '@/mixins/PageListMixin'
import SysUserAgentModal from './modules/user/SysUserAgentModal'
import { downFile, postAction } from '@/api/manage'
import HSearchForm from '@/components/hrhx/form/HSearchForm'

export default {
  name: 'UserManageList',
  components: {
    HSearchForm,
    SysUserAgentModal,
    UserModal,
    PasswordModal
  },
  mixins: [PageListMixin],
  data() {
    return {
      description: '这是用户管理页面',
      queryParam: {},
      columns: Object.freeze([
        {
          title: '用户账号',
          align: 'center',
          dataIndex: 'username',
          width: 120
        },
        {
          title: '真实姓名',
          align: 'center',
          width: 100,
          dataIndex: 'realname'
        },
        {
          title: '头像',
          align: 'center',
          width: 120,
          dataIndex: 'avatar',
          scopedSlots: { customRender: 'avatarslot' }
        },

        {
          title: '性别',
          align: 'center',
          width: 80,
          dataIndex: 'sex_dictText',
          sorter: true
        },
        {
          title: '生日',
          align: 'center',
          width: 180,
          dataIndex: 'birthday'
        },
        {
          title: '手机号码',
          align: 'center',
          width: '120px',
          dataIndex: 'phone'
        },
        {
          title: '邮箱',
          align: 'center',
          dataIndex: 'email'
        },
        {
          title: '状态',
          align: 'center',
          width: 80,
          dataIndex: 'status_dictText'
        },
        /* {
           title: '创建时间',
           align: "center",
           width: 150,
           dataIndex: 'createTime',
           sorter: true
         },*/
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: '120px',
          fixed: 'right'
        }
      ]),
      selectedRowKeys: [],
      interface: {
        imgerver: window._CONFIG['resourcesUrl'],
        syncUser: '/process/extActProcess/doSyncUser',
        list: '/sys/user/list',
        delete: '/sys/user/delete',
        deleteBatch: '/sys/user/deleteBatch',
        exportXlsUrl: '/sys/user/exportXls',
        importExcelUrl: 'sys/user/importExcel',
        excelTemplateUrl: '/sys/user/downLoadTemplated'
      }
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domainURL']}/${this.interface.importExcelUrl}`
    }
  },
  created() {
    if (!this.disableMixinCreated) {
      this.queryParam.orgCode = this.$store.getters.userInfo.orgCode
      this.loadData(1)
    }
  },
  methods: {
    getAvatarView: function (avatar) {
      return this.interface.imgerver + avatar
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },

    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },

    batchFrozen: function (status) {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return false
      } else {
        let ids = ''
        let that = this
        let isAdmin = false
        that.selectionRows.forEach(function (row) {
          if (row.username === 'admin') {
            isAdmin = true
          }
        })
        if (isAdmin) {
          that.$message.warning('管理员账号不允许此操作,请重新选择！')
          return
        }
        that.selectedRowKeys.forEach(function (val) {
          ids += val + ','
        })
        that.$confirm({
          title: '确认操作',
          content: '是否' + (status === 1 ? '解冻' : '冻结') + '选中账号?',
          onOk: function () {
            frozenBatch({ ids: ids, status: status }).then(res => {
              if (res.code === '200') {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    handleMenuClick(e) {
      if (e.key === 1) {
        this.batchDel()
      } else if (e.key === 2) {
        this.batchFrozen(2)
      } else if (e.key === 3) {
        this.batchFrozen(1)
      }
    },
    handleFrozen: function (id, status, username) {
      let that = this
      //TODO 后台校验管理员角色
      if ('admin' === username) {
        that.$message.warning('管理员账号不允许此操作！')
        return
      }
      frozenBatch({ ids: id, status: status }).then(res => {
        if (res.code === '200') {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleChangePassword(username) {
      this.$refs.passwordmodal.show(username)
    },
    handleAgentSettings(username) {
      this.$refs.sysUserAgentModal.agentSettings(username)
      this.$refs.sysUserAgentModal.title = '用户代理人设置'
    },
    passwordModalOk() {
      //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
    },
    /**
     * 为所有的用户提供统一的验证码
     */
    handleValid() {
      console.log('生成验证吗')
      postAction('/sys/getValidCode').then(res => {
        console.log(res)
        const h = this.$createElement
        this.$info({
          title: '验证码通知',
          content: h('div', {}, [
            h('p', `通用验证码是：${res.value}，请谨慎告知相关人员`),
            h('p', `重新生成后，该验证码会失效`)
          ])
        })
      })
    },
    //Excel模板下载
    downloadTheTemplate(fileName) {
      //ExcelConfigurationTemplate
      let param = {}
      downFile(this.interface.excelTemplateUrl, param).then(data => {
        console.info('----' + data)
        console.info('----' + data.data)
        if (!data) {
          this.$message.warning('模板文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    }
  }
}
</script>
<style scoped>
.ant-drawer-left.ant-drawer-open,
.ant-drawer-right.ant-drawer-open {
  width: 100%;
  height: 100% !important;
  -webkit-transition: -webkit-transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
  transition: -webkit-transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
  transition: transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
  transition: transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1), -webkit-transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
}
</style>
