<template>
<div class="routerWapper">
	<div v-if="$route.name == 'people'&& $permission('000904')" class="layoutMargin layoutPadding" >
		<a-form class="protalForm" :form="searchForm">
			<a-row type="flex" class="formItemLine" :justify="simpleSearchForm?'end':'space-between'" align='middle' :gutter="simpleSearchForm?16:0">
        <a-col span="6" v-if="!simpleSearchForm">
					<a-form-item class='formItem' label="手机号" :label-col="formItemLabelCol" :wrapper-col="formItemWrapperCol">
						<a-input placeholder="请输入手机号" v-decorator="['phone_l']" />
					</a-form-item>
				</a-col>
				<a-col span="6" v-if="!simpleSearchForm">
					<a-form-item label="角色名称" :label-col="formItemLabelCol" :wrapper-col="formItemWrapperCol">
						<a-select mode="multiple" placeholder="请选择" allowClear v-decorator="['roleIds_in']" >
              <a-select-option
                v-for="option in roleList"
                :key="option.id"
                :value="option.id">
                {{option.roleName}}
              </a-select-option>
            </a-select>
					</a-form-item>
				</a-col>
				
			</a-row>
      <a-col span="24" class="algin-right">
					<a-button @click="reset" html-type="submit">重置</a-button>
					<a-button type="primary" @click="search" html-type="submit">搜索</a-button>
          <!-- <a-button type="primary" v-if='simpleSearchForm' @click="showMoreSearch">更多搜索</a-button>
          <a-button type="primary" v-if='!simpleSearchForm' @click="closeMoreSearch">简单搜索</a-button> -->
			</a-col>
		</a-form>
		<p class="gayLine noline"></p>
		<div class='portalTableOperates'>
			<a-button icon='plus' v-if="$permission('00090403')" type="primary" @click='handleAdd'>添加账户</a-button>
		</div>
		<a-table size='small' class="portalTable" :columns="columns" :dataSource="dataTable" rowKey='id' :pagination='pagination'>
			<span slot="action" slot-scope="text, record">
				<span class="actionBtn" v-if="$permission('00090401')" @click="viewBtn(record)">查看<a-divider type="vertical" /></span>
				<!-- <span class="actionBtn" v-if="record.status==0 && $permission('P03102')" @click="$router.push({name: '/systemManagement/administrator/distribution',query:{id:record.id}})">权限分配</span> -->
				<a-dropdown >
					<span class="actionBtn" v-if="record.status!=8" > 更多
						<a-icon type="down" />
          </span>
					<a-menu slot="overlay">
						<!-- <a-menu-item v-if="$permission('00090401')" class="actionBtn" key="4"> 重置密码
						</a-menu-item> -->
						<!-- <a-menu-item class="actionBtn" key="2" v-if="$permission('S00011416')"> 禁用 </a-menu-item> -->
						<!-- <a-menu-item class="actionBtn" v-if="$permission('00090405')" key="1"  @click='(event)=>{showOpeations(event.key,record)}'> 启用 </a-menu-item>
						<a-menu-item class="actionBtn" v-if="$permission('00090406')" key="3"  @click='(event)=>{showOpeations(event.key,record)}'> 注销 -->
						<!-- </a-menu-item> -->
            <a-menu-item class="actionBtn" v-if="$permission('00090402')" @click="handleEdit(record)"> 修改
						</a-menu-item>
					</a-menu>
				</a-dropdown>
			</span>

      <span slot="userType" slot-scope="text" align="center"> 
        {{getUserType(text)}}
      </span>

      <span slot="status" slot-scope="text, record">
        <userStatus :status="record.status||'0'" />
			</span>
      <span slot="phone" slot-scope="text, record">
        <span>{{record.phone}}</span>
			</span>
		</a-table>

		<resetPassword :resetPwdShow="resetPwdShow" @on-cancel="handleCancel" ref="reset" @on-ok="handleResetOk"></resetPassword>
	</div>
  <RouterWapper v-else></RouterWapper>
</div>
</template>
<script>
import userStatus from '@/views/components/user-status'
import userRole from '@/views/components/user-role'
import resetPassword from '@/views/components/resetPassword'
import { encryptDes } from '@/util/des-cryptojs'

