<template>
  <div class="phone-management">
    <!-- 搜索|新增 -->
    <div class="set-parameters">
      <el-input
        v-model="deviceid"
        class="device-wechat-id"

        placeholder="请输入设备号"
        clearable
        minlength="15"
        maxlength="16"
        show-word-limit
      ></el-input>
      <el-input
        v-model="wechatid"
        class="wechat-id-input device-wechat-id"

        placeholder="请输入wxid"
        clearable
        minlength="6"
        maxlength="20"
        show-word-limit
      ></el-input>
      <el-select v-model="accountid"  placeholder="请选择客服账号" filterable clearable>
        <el-option
          v-for="account in accounts"
          :key="account.createTime"
          :label="account.account"
          :value="account.id"
        ></el-option>
      </el-select>
      <el-select v-model="isonline"  placeholder="上线状态" filterable clearable>
        <el-option v-for="ols in onlineState" :key="ols.id" :label="ols.label" :value="ols.value"></el-option>
      </el-select>
      <el-button type="primary"  @click="queryData">查询</el-button>
      <el-button type="primary"  @click="showDialog">添加</el-button>
    </div>

    <!-- 信息展示 -->
    <el-table :data="tableData" stripe style="width: 100%" height="60px">
      <!-- <el-table-column prop="accountname" label="所属操作员" header-align="center" align="center"></el-table-column> -->
      <el-table-column prop="accountid" label="所属操作员" header-align="center" align="center">
        <template slot-scope="{ row }">
          <el-tag v-for="(ai, index) in row.accountid" :key="index" style="margin: 5px" type="success">
            {{ accountsMap[ai] || ai }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deviceid" label="设备号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="wxid" label="微信id" header-align="center" align="center"></el-table-column>
      <el-table-column prop="name" label="微信昵称" header-align="center" align="center"></el-table-column>
      <el-table-column label="手机是否在线" header-align="center" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.isonline === 0" style="color: #67c23a" v-text="'已上线'"></span>
          <span v-else style="color: #f56c6c" v-text="'已下线'"></span>
        </template>
      </el-table-column>
      <el-table-column label="最近登陆时间" header-align="center" align="center">
        <template slot-scope="scope">
          <span v-text="$options.filters.transformTime2Minute(scope.row.login_time)"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" header-align="center" align="center">
        <template slot-scope="scope">
          <el-button  @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button

            style="background-color: #ff9f00; color: #ffffff"
            type="warning"
            @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="pageNo"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="pageSize"
      :pager-count="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <el-dialog :modal="false" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item label="所属操作员" :label-width="formLabelWidth" prop="accountid">
          <el-select
            v-model="form.accountid"
            multiple
            placeholder="请选择部门"
            filterable
            clearable
            style="width: 280px"
          >
            <el-option
              v-for="account in accounts"
              :key="account.id"
              :label="account.account"
              :value="account.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备ID" :label-width="formLabelWidth" prop="deviceid">
          <el-input
            v-model="form.deviceid"
            placeholder="请输入账号名称"
            clearable
            minlength="15"
            maxlength="16"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机别名" :label-width="formLabelWidth" prop="devnickname">
          <el-input
            v-model="form.devnickname"
            placeholder="请输入手机别名"
            clearable
            maxlength="20"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机品牌" :label-width="formLabelWidth" prop="brand">
          <el-input
            v-model="form.brand"
            placeholder="请输入手机品牌"
            clearable
            maxlength="20"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机型号" :label-width="formLabelWidth" prop="module">
          <el-input
            v-model="form.module"
            placeholder="请输入手机型号"
            clearable
            maxlength="20"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateOrAddDevice">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { queryAccountsByCid, queryDevices, deleteDevices, addDevice, updateDevice } from '@/api/httpApiAdmin'

export default {
  name: 'PhonesManagerment',
  data() {
    return {
      tableData: [], // 表格中的数据
      deviceid: '', // 设备号
      wechatid: '', // 微信id
      accountid: '', // 客服账号id
      accounts: [], // 客服列表
      isonline: '', // 微信在线状态
      onlineState: [
        {
          id: 'isonline0',
          value: 0,
          label: '已上线'
        },
        {
          id: 'isonline1',
          value: 1,
          label: '已下线'
        }
      ], // 微信在线状态列表

      pageNo: 1, // 第几页
      pageSize: 20, // 每页几个数据
      total: 0, // 总数
      dialogTitle: '添加设备',
      dialogVisible: false, // 显示dialog
      formLabelWidth: '120px',
      form: {
        id: '',
        cid: '',
        deviceid: '', // 设备id（一般为imei）
        accountid: '', // 所属操作员账号id，为空则未分配
        devnickname: '', // 设备名称
        brand: '', // 手机品牌
        module: '' // 手机型号
      }, // 表单
      rules: {
        accountid: [{ required: true, message: '请选择操作员', trigger: 'blur' }],
        deviceid: [{ required: true, message: '请输入设备号', trigger: 'blur' }]
      } // 表单验证
    }
  },
  computed: {
    ...mapState({
      adminInfo: 'adminInfo'
    }),
    accountsMap() {
      const am = {}
      this.accounts.forEach((x) => {
        am[x.id] = x.account
      })
      console.log(am)
      return am
    },
  },
  mounted() {
    queryAccountsByCid(this.adminInfo.cid).then((res) => {
      if (res.code === 0) {
        this.accounts = res.data || []
      }
    })
    this.queryDataSilence()
  },
  methods: {
    // 分页查询数据
    queryData() {
      queryDevices(
        this.adminInfo.cid,
        this.pageNo,
        this.pageSize,
        this.deviceid,
        this.wechatid,
        this.accountid,
        this.isonline
      ).then((res) => {
        if (res.code === 0) {
          const devicesList = res.data.rows || []
          for (const device of devicesList) {
            device.accountid = device.accountid.split(',')
          }
          this.tableData = devicesList
          this.total = res.data.records || 0
          this.$message({
            type: 'success',
            message: '查询成功！',
            duration: 1000
          })
        }
      })
    },
    queryDataSilence() {
      queryDevices(
        this.adminInfo.cid,
        this.pageNo,
        this.pageSize,
        this.deviceid,
        this.wechatid,
        this.accountid,
        this.isonline
      ).then((res) => {
        if (res.code === 0) {
          const devicesList = res.data.rows || []
          for (const device of devicesList) {
            device.accountid = device.accountid.split(',')
          }
          this.tableData = devicesList
          this.total = res.data.records || 0
        }
      })
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
      this.queryData()
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.pageNo = val
      this.queryData()
    },
    // 显示dialog
    showDialog() {
      this.resetForm()
      this.dialogTitle = '添加设备'
      this.dialogVisible = true
    },
    // 修改或添加设备
    updateOrAddDevice() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { id, deviceid, accountid, devnickname, brand } = this.form
          const cid = this.adminInfo.cid
          const model = this.form.module
          const accountIdStr = accountid.join(',')
          if (this.dialogTitle === '添加设备') {
            addDevice(cid, deviceid, accountIdStr, devnickname, brand, model).then((res) => {
              if (res.code === 0) {
                this.queryDataSilence()
                this.dialogVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功!',
                  duration: 1000
                })
              }
            })
          } else {
            updateDevice(id, cid, deviceid, accountIdStr, devnickname, brand, model).then((res) => {
              if (res.code === 0) {
                this.dialogVisible = false
                this.queryDataSilence()
                this.$message({
                  type: 'success',
                  message: '更新成功',
                  duration: 1000
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: '',
        cid: '',
        deviceid: '', // 设备id（一般为imei）
        accountid: '', // 所属操作员账号id，为空则未分配
        devnickname: '', // 设备名称
        brand: '', // 手机品牌
        module: '' // 手机型号
      }
    },
    // 显示编辑dialog
    handleEdit(index, row) {
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          if (key === 'state') {
            this.form[key] = row[key] === 1
          } else if (key === 'accountid') {
            const aids = []
            row['accountid'].forEach((x) => {
              aids.push(Number(x))
            })
            this.form['accountid'] = aids
          } else {
            this.form[key] = row[key]
          }
        }
      }
      this.dialogTitle = '编辑设备'
      this.dialogVisible = true
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm('是否删除设备？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteDevices(row.id).then((res) => {
            if (res.code === 0) {
              const pn = Math.ceil((this.total[this.activeName] - 1) / this.pageSize)
              if (this.pageNo > pn) {
                this.pageNo = pn
              }
              this.queryDataSilence()
              this.$message({
                type: 'success',
                message: '删除成功!',
                duration: 1000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消',
            duration: 1000
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.phone-management {
  height: 100%;
  display: flex;
  flex-direction: column;

  .set-parameters {
    padding: 10px 5px;
    display: flex;
    align-items: center;
    border-bottom: solid $border-color-1 2px;
    .el-button,
    .wechat-id-input,
    .el-select {
      margin-left: 20px;
    }
    ::v-deep .device-wechat-id {
      width: 220px;
      .el-input__inner {
        width: 220px;
      }
    }
  }

  .el-pagination {
    padding: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: solid 1px $border-color-1;
    background-color: white;
  }

  ::v-deep .el-dialog {
    width: 500px;
    .el-form {
      width: 400px;
    }
  }
}
</style>
