<template>
  <div id="device-management">
    <div class="device-management-body" v-loading.fullscreen.lock="fullscreenLoading">
      <div class="order-management-body">
        <div class="order-management-inner">
          <div class="base-info">
            <!-- <span>关键词：</span> -->
            <span>用户名：</span>
            <el-input style="width:220px;" @keyup.enter.native="currentPage=1&&_getCameraData()" v-model="searchKey" placeholder="请输入用户名"></el-input>
            <el-button type="primary" @click="currentPage=1&&_getCameraData()" color='red'>搜索</el-button>
            <el-button icon="el-icon-plus" type="primary" style="float: right;" @click="showCameraDialog" color='red'>添加相机</el-button>
          </div>
        </div>
        <!-- 全部 -->
        <div class="device-management_bottom">
          <div class="order-management-table">
            <el-table ref="order_table" class='e-table' :data="cameras" style="width: 100%">
              <el-table-column prop="childName" label="设备ID">
              </el-table-column>
              <el-table-column prop="userName" label="手机号(用户名)">
              </el-table-column>
              <el-table-column prop="goodsName" label="设备类型">
              </el-table-column>
              <el-table-column prop="snCode" label="sn码">
              </el-table-column>
              <el-table-column width="300" label="激活时间">
                <template slot-scope="scope">
                  <div>{{scope.row.activatedTime}}</div>
                </template>
              </el-table-column>
              <el-table-column prop="own" label="出货类型">
              </el-table-column>
              <el-table-column prop="companyName" label="客户名称">
                <template slot-scope="scope">
                  <div>{{scope.row.companyName||'-'}}</div>
                </template>
              </el-table-column>
              <el-table-column prop="balance" label="当前余额(点)">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="showDialog(scope.row)" class="edit_btn">点数</el-button>
                  <el-button type="text" v-if="scope.row.userName!='未绑定'" @click="_unbindDevice(scope.row)" class="delete_btn">解绑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="order-management-pagination">
            <el-pagination  @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pagesize" layout="total, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </div>
        <el-dialog width="450px" title="点数修改" :visible.sync="dialogFormVisible">
          <el-form :model="form" >
            <el-form-item >
              <div style="display: flex;justify-content: space-between;font-size: 14px;">
                <span>设备ID：
              <span>{{currentChildName}}</span>
                </span>
                <span>当前余额：
              <span>{{currentBalance}}</span>
                </span>
              </div>
            </el-form-item>
            <el-form-item label="充值类型">
              <el-select v-model="form.region" placeholder="请选择点数修改类型">
                <el-option label="系统赠送" value=0></el-option>
                <el-option label="退充值款" value=-2></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="充值点数" width="100%">
              <el-input @keyup.native="_checkInput" maxlength="5" :suffix-icon="form.region==-2?'el-icon-minus':'el-icon-plus'" v-model.number="form.point"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="_modifyPoints">确 定</el-button>
          </div>
        </el-dialog>
        <el-dialog width="470px" title="添加相机" :visible.sync="cameraVisible">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
            <el-form-item label="出库类型" prop="own">
              <el-select v-model="ruleForm.own" placeholder="请选择出库类型">
                <el-option label="正常销售" value="0"></el-option>
                <el-option label="礼品赠送" value="2"></el-option>
                <el-option label="员工自用" value="1"></el-option>
                <el-option label="其他" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="相机类型" prop="type">
              <el-select v-model="ruleForm.type" placeholder="请选择相机类型">
                <el-option label="四维看看Pro八目相机" value="1"></el-option>
                <el-option label="四维看看Lite双目相机" value="0"></el-option>
                <el-option label="四维看看双目转台相机" value="3"></el-option>
                <el-option label="四维看看激光相机" value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="wifi名称" prop="wifi">
              <el-input v-model="ruleForm.wifi"></el-input>
            </el-form-item>
            <el-form-item label="物理地址" prop="address">
              <el-input v-model="ruleForm.address"></el-input>
            </el-form-item>
            <el-form-item label="sn码" prop="snCode">
              <el-input v-model="ruleForm.snCode"></el-input>
            </el-form-item>
            <el-form-item label="初始点数" @keyup.native="_checkPointInput" prop="initPoint">
              <el-input v-model="ruleForm.initPoint"></el-input>
            </el-form-item>
            <el-form-item label="订单号" prop="orderNum">
              <el-input v-model="ruleForm.orderNum"></el-input>
            </el-form-item>
            <el-form-item label="客户名称" prop="own">
              <el-select v-model="ruleForm.companyId" placeholder="请选择">
                <el-option v-for="(item,i) in companyList" :key="i" :label="item.companyName" :value="item.id">{{item.companyName}}</el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cameraVisible = false">取 消</el-button>
            <el-button type="primary" @click="_addCamera">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>