export default {
  components: {
    userStatus,
    resetPassword,
    userRole,
  },
  props: {
    personType: {
      type: String,
    }
  },
  data() {
    return {
      roleList: [],
      // 展示、收取简单搜索开关，true为简单搜索
      simpleSearchForm: false,
      colSpe: {
        labelCol: {
          span: 8
        },
        wrapperCol: {
          span: 16
        },
      },
      pagination: {
        pageSize: 10,
        total: 0,
        current: 1,
        defaultCurrent: 1,
        showQuickJumper: true,
        onChange: this.pageChange
      },
      statusList: [0],
      searchForm: this.$form.createForm(this),
      defaultValue: '',
      dataTable: [],
      plainOptions: [
        {
          text: '正常',
          value: '1'
        }, 
        {
          text: '已注销',
          value: '9'
        }
      ],
      opeation: {
        title: '',
        tips: '',
        type: '',
        item: null
      },
      treeData: [],
      resetPwdShow: false
    }
  },
  computed: {
    formItemLabelCol(){
      let labelCol = {}
      if(this.simpleSearchForm){
        labelCol = { span: 0 }
      }else{
        labelCol = { span: 8 }
      }
      return labelCol
    },
    formItemWrapperCol(){
      let wrapperCol = {}
      if(this.simpleSearchForm){
        wrapperCol = { span: 24 }
      }else{
        wrapperCol = { span: 16 }
      }
      return wrapperCol
    },
    columns(){
      return [
        {
          title: '账号',
          dataIndex: '',
          align: 'center',
          key: '',
          width: '10%',
          scopedSlots: {
            customRender: 'phone',
          },
        },  
        {
          title: '身份',
          align: 'center',
          dataIndex: 'type',
          key: 'type',
          width: '10%',
          scopedSlots: {
            customRender: 'userType',
          },
        },  
        {
          title: '角色',
          dataIndex: 'roleNames',
          align: 'center',
          key: 'roleNames',
          width: '13%',
          scopedSlots: {
            customRender: 'roleIds',
          },
        }, 
        {
          title: '手机号',
          align: 'center',
          dataIndex: 'phone',
          key: 'phone',
          width: '20%',
        }, 
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: '12%',
          scopedSlots: {
            customRender: 'action',
          },
        }
      ]
    }
  },
  watch: {
    $route(cur) {
      if (cur) {
        this.getSearchParams()
        this.getRoleList()
      }
    }, 
  },
  mounted() {
    if(this.$route.name == 'people'){
      this.$nextTick(function () {
        this.getSearchParams()
        this.getRoleList()
      })

    }
  },
  methods: {
    // 查询角色列表
    getRoleList(){
      this.$ajax.get({
        url: this.$api.GET_ROLE_LIST,
        params: {
          pageSize: 10000,
        }
      }).then(res => {
        if(res.code === '200'){
          this.roleList= this.$com.confirm(res, 'data.content', [])
        }else{
          this.$message.error(res.msg)
        }

      })
    },
    /**
     * 从vuex中或已存储的搜索条件，判断此条件是否为当前路由的 。如果是则使用
     */
    getSearchParams(){
      const searchParams = !this.$store.state.listSearchParams?null:this.$store.state.listSearchParams[this.$route.name]
      if(!!searchParams && !!searchParams.routeName && (this.$route.name == searchParams.routeName)){
        if(!!searchParams.params){
          Object.keys(searchParams.params).forEach(elem => {
            switch (elem) {
            case 'phone_l':
              this.searchForm.setFieldsValue({ 'phone_l': searchParams.params[elem] })
              break
            // case 'roleIds_in':
            //   console.log(searchParams.params[elem])
            //   this.searchForm.setFieldsValue({ 'roleIds_in': searchParams.params[elem].split(',') })
            //   break
            case 'username_l':
              this.searchForm.setFieldsValue({ 'username_l': searchParams.params[elem] })
              break
            case 'status_in':
              this.searchForm.setFieldsValue({ 'status_in': searchParams.params[elem].split(',') })
              break
            default:
              break
            }
          })
        }
        if(!!searchParams.pagination){
          if(!!searchParams.pagination.current){
            if (searchParams.params.tabName == this.personType) {
              this.pagination.current = searchParams.pagination.current
            }
            this.pagination.pageSize = searchParams.pagination.pageSize
          }
        }
      }
      this.getList()
    },
    /**
     * 处理列表展示的身份类型
     */
    getUserType(UserType){
      let userTypeList =[
        {
          key: '0',
          value: '后台管理员',
        }, {
          key: '1',
          value: '决策人员',
        }, {
          key: '2',
          value: '机构',
        }, {
          key: '3',
          value: '机构人员',
        }, {
          key: '4',
          value: '中介',
        }, {
          key: '5',
          value: '中介人员',
        },
      ]
      for(let i=0;i<userTypeList.length;i++){
        if(!!UserType){
          if(UserType == userTypeList[i].key){
            return userTypeList[i].value
          }
        }else{
          return '暂无'
        }
      }
    },
    //关闭更多搜索
    closeMoreSearch(){
      this.simpleSearchForm = true
    },
    //展示更多搜索
    showMoreSearch(){
      this.simpleSearchForm = false
    },
    //分页
    pageChange(current) {
      this.pagination.current = current
      this.getList()
    },
    // 查询按钮
    search() {
      this.pagination.current = 1
      this.getList()
    },
    // 重置按钮
    reset() {
      this.pagination.current = 1
      this.searchForm.resetFields()

      this.getList()
    },
    // 查询列表
    getList(){
      let searchParms = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        phone_ne: 0
      }
      searchParms = Object.assign({}, searchParms, this.searchForm.getFieldsValue())
      if (searchParms.roleIds_in && searchParms.roleIds_in.length>0) {
        searchParms.roleIds_in = searchParms.roleIds_in.join(',')
      } 

      this.$ajax.get({
        url: this.$api.GET_STAFF_LIST,
        params: searchParms
      }).then(res => { 
        if (res.code == '200') { 
          this.pagination.current = res.data.page
          this.pagination.pageSize = res.data.pageSize
          this.pagination.total = res.data.totalRows
          this.dataTable = this.$com.confirm(res, 'data.content', [])
          //
          // 存储当前页面列表的搜索信息
          //

          this.$com.storeSearchParams(
            this.$route.name,
            this.pagination,
            Object.assign({}, searchParms, {tabName: this.personType})
          )
        } else {
          this.$message.info(res.msg, 10)
        }
      })
    },
    handleAdd() {
      this.$router.push({
        name: 'createStaff',
        query: {
          personType: this.personType
        }
      })
    },
    //跳转详情页面
    viewBtn(record) {
      this.$router.push({
        name: 'staffInfo',
        query: {
          id: record.id,
          personType: this.personType
        }
      })
    },
    //跳转修改页面
    handleEdit(record) {
      this.$router.push({
        name: 'editStaff',
        query: {
          id: record.id,
          // personType:this.$route.query.personType
        }
      })
    },
    showOpeations(key, item) {
      this.opeation.type = key
      this.opeation.item = item
      const vm = this
      switch (key) {
      case '1':
        this.opeation.title = '您确认要启用该账号吗?'
        this.opeation.tips = '启用后，该账号将被允许登录平台'
        break
      case '2':
        this.opeation.title = '您确定要禁用吗？'
        this.opeation.tips = '禁用后，该账号将不被允许登录平台直到再次启用'
        break
      case '3':
        this.opeation.title = '您确认要注销该账号吗？'
        this.opeation.tips = '注销后，该账号将被使用'
        break
      case '4':
        this.opeation.title = '您确认要重置账号密码吗？'
        this.opeation.tips = '重置后，需要使用新密码登录'
        break
      default:
        break
      }
      if (key != 4 && key !=5) {
        this.$modal.confirm({
          title: this.opeation.title,
          content: this.opeation.tips,
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            vm.handleOk()
          },
        })
      } else if(key == 5){
        this.$router.push({ path: '/systemManagement/administrator/distribution',
          query: {
            id: item.id
          }
        })
      }else if(key == 4){
        this.resetPwdShow = true
      }
    },
    handleOk() {
      const key = this.opeation.type
      let apiUrl = ''
      let status = 1
      switch (key) {
      case '1':
      //启用操作
        apiUrl = this.$api.PUT_STAFF_INFO
        status = 1
        break
      case '2':
      // //禁用操作
      //   apiUrl = this.$api.PUT_STAFF_INFO
      //   status= '8'
      //   break
      case '3':
      //注销操作
        apiUrl = this.$api.PUT_STAFF_INFO
        status= '9'

        break
      default:
        break
      }
      this.$ajax.put({
        url: apiUrl,
        params: {
          id: this.opeation.item.id,
          status,
        }
      }).then(res => {
        if (res.code == '200') {
          this.$message.success('操作成功！')
          this.getList()
        }
      })
    },
    handleCancel() {
      this.resetPwdShow = false
      this.$refs.reset.resetForm()
    },
    handleResetOk(values) {
      this.$ajax.put({
        url: this.$api.PUT_STAFF_PWD,
        params: {
          id: this.opeation.item.id,
          pwd: encryptDes(values.newPwd)
        }
      }).then(res => {
        if (res.code === '200') {
          this.$message.success('重置密码成功')
          this.handleCancel()
          this.getList()
        }
      })
    },
  }
}
</script>
<style scoped>
	.opeationTable {
		margin: 10px 0;
	}
  .roleNames{
    width: 120px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>