<template>
  <div class="wrap" v-loading="loading">
    <el-card shadow="hover" class="mgb20">
      <div>
        <div class="flex-center mgb20">
          <p class="hr_tag"></p>
          <span>筛选</span>
        </div>
        <div style="overflow: auto;">
          <el-form label-width="80px">
            <el-row>
              <el-col :span="5">
                <el-form-item label="省份">
                  <el-select v-model="form.provinces" clearable placeholder="请选择省份" @change="getCity"
                    @clear="clearprovince()">
                    <el-option v-for="(item, index) in provinceList" :key="index" :label="item.provinceName"
                      :value="item.provinceId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="城市">
                  <el-select v-model="form.city" clearable placeholder="请选择城市" :disabled="form.provinces ? false : true"
                    @clear="clearcity()" @change="initData">
                    <el-option v-for="(item, index) in cityList" :key="index" :label="item.cityName"
                      :value="item.cityId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="来源">
                  <el-select v-model="form.platformId" clearable placeholder="请选择来源" @change="initData">
                    <el-option v-for="item in platformList" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="学校">
                  <el-select v-model="form.schoolId" clearable filterable placeholder="请选择学校" @change="initData">
                    <el-option v-for="(item, index) in schoolList" :key="index" :label="item.schoolName"
                      :value="item.schoolId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="5">
                                <el-form-item label="角色">
                                    <el-select v-model="form.accountRole" clearable placeholder="请选择角色" @change="initData">
                                        <el-option v-for="(item,index) in accountRoleList" :key="index" :label="item.name" :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col> -->
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="创建时间" class="userRadio">
                  <el-radio-group v-model="form.month">
                    <el-radio v-for="(item, index) in dateList" :key="index" :label="item.id" border>{{ item.name
                      }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="自定义">
                  <el-date-picker v-model="form.date" align="right" unlink-panels type="daterange"
                    start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                    clearable></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-input placeholder="支持手机号,姓名" prefix-icon="el-icon-search" v-model="form.keyword"
                    clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>
        </div>
      </div>
    </el-card>

    <el-card shadow="hover" class="card">
      <div class="flex-between mgb20">
        <div class="flex-center">
          <p class="hr_tag"></p>
          <span>用户列表</span>
        </div>
        <div>
          <el-button type="primary" round @click="delAllSelection" v-auth>批量删除</el-button>
        </div>
      </div>
      <el-table :data="userData" class="table" ref="table" header-align="center"
        @selection-change="handleSelectionChange" row-key="userId">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true"></el-table-column>
        <el-table-column type="index" width="100" label="序号" align="center"></el-table-column>
        <el-table-column prop="userName" label="姓名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
        <el-table-column prop="schoolName" label="学校" align="center"></el-table-column>
        <el-table-column prop="platformName" label="来源" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" align="center"></el-table-column>
        <el-table-column prop="logInNumber" label="登录次数" align="center"></el-table-column>
        <el-table-column prop="lastLoginTime" label="最近登录时间" align="center"></el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="toDetail(scope.row, 1)" v-auth>查看</el-button>
            <el-button v-if="scope.row.userId !== 1" type="text" @click="handleDelete(scope.row)" v-auth>删除</el-button>
            <el-button type="text" @click="resetPassword(scope.row)" v-auth>重置密码</el-button>
            <!-- displayState： 0：禁用，1：启用；2：至少有一个状态为禁用（变颜色），展示为启用状态 -->
            <el-switch v-if="scope.row.userId !== 1" :key="loading" v-model="scope.row.enable" :active-value="1"
              :inactive-value="0" :class="{ error: scope.row.displayState === 2 }" style="margin: 0 10px 0 5px"
              :active-text="scope.row.enable ? '启用' : '禁用'"
              :active-color="scope.row.displayState === 2 ? '#ff552c' : '#062c87'"
              :inactive-color="scope.row.displayState === 2 ? '#ff552c' : '#dcdfe6'"
              @change="switchOff($event, scope.row, scope.$index)" v-auth="'/user:启用'"></el-switch>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background @current-change="currentChange" :current-page="page" layout="total, prev, pager, next"
          :total="totals">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import Setting from '@/setting'
import qs from 'qs'
export default {
  name: 'user',
  data () {
    return {
      platformId: Setting.platformId,
      searchTimer: null,
      form: {
        countries: '中国',
        provinces: +this.$route.query.provinces || '',
        city: +this.$route.query.provinces || '',
        platformId: +this.$route.query.platformId || '',
        schoolId: +this.$route.query.schoolId || '',
        accountRole: '',
        keyword: this.$route.query.keyword || '',
        date: this.$route.query.startTime ? [this.$route.query.startTime, this.$route.query.endTime] : [],
        startTime: this.$route.query.startTime || '',
        endTime: this.$route.query.endTime || '',
        month: +this.$route.query.month || ''
      },
      accountRoleList: [{
        name: '超级管理员',
        value: 1
      },
      {
        name: '管理员',
        value: 13
      },
      {
        name: '教师',
        value: 14
      },
      {
        name: '学生',
        value: 4
      }],
      countryList: [{
        name: '中国'
      }],
      provinceList: this.$store.state.provinceList,
      cityList: [],
      schoolList: [],
      userData: [],
      dateList: [{
        id: '',
        name: '不限'
      },
      {
        id: 3,
        name: '3个月内'
      },
      {
        id: 6,
        name: '6个月内'
      },
      {
        id: 9,
        name: '9个月内'
      },
      {
        id: 12,
        name: '1年内'
      }],
      platformList: [
        {
          value: '',
          label: '不限'
        },
        {
          value: 1,
          label: '职站'
        },
        {
          value: 2,
          label: '数据前瞻'
        },
      ],
      page: +this.$route.query.page || 1,
      pageSize: 10,
      totals: 0,
      multipleSelection: [],
      loading: false,

    };
  },
  watch: {
    'form.keyword': function (val) {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.initData()
      }, 500)
    },
    'form.month': function (val) {
      if (val) {
        let unit = 24 * 60 * 60 * 1000
        this.form.date = [this.formatDate('yyyy-MM-dd', new Date(new Date().getTime() - unit * 30 * val)), this.formatDate('yyyy-MM-dd', new Date(new Date().getTime() + unit))]
      } else {
        this.form.date = []
      }
    },
    'form.date': function (val) {
      if (val && val.length) {
        this.form.startTime = val[0]
        this.form.endTime = val[1]
      } else {
        this.form.startTime = ''
        this.form.endTime = ''
      }
      this.initData()
    }
  },
  mounted () {
    const { query } = this.$route
    if (query.page) {
      this.$router.push('/user').catch(() => { })
    }

    this.getData()
    this.getSchoolData();
  },
  methods: {
    getData () {
      this.loading = true
      this.$post(this.api.userManagementList, {
        countries: this.form.countries,
        provinceId: this.form.provinces,
        cityId: this.form.city,
        platformId: this.form.platformId,
        schoolId: this.form.schoolId,
        month: this.form.month,
        creationTime: this.form.startTime,
        endTime: this.form.endTime,
        roleId: this.form.accountRole,
        searchContent: this.form.keyword,
        pageNum: this.page,
        pageSize: this.pageSize
      }).then(({ page }) => {
        const { records, total } = page
        records.map(e => {
          e.enable = e.displayState
          if (e.enable === 2) {
            e.enable = 1
          }
        })
        this.userData = records
        this.totals = total
        this.loading = false
      }).catch(res => {
        this.loading = false
      })
    },
    initData () {
      this.page = 1
      this.getData()
    },
    // 清除省份
    clearprovince () {
      this.form.city = '',
        this.form.schoolId = ''
    },
    // 获取城市
    getCity () {
      this.clearprovince()
      this.getCityData()
      this.page = 1
      this.getData()
    },
    getCityData () {
      let data = {
        provinceId: this.form.provinces
      }
      this.$get(this.api.queryCity, data).then(res => {
        this.cityList = res.list
      }).catch(res => { })
    },
    // 清除城市
    clearcity () {
      this.form.schoolId = ''
    },
    // 获取学校/客户名称
    getSchool () {
      this.clearcity()
      this.getSchoolData()
      this.page = 1
      this.getData()
    },
    getSchoolData () {
      let data = {
        provinceId: "",
        cityId: ""
      }
      this.$get(this.api.querySchoolData, data).then(res => {
        this.schoolList = res.list
      }).catch(res => { })
    },
    currentChange (val) {
      this.page = val
      this.$router.push(`user?page=${val}`)
      this.getData()
    },
    toDetail (row, detail) {
      this.$store.commit('setReferrer', `${this.$route.path}?${qs.stringify(this.form)}&page=${this.page}`)
      this.$router.push(`/adduser?userId=${row.userId}${detail ? '&show=1' : ''}`)
    },
    handleDelete (row) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$post(this.api.delUserAccountsByNakadai, row.accountIds).then(res => {
          this.$message.success('删除成功')
          this.getData()
        }).catch(res => { })
      }).catch(() => { })
    },
    resetPassword (row) {
      this.$confirm(`重置后的密码为：${Setting.initialPassword}，确定重置？`, '提示', {
      }).then(() => {
        this.$get(this.api.resetPwd, {
          newPwd: Setting.initialPassword,
          userId: row.userId,
        }).then(res => {
          if (res.message == 'success') {
            this.$message.success('重置成功')
          } else {
            this.$message.error('重置失败')
          }
        }).catch(res => { })
      }).catch(() => { })
    },
    // 调禁用启用接口
    switchUser (val, row) {
      this.$get(this.api.updateAccountAllEnable, {
        id: row.userId,
        isEnable: val,
        phone: row.phone
      }).then(res => {
        this.$message.success(val ? '启用成功' : '禁用成功')
        this.getData()
      }).catch(res => { })
    },
    // 禁用启用
    switchOff (val, row) {
      // 如果是启用，则要判断，禁用不用判断
      if (val) {
        // 判断是否能够一键启用（数据平台）
        this.$post(`${this.api.oneClickEnableVerification}?accountIds=${row.accountIds}`).then(({ result }) => {
          this.switchUser(val, row)
        }).catch((res) => {
          // 弹框提示是否要继续启用，点了是，才需要继续启用
          this.$confirm(res.message, '提示', {
            type: 'info',
            closeOnClickModal: false
          }).then(() => {
            this.switchUser(val, row)
          }).catch(() => {
            // 选了否，还原成禁用
            row.isEnable = 0
          })
        })
      } else {
        this.switchUser(val, row)
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    delAllSelection () {
      if (this.multipleSelection.length) {
        let ids = []
        this.multipleSelection.map(e => {
          ids.push(...e.accountIds)
        })
        this.$confirm('确定要删除选中用户吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$post(this.api.delUserAccountsByNakadai, ids).then(res => {
            this.$message.success('删除成功')
            this.$refs.table.clearSelection()
            this.getData()
          }).catch(res => {

          })
        }).catch(() => { })
      } else {
        this.$message.error('请先选择客户 ！')
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.el-form {
  min-width: 1800px;
}

.card {
  min-height: calc(100vh - 380px);
}

.el-form-item {
  margin-bottom: 0;

  /deep/.el-radio {
    width: 87px;
    text-align: center;

    .el-radio__label {
      padding-left: 0;
    }
  }

  .el-radio.is-bordered+.el-radio.is-bordered {
    margin-left: 0;
  }
}

/deep/.error {
  .el-switch__label.is-active {
    color: #ff552c;
  }
}
</style>
