<template>
  <div>
    <div>
      <el-form :inline="true" class="orderform" size="mini">
        <el-row>
          <el-form-item label="账号/账号名称:">
            <el-input v-model="tag" style="width: 250px" placeholder="请输入..." class="search_tag" clearable/>
          </el-form-item>
          <el-form-item label="使用频率:">
            <el-select v-model="callValue" clearable placeholder="请选择使用频率" size="mini">
              <el-option
                v-for="item in callOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="活跃状态:">
            <el-select v-model="statusValue" clearable placeholder="请选择" size="mini">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="预警状态:">
            <el-select v-model="alarmValue" clearable placeholder="请选择" size="mini">
              <el-option
                v-for="item in alarmOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="btn_search()"><i class="el-icon-search"/> 搜索</el-button>
            <el-button @click="btn_clear()"><i class="el-icon-remove-outline"/> 重置</el-button>
            <el-button @click="createUser()"><i class="el-icon-plus"/> 添加</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <el-table
        ref="multipleTable"
        :data="tableData"
        :highlight-current-row="true"
        :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
        class="mytable"
        border>
        <el-table-column
          prop="id"
          label="序列号"/>
        <el-table-column
          prop="account"
          label="帐号"/>
        <el-table-column
          prop="name"
          label="账号名称"/>
        <el-table-column
          prop="role.roleName"
          label="角色"/>
        <el-table-column
          width="120px"
          prop="phone"
          label="电话"/>
        <el-table-column
          prop="email"
          label="邮箱"/>
        <el-table-column
          prop="companyName"
          label="公司名称"/>
        <el-table-column
          prop="companyInfo"
          label="公司介绍">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>{{ scope.row.companyInfo }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="mini">查看详情...</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column
          :formatter="formatStatus"
          prop="status"
          label="状态"
        />
        <!-- <el-table-column
          label="剩余次数">
          <template slot-scope="scope">
            <el-button type="text" @click="handleCheck(scope.row)">查看明细</el-button>
          </template>
        </el-table-column> -->
        <el-table-column
          width="200px"
          label="操作">
          <template slot-scope="scope">
            <el-row>
              <el-button v-if="scope.row.status === 0" type="text" @click="handleActivate(scope.row)">解封</el-button>
              <!--              <el-button v-if="scope.row.status !== 0" type="text" @click="handleActivate(scope.row)">封号</el-button>-->
              <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <!-- <el-button type="text"><router-link :to="{path:'/appmngr/applist',query:{developer:scope.row.name}}" tag="a"><span class="blue">应用</span></router-link></el-button> -->
              <!--              <el-button type="text"><router-link :to="{path:'/devappreport/appreport',query:{userId:scope.row.id}}" tag="a"><span class="blue">统计</span></router-link></el-button>-->
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <div class="mydiv">
        <el-pagination
          :current-page.sync="pageNo"
          :page-sizes="[10, 50, 100, 300,1000]"
          :page-size="pageSize"
          :total="totalDataNumber"
          layout="sizes,total, prev, pager, next"
          class="table-pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>

      <el-dialog
        :visible.sync="dialogFormVisible"
        title="提示"
        width="30%">
        <span v-if="status > 0">确定对选择用户进行 <b>封号</b> 处理? </span>
        <span v-if="status === 0">确定对选择用户进行 <b>解封</b> 处理? </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog :visible.sync="addFormVisible" title="新增开发者">
        <el-form :rules="rules" :model="form">
          <el-form-item :label-width="formLabelWidth" prop="account" label="帐号">
            <el-input v-model="form.account"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="password" label="密码">
            <el-input v-model="form.password"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="用户状态">
            <el-select v-model="form.status" placeholder="请选择用户状态">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="name" label="账号名称">
            <el-input v-model="form.name"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="mobilephone" label="电话">
            <el-input v-model="form.mobilephone"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="email" label="邮箱">
            <el-input v-model="form.email"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="公司名称">
            <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="公司介绍">
            <el-input v-model="form.companyInfo" placeholder="请输入公司介绍"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="btn_create_cancel">取 消</el-button>
          <el-button type="primary" @click="btn_create_submit">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="editFormVisible" title="编辑开发者">
        <el-form :rules="rules" :model="editForm">
          <el-form-item :label-width="formLabelWidth" prop="account" label="帐号">
            <el-input v-model="editForm.account" :disabled="true"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="用户状态">
            <el-select v-model="editForm.status" placeholder="请选择用户状态">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="name" label="账号名称">
            <el-input v-model="editForm.name"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="mobilephone" label="电话">
            <el-input v-model="editForm.mobilephone"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="email" label="邮箱">
            <el-input v-model="editForm.email"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="公司名称">
            <el-input v-model="editForm.companyName" placeholder="请输入公司名称"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="公司介绍">
            <el-input
              v-model="editForm.companyInfo"
              type="textarea"
              rows="3"
              placeholder="请输入公司介绍"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="btn_update_cancel">取 消</el-button>
          <el-button type="primary" @click="btn_update_submit">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        :visible.sync="showTimesFormVisible"
        title="应用接口剩余次数"
        width="50%">
        <el-table
          :row-style="tableRowStyle"
          :data="selectTimes"
          :highlight-current-row="true"
          :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
          border>
          <el-table-column
            prop="appName"
            label="应用名称"/>
          <el-table-column
            prop="apiName"
            label="接口名称"/>
          <el-table-column
            prop="total"
            label="总计次数"/>
          <el-table-column
            prop="used"
            label="已使用数"/>
          <el-table-column
            :formatter="calculateRemainTimes"
            prop="remain"
            label="剩余次数"/>
          <el-table-column
            :formatter="calculateRemainRate"
            prop="remainRate"
            label="剩余比例"/>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showTimesFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="showTimesFormVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'
import md5 from 'js-md5'
import APP_CONFIG from "../../../public/config";
export default {
  name: 'Index',
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    }
  },
  data() {
    return {
      rules: {
        account: [{ required: true, message: '请输入帐号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入账号名称', trigger: 'blur' }],
        mobilephone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
      },
      status: '',
      account: '',
      tag: '',
      callValue: '', // 使用频率状态
      callOptions: [{
        value: 1,
        label: '今日调用'
      }, {
        value: 2,
        label: '本周调用'
      }, {
        value: 3,
        label: '本月调用'
      }],
      statusValue: '', // 活跃状态
      statusOptions: [{
        value: 1,
        label: '活跃账户'
      }, {
        value: 2,
        label: '不活跃账户'
      }],
      alarmValue: '', // 预警状态
      alarmOptions: [{
        value: 1,
        label: '预警账户'
      }, {
        value: 2,
        label: '异常账户'
      }, {
        value: 3,
        label: '非法账户'
      }],
      options: [{
        value: 1,
        label: '免费用户'
      }, {
        value: 2,
        label: '付费用户'
      }, {
        value: 3,
        label: 'VIP用户'
      }, {
        value: 4,
        label: '测试用户'
      }, {
        value: 0,
        label: '异常用户'
      }],
      roles: [],
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      dialogFormVisible: false, // 封号/解封框
      addFormVisible: false, // 新增管理用户
      editFormVisible: false, // 编辑用户
      formLabelWidth: '150px', // 弹出框form宽
      form: {
        account: '',
        password: '',
        role: '',
        mobilephone: '',
        name: '',
        status: '',
        email: '',
        companyName: '',
        companyInfo: ''
      },
      editForm: {
        id: '',
        account: '',
        role: '',
        mobilephone: '',
        name: '',
        status: '',
        email: '',
        companyName: '',
        companyInfo: ''
      },
      checkUserId: '',
      showTimesFormVisible: false,
      selectTimes: []
    }
  },
  created() {
    this.btn_search()
  },
  mounted() {
  },
  methods: {
    formatStatus(ob) {
      // 1=免费用户 0=异常用户 2=付费用户 3=VIP用户 4=测试用户)
      if (ob.status === 1) {
        return '免费用户'
      } else if (ob.status === 0) {
        return '异常用户'
      } else if (ob.status === 2) {
        return '付费用户'
      } else if (ob.status === 3) {
        return 'VIP用户'
      } else if (ob.status === 4) {
        return '测试用户'
      } else {
        return '未知'
      }
    },
    btn_search() {
      const vm = this
      axios.get(process.env.BASE_API + '/user/listdevbyadmin', {
        params: {
          tag: this.tag,
          callValue: this.callValue,
          statusValue: this.statusValue,
          alarmValue: this.alarmValue
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.totalDataNumber = 0
          vm.allData = []
          vm.tableData = []
        } else {
          // console.log(obj.data)
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.allData = obj.data
            vm.tableData = obj.data.slice(0, vm.pageSize)
          } else {
            vm.allData = []
            vm.tableData = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_clear() {
      this.tag = ''
      this.callValue = ''
      this.statusValue = ''
      this.alarmValue = ''
      this.btn_search()
    },
    handleCurrentChange() {
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    handleActivate(row) {
      this.status = row.status
      this.account = row.account
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      this.editFormVisible = true
      this.editForm.id = row.id
      this.editForm.account = row.account
      this.editForm.status = row.status
      this.editForm.name = row.name
      this.editForm.mobilephone = row.phone
      this.editForm.email = row.email
      this.editForm.companyName = row.companyName
      this.editForm.companyInfo = row.companyInfo
    },
    handleCancel() {
      this.dialogFormVisible = false
    },
    handleSubmit() {
      var vm = this
      var params = new URLSearchParams()
      params.append('account', vm.account)
      if (vm.status === 1) {
        params.append('status', 0)
      } else {
        params.append('status', 1)
      }
      axios.post(process.env.BASE_API + '/user/activteuser', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.btn_search()
        }
        vm.status = ''
      }).catch(function(error) {
        alert(error)
      })
      this.dialogFormVisible = false
    },
    dateformatter(row, column) {
      var date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm')
    },
    createUser() {
      this.addFormVisible = true
    },
    btn_create_cancel() {
      this.addFormVisible = false
    },
    btn_create_submit() {
      if (this.form.account === '' || this.form.account === undefined) {
        this.$message.error('请输入账号，账号不能为空')
        return
      }
      if (this.form.password === '' || this.form.password === undefined) {
        this.$message.error('请输入密码，密码不能为空')
        return
      }
      if (this.form.name === '' || this.form.name === undefined) {
        this.$message.error('请输入账号名称，账号名称不能为空')
        return
      }
      if (this.form.mobilephone === '' || this.form.mobilephone === undefined) {
        this.$message.error('请输入电话，电话不能为空')
        return
      }
      if (this.form.email === '' || this.form.email === undefined) {
        this.$message.error('请输入邮箱，邮箱不能为空')
        return
      }
      var regEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
      if (this.form.email === '') {
        this.$message.info('请输入邮箱')
        return
      } else if (!regEmail.test(this.form.email)) {
        this.$message.info('邮箱格式不正确')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('account', vm.form.account)
      params.append('password', md5(vm.form.password))
      params.append('name', vm.form.name)
      params.append('phone', vm.form.mobilephone)
      params.append('email', vm.form.email)
      params.append('status', vm.form.status)
      params.append('companyName', vm.form.companyName)
      params.append('companyInfo', vm.form.companyInfo)
      axios.post(process.env.BASE_API + '/user/insertbyadmin', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.form = ''
          vm.btn_search()
        }
        vm.status = ''
      }).catch(function(error) {
        alert(error)
      })
      this.addFormVisible = false
    },
    btn_update_cancel() {
      this.editFormVisible = false
    },
    btn_update_submit() {
      if (this.editForm.account === '' || this.editForm.account === undefined) {
        this.$message.error('请输入账号，账号不能为空')
        return
      }
      if (this.editForm.status === '' || this.editForm.status === undefined) {
        this.$message.error('请选择用户状态')
        return
      }
      var regEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
      if (this.editForm.email === '') {
        this.$message.info('请输入邮箱')
        return
      } else if (!regEmail.test(this.editForm.email)) {
        this.$message.info('邮箱格式不正确')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('id', vm.editForm.id)
      params.append('account', vm.editForm.account)
      params.append('email', vm.editForm.email)
      params.append('name', vm.editForm.name)
      params.append('status', vm.editForm.status)
      params.append('phone', vm.editForm.mobilephone)
      params.append('companyName', vm.editForm.companyName)
      params.append('companyInfo', vm.editForm.companyInfo)
      axios.post(process.env.BASE_API + '/user/update', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.form = ''
          vm.btn_search()
        }
        vm.status = ''
      }).catch(function(error) {
        alert(error)
      })
      this.editFormVisible = false
    },
    handleCheck(row) {
      this.showTimesFormVisible = true
      this.checkUserId = row.id
      const vm = this
      axios.get(process.env.BASE_API + '/appapi/selectusertimes', {
        params: {
          userId: this.checkUserId
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.selectTimes = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.selectTimes = obj.data
          } else {
            vm.selectTimes = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    calculateRemainTimes(ob) {
      if (ob.used === null) {
        ob.used = 0
      }
      return ob.total - ob.used
    },
    calculateRemainRate(ob) {
      if (ob.used === null) {
        ob.used = 0
      }
      var rate = parseFloat((ob.total - ob.used) / ob.total * 100).toFixed(2)
      return rate + '%'
    },
    tableRowStyle({ row, rowIndex }) {
      if (row.remain === '0.0') {
        //  异常
        return 'background-color: red'
      } else if (row.remain > 0 && row.remainRate < 0.2) {
        // 预警
        return 'background-color: orange'
      }
    }
  }
}
</script>

<style scoped>
  .orderform {
    padding-top: 20px;
    padding-left: 10px;
    padding-right: 10px;
  }
  .mytable{
    margin-right: 10px;
    margin-left: 20px;
    width: 90%;
  }
  .mydiv {
    float: right;
    margin-right: 10px;
  }
  body .el-table th.gutter{
    display: table-cell!important;
  }
  .btn {
    display: inline-block;
    float: left;
  }
</style>
