<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="query" :model="userdata" style="display: inline-block;">
        <el-input v-model="userdata.name" placeholder="用户名称" clearable style="width: 200px;" class="filter-item" name="userskk" @input="changeValue" />
        <el-select v-model="userdata.state" placeholder="状态" clearable class="filter-item" style="width: 130px" @change="selectOne">
          <el-option v-for="item in calendarTypeOptions" :key="item" :label="item" :value="item" />
        </el-select>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleSubmit">
          {{ $t('table.search') }}
        </el-button>
      </el-form>
      <el-button v-if="userList != '' " v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('table.export') }}
      </el-button>
      <el-badge v-if="paper > 0" :value="paper" class="item" style="margin-bottom: 8px;">
        <el-button size="small" @click="userpaty">
          <svg-icon class-name="custom-class" icon-class="feizhilou" />废纸篓
        </el-button>
      </el-badge>
    </div>
    <el-table :key="tableKey" v-loading="loading" :data="userList" border fit highlight-current-rows>
      <el-table-column align="center" label="id" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号名称" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名称" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户邮箱" width="180">
        <template slot-scope="scope">
          <span @click="handleCopy(scope.row.email,$event)">{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户下设备数量" width="170">
        <template slot-scope="scope">
          <span v-for="item in userDaviceNum" :key="item.index">{{ scope.row.id==item.id ? item.count : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户地址" width="340">
        <template slot-scope="scope">
          <span>{{ scope.row.province }}<br>{{ scope.row.area }}<br>{{ scope.row.city }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号">
        <template slot-scope="scope">
          <span>{{ scope.row.phone_number }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色">
        <template slot-scope="scope">
          <span>{{ scope.row.role_name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="250">
        <template slot-scope="scope">
          <span :style="{color:( scope.row.state==1 ? '#F56C6C' : ( scope.row.state==3 ? '#909399' : '#67C23A' ) )}">{{ scope.row.state==1 ? '禁用' : ( scope.row.state==3 ? '用户已被丢弃废纸篓' : '正常' ) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.state<3" type="primary" size="mini" @click="userUpdate(scope.row.id)">编辑</el-button>
          <el-popover width="160" trigger="click" placement="top">
            <p>此删除,分丢弃废纸篓,和删除</p>
            <div style="text-align: right; margin: 0">
              <el-button v-if="scope.row.state<3" size="mini" type="text" @click="userDelete(scope.row.id, 1)">丢弃废纸篓</el-button>
              <el-button type="text" size="mini" @click="userDelete(scope.row.id, 2)">删除</el-button>
            </div>
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popover>
          <el-switch v-if="scope.row.state==2" :v-model="false" inactive-color="#ff4949" @change="UpuserForbidden(scope.row.id)"></el-switch>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="userdata.page" :limit.sync="userdata.limit" @pagination="getUserList" />
    <el-dialog :visible.sync="dialogPvVisible" title="编辑用户" width="85%" style="margin-top: auto;">
      <el-form :model="upUserData" class="demo-ruleForm" status-icon>
        <el-form-item label="账号名称" prop="username">
          <el-input v-model.number="upUserData.username"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="nickname">
          <el-input v-model.number="upUserData.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.number="upUserData.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone_number">
          <el-input v-model.number="upUserData.phone_number"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="user_role">
          <el-select v-model="upUserData.user_role_id" clearable class="filter-item" @change="selectOne">
            <el-option v-for="item in user_roles" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义标题" prop="title">
          <el-input v-model.number="upUserData.title"></el-input>
        </el-form-item>
        <el-form-item label="自定义公司名称" prop="company">
          <el-input v-model.number="upUserData.company"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">提交</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { userList, userSeek, userDelete, userDataInfo, postUpUser, paperBasket, UpuserForbidden } from '@/api/users';
import Pagination from '@/components/Pagination'; // 分页
import waves from '@/directive/waves'; // 水波纹效果
import clip from '@/utils/clipboard';
import { parseTime } from '@/utils';
export default {
  name: 'UserData',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      downloadLoading: false,
      dialogPvVisible: false,
      userList: [],
      userDaviceNum: [],
      calendarTypeOptions: ['正常', '禁用', '已删除'],
      total: 0,
      userdata: {
        limit: 10,
        page: 1,
        nickname: undefined,
        state: undefined,
      },
      upUserData: {
        username: undefined,
        name: undefined,
        title: undefined,
        email: undefined,
        company: undefined,
        userid: undefined,
        phone_number: undefined,
        user_role_id: undefined,
      },
      paper: undefined,
      user_roles: [
        { id: 1, name: '行业主管部门负责人' },
        { id: 2, name: '燃气用户' },
        { id: 3, name: '应急抢修人员' },
        { id: 4, name: '村内“两员”' },
      ],
    };
  },
  created() {
    this.getUserList(); // 用户列表
    this.paperBasket();
  },
  methods: {
    getUserList() {
      this.loading = true;
      userList(this.userdata.limit, this.userdata.page)
        .then(response => {
          var userlistdata = response.data.users;
          this.userList = userlistdata;
          this.userList.forEach((element, index) => {
            element['index'] = (this.userdata.page - 1) * this.userdata.limit + index + 1;
          });
          this.total = response.data.count;
          this.userDaviceNum = response.data.davicenum;
          this.loading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 搜索
    handleSubmit() {
      userSeek(this.userdata)
        .then(response => {
          var userlistdata = response.data.users;
          this.userList = userlistdata;
          this.userList.forEach((element, index) => {
            element['index'] = (this.userdata.page - 1) * this.userdata.limit + index + 1;
          });
          this.total = response.data.count;
          this.userDaviceNum = response.data.davicenum;
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleDownload() {
      this.downloadLoading = true;
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', '账号名称', '用户名称', '用户邮箱', '用户地址(省)', '用户地址(市)', '用户地址(区)', '创建时间', '状态'];
        const filterVal = ['id', 'username', 'nickname', 'email', 'province', 'area', 'city', 'created_at', 'state'];
        const data = this.formatJson(filterVal, this.userList);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户列表',
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'created_at') {
          return parseTime(v[j]);
        } else if (j === 'state') {
          return v[j] === 1 ? '用户已被删除' : (v[j] === 3 ? '禁用' : '正常');
        } else {
          return v[j];
        }
      }));
    },
    handleCopy(text, event) {
      clip(text, event);
    },
    // 用户废纸篓
    userpaty() {
      this.$router.push({ path: '/users/userStatus' });
    },
    // 编辑
    userUpdate(id) {
      this.dialogPvVisible = true;
      this.getuserDataInfo(id);
      this.upUserData.userid = id;
    },
    userDelete(id, type) {
      var data = {
        'duserid': id,
        'type': type,
      };
      userDelete(data)
        .then(response => {
          if (response.code === 105) {
            this.$message({
              message: response.msg,
              type: 'warning',
            });
          } else {
            this.getUserList();
            this.paperBasket();
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 删除
    selectOne(event, item) {
      if (event === '') {
        this.userdata.state = undefined;
      }
    },
    changeValue(event, item) {
      if (event === '') {
        this.userdata.nickname = undefined;
      }
    },
    // 重置
    resetForm() {
      for (const key in this.upUserData) {
        this.upUserData[key] = undefined;
      }
    },
    submitForm() {
      postUpUser(this.upUserData)
        .then(response => {
          if (response.code === 105) {
            this.$notify.error({
              message: response.msg,
              type: 'warning',
            });
          } else {
            if (response.code === 200) {
              this.dialogPvVisible = false;
              this.getUserList();
              this.paperBasket();
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    getuserDataInfo(id) {
      userDataInfo(id)
        .then(response => {
          if (response.code === 105) {
            this.$message({
              message: response.msg,
              type: 'warning',
            });
          } else {
            console.log(response.data);
            for (const key in this.upUserData) {
              for (const k in response.data) {
                if (key === k) {
                  if (response.data[k] !== null) {
                    this.upUserData[key] = response.data[k];
                  }
                }
              }
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 获取废纸篓数量
    paperBasket() {
      paperBasket()
        .then(response => {
          if (response.code === 200) {
            this.paper = response.data;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    UpuserForbidden(id) {
      this.$confirm('是否将用户禁用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        UpuserForbidden(id)
          .then(response => {
            this.getUserList();
            this.paperBasket();
          })
          .catch(err => {
            console.log(err);
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消',
        });
      });
    },
  },
};
</script>

<style>
</style>