export default {
  data () {
    return {
      tabs: [{ name: '设备ID', idx: 0 }, { name: '手机号', idx: 1 }, { name: '当前余额', idx: 2 }, { name: '历史充值', idx: 3 }],
      expands: [],
      expandedArr: [],
      cameras: [],
      currentPage: 1,
      key_input: '',
      fullscreenLoading: false,
      product: {
        'name': '',
        'packageName': '',
        'count': '',
        'amount': '',
        'url': ''
      },
      // labelPosition: 'right',
      receive: {
        'name': '',
        'phone': '',
        'address': '',
        'invoice': '',
        'expressNum': ''
      },
      searchKey: '',
      total: 0,
      // expressNum_input: "",
      searchDate: [],
      searchOrderNumber: '',
      searchPhone: '',
      searchExpressNum: '',
      hasClickSearch: false,
      tabIndex: 0,
      dialogFormVisible: false,
      cameraVisible: false,
      form: {
        point: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      ruleForm: {
        wifi: '',
        address: '',
        initPoint: '',
        type: [],
        own: [],
        snCode: '',
        orderNum: '',
        companyId: ''
      },
      rules: {
        wifi: [
          { required: true, message: '请输入WiFi名称', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入物理地址', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        snCode: [
          { required: true, message: '请输入SN码', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        initPoint: [
          { required: true, message: '请输入初始点数', trigger: 'blur' }
          // { type: "number", message: '必须为数字值', trigger: 'blur' }
        ]

      },
      cameraInfo: {
        wifi: '',
        type: '',
        address: '',
        initPoint: '',
        orderNum: '',
        companyId: ''
      },
      companyList: [],
      formLabelWidth: '30%',
      value2: true,
      currentChildName: '',
      currentDeviceId: '',
      currentBalance: '',
      pagesize: 10
    }
  },
  watch: {
    currentPage () {
      this._getCameraData()
    }
  },
  methods: {
    _getCameraData () {
      this.fullscreenLoading = true
      if (!Number(this.currentPage)) this.currentPage = 1
      let params = {
        userName: window.localStorage.getItem('zfb_username')
      }
      this.$http({
        method:'post',
        url:'/company/selectCompanyDevice',
        data: params,
        headers:{
          token: window.localStorage.getItem('zfb_token')
        }
      }).then(res => {
        this.fullscreenLoading = false
        console.log(res)
        if (res.code === 0) {
          let temp = res.data.list
          // let temp = res.message
          for (var i = 0; i < temp.length; i++) {
            switch (temp[i]['own']) {
              case 0:
                temp[i]['own'] = '正常销售'
                break
              case 1:
                temp[i]['own'] = '员工自用'
                break
              case 2:
                temp[i]['own'] = '礼品赠送'
                break
              case 3:
                temp[i]['own'] = '其他'
                break
            }
            temp[i]['userName'] = temp[i]['userName'] ? temp[i]['userName'] : '未绑定'
            temp[i]['activatedTime'] = temp[i]['activatedTime'] ? new Date(temp[i]['activatedTime']).format('yyyy-MM-dd hh:mm:ss') : '/'
          }
          this.cameras = temp
          this.total = res.data.total ? res.data.total : this.total
        }
      })
    },
    handleCurrentChange (val) {
      this.currentPage = val
    },
    showDialog (row) {
      this.form.region = ''
      this.form.point = ''
      this.currentChildName = row.childName
      this.currentDeviceId = row.id
      this.currentBalance = row.balance
      this.dialogFormVisible = true
    },
    async getCompanyList () {
      let result = await this.$http.post('/manager/company/listAll')
      this.companyList = result.data
    },
    async _unbindDevice (row) {
      this.$confirm('确定把该设备从账号中解除绑定', '解绑设备', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.fullscreenLoading = true
        console.log(row)
        let res = await this.$http.post('/manager/camera/unbind', {
          cameraId: row.id
        })
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '解绑成功!'
          })
          this._getCameraData()
        } else {
          this.$alert('解绑失败', '提示', {
            confirmButtonText: '确定'
          })
        }
        this.fullscreenLoading = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消解绑'
        })
        this.fullscreenLoading = false
      })
    },
    _checkInput: function (e) {
      this.form.point += ''
      this.form.point = this.form.point.replace(/[^\d]/g, '')
      if (Number(this.form.point) && this.form.point > 10000) {
        this.form.point = 10000
      }
    },
    _checkPointInput: function (e) {
      this.ruleForm.initPoint += ''
      this.ruleForm.initPoint = this.ruleForm.initPoint.replace(/[^\d]/g, '')
      if (Number(this.ruleForm.initPoint) && this.ruleForm.initPoint > 10000) {
        this.ruleForm.initPoint = 10000
      }
    },
    async _modifyPoints () {
      let body = this.form.region
      let points = this.form.point
      let cameraId = this.currentDeviceId

      if (!body) {
        this.$alert('请选择充值类型', '提示', {
          confirmButtonText: '确定',
          callback: action => {

          }
        })
      } else {
        let res = await this.$http.post('/manager/camera/modifyPoints', {
          body: Number(body),
          cameraId,
          points
        })

        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '充值成功!'
          })
          this._getCameraData()
          this.dialogFormVisible = false
        } else {
          this.$alert(res.msg, '提示', {
            confirmButtonText: '确定'
          })
        }
      }
    },

    async _addCamera () {
      let {
        wifi: wifiName,
        address: childName,
        initPoint: balance,
        own,
        type,
        snCode,
        companyId,
        orderNum: orderSn
      } = this.ruleForm
      if (wifiName === '' || childName === '' || snCode === '' || balance === '' || own === '' || type === '') {
        return
      }

      this.fullscreenLoading = true
      let res = await this.$http.post('/manager/camera/add', {
        childName,
        wifiName,
        orderSn,
        snCode,
        companyId,
        balance: Number(balance),
        type: Number(type),
        own
      })
      this.fullscreenLoading = false
      if (res.code === 0) {
        this.$alert('该相机信息已成功添加入库', '添加成功', {
          confirmButtonText: '确定'
        })
        this._getCameraData()
        this.ruleForm.address = ''
        this.ruleForm.wifi = ''
        this.ruleForm.own = ''
        this.ruleForm.orderNum = ''
        this.ruleForm.snCode = ''
        this.ruleForm.type = ''
        this.ruleForm.initPoint = ''
        this.ruleForm.companyId = ''

        this.cameraVisible = false
      } else {
        this.$alert(res.msg, '添加失败', {
          confirmButtonText: '确定'
        })
      }
    },
    showCameraDialog (row) {
      this.cameraVisible = true
    }
  },
  created () {
    this._getCameraData()
    this.getCompanyList()
  }
}

</script>
<style lang="css" scoped>
@import './style.css';
</style>
<style type="text/css">
.el-table__expand-icon>i {
  display: none !important;
}

.edit_btn span {
  color: #09e1c0
}

.delete_btn span {
  color: #f56c6c
}

</style>
