<template>
  <div id="container">
    <div class="alarmrecord">
      <el-card class="box-card">
        <el-row class="">
          <div class="search">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="" v-if="userInfo.type==0">
                <selectoption></selectoption>
              </el-form-item>
              <el-form-item label="单位名称:">
               <!-- <el-select v-model="formInline.enterpriseId" size="small" class="w200" clearable placeholder="请选择所属单位">
                  <el-option :label="item.name" :value="item.id" v-for="item in enterpriselist" :key="item.id">
                  </el-option>
                </el-select> -->
              <el-cascader :options="enterpriselist" v-model="formInline.enterpriseId" size="small" ref="cascaderone"  placeholder="请选择所属单位" :props="{ checkStrictly: true }" @change="checkNodeRecordTop" clearable></el-cascader>
              </el-form-item>
              <el-form-item label="姓名:">
                <el-input v-model="formInline.name" placeholder="请输入联系人姓名" size="small" :clearable="true"></el-input>
              </el-form-item>
              <el-form-item label="电话:">
                <el-input v-model="formInline.phone" type="number" maxlength="11" placeholder="请输入联系人电话" size="small"
                  :clearable="true"></el-input>
              </el-form-item>
              <el-form-item label="通知方式:">
                <el-select v-model="formInline.mode" clearable size="small" class="w200" @input="InputFun($event)"
                  placeholder="请选择通知方式">
                  <el-option :label="item.name" :value="item.id" v-for="item in modeList" :key="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="mini" @click="reset">重置</el-button>
                <el-button type="primary" size="mini" @click="getlist">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-row>
        <el-row class="marginTop">
          <div class="tablecell">
            <el-row class="floatRight">
              <el-button type="primary" size="mini" @click="batchProcessing">新增</el-button>
            </el-row>
            <el-table ref="multipleTable" :data="tableData" :border="true" tooltip-effect="dark" style="width: 100%"
              :header-cell-style="rowClass" row-key="id" :default-expand-all="true"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :cell-style="{fontSize:'12px'}"
              @selection-change="handleSelectionChange" stripe height="590">
              <el-table-column type="selection" width="55">
              </el-table-column>
              <el-table-column prop="name" label="姓名" width="120">
              </el-table-column>
              <el-table-column prop="enterpriseName" label="所属单位" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="phone" label="电话" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="通知方式" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.toSms" inactive-text="短信"
                    @change="modifswitch(scope.$index, scope.row)">
                  </el-switch>
                  <el-switch v-model="scope.row.toWechat" inactive-text="公众号"
                    @change="modifswitch(scope.$index, scope.row)"></el-switch>
                  <el-switch v-model="scope.row.toVoice" inactive-text="电话"
                    @change="modifswitch(scope.$index, scope.row)"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="快捷操作" width="340">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click="modifyRoom(scope.$index, scope.row)">
                    编辑</el-button>
                  <el-button type="primary" size="mini" @click="allocationQuota(scope.$index, scope.row)">
                    分配额度</el-button>
                  <el-button type="danger" size="mini" @click="deleteAlarm(scope.$index, scope.row)">
                    删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="page">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="currentPage" :page-sizes="[10, 20, 30, 100]" :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
            </el-pagination>
          </div>
        </el-row>
      </el-card>
      <el-dialog title="分配额度" :visible.sync="dialogVisible2" width="30%" style="overflow: hidden;"
        :before-close="handleClose">
        <el-form ref="form" :model="quotaForm" label-width="120px" :inline="true" :rules="rules">
          <el-form-item label="可分配额度" prop="phone">
             <el-input v-model="balanceData" class="w200" type="number" :clearable="true" disabled></el-input>
           </el-form-item>
          <el-form-item label="现有额度" prop="phone">
             <el-input v-model="quotaForm.balance" class="w200" type="number" :clearable="true" disabled></el-input>
           </el-form-item>
          <el-form-item label="分配额度" prop="phone">
             <el-input v-model="quotaForm.distribution" class="w200" type="number" :clearable="true"></el-input>
           </el-form-item>
        </el-form>
        <!-- <Map ref="map" @close="$refs.map.close()" @updateLocation="updateLocation"></Map> -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="modifyQuotaMethods">提交</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
        <el-form ref="form" :model="formRoom" label-width="120px" :inline="true" :rules="rules">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formRoom.name" class="w200" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="接警电话" prop="phone">
            <el-input v-model="formRoom.phone" class="w200" :clearable="true"></el-input>
          </el-form-item>
         <!-- <el-form-item label="余额" prop="phone">
            <el-input v-model="formRoom.balance" class="w200" type="number" :clearable="true"></el-input>
          </el-form-item> -->
          <el-form-item label="接收类型">
            <el-select v-model="formRoom.atAlert" multiple collapse-tags placeholder="请选择">
                <el-option
                  v-for="item in atAlertList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="所属单位" prop="region">
           <!-- <el-select v-model="formRoom.region" class="w200" placeholder="请选择所属单位">
              <el-option :label="item.name" :value="item.id" v-for="item in enterpriselist" :key="item.id">
              </el-option>
            </el-select> -->
              <el-cascader :options="enterpriselist" v-model="formRoom.region" ref="cascader"  placeholder="请选择所属单位" :props="{ checkStrictly: true }" @change="checkNodeRecord" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="通知方式：">
            <el-switch v-model="formRoom.toSms" inactive-text="短信"></el-switch>
            <el-switch v-model="formRoom.toWechat" inactive-text="公众号"></el-switch>
            <el-switch v-model="formRoom.toVoice" inactive-text="电话"></el-switch>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" v-if="modifyStatus">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateRoom">修改</el-button>
        </span>
        <span slot="footer" class="dialog-footer" v-else>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">提交</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    httpGet,
    httpPost
  } from "../../api/index";
  import {
    ztreeToElementTree,
    recursion,
    ztreeToElementTree2,
    uniqueArray,
    paramsValidate
  } from "../../utils/index"
  import utils from "../../utils/util.js";
  import moment from "moment"
  export default {
    name: "alarmRecord",
    data() {
      return {
        balanceData:0,
        props: {
          multiple: true,
          emitPath: false
        },
        modeList: [{
            name: '短信',
            id: 'toSms'
          },
          {
            name: '公众号',
            id: 'toWechat'
          },
          {
            name: '电话',
            id: 'toVoice'
          },
        ],
        pageTotal: 0,
        rules: {
          region: [{
            required: true,
            message: '请选择所属单位',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: '请输入电话',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }]
        },
        dialogVisible2: false,
        titleText: '设备未处理报警记录(IMEI:860709056256857)',
        textarea: '', //批量处理备注
        dialogVisible: false,
        dialogVisible1: false,
        input: '',
        content: '切换单个/多个查询模式',
        selected: true,
        advancedQueryStatus: false,
        advancedQueryText: '高级查询',
        formInline: {
          phone: '',
          name: '',
          toSms: false,
          toVoice: false,
          toWechat: false,
          enterpriseId: '',
        },
        atAlertList:[
          {
            value: 1,
            label: '撬锁报警'
          },
          {
            value: 2,
            label: '强行开门报警'
          },
          {
            value: 7,
            label: '低电量报警'
          },
          {
            value: 9,
            label: '胁迫开锁报警'
          }
        ],
        tableData: [],
        rowStyle: {
          background: '#f8f9fa',
          fontSize: '12px'
        },
        multipleSelection: [],
        enterpriselist: [],
        formRoom: {
          name: '',
          phone: '',
          region: '',
          toWechat: false,
          toVoice: false,
          toSms: false,
          enterpriseId:'',
          atAlert:[],
          balance:0
        },
        form1: {
          address: '',
          province: '',
          city: '',
          latitude: 0, // 纬度
          longitude: 0, // 经度
          district: ''
        },
        currentPage: 1,
        currentPage1: 1,
        pageSize: 10,
        pageTotal1: 0,
        batch: true,
        zNodes: [],
        modifyRow: '',
        modifyStatus: false,
        deviceList: [],
        devicerow: '',
        userInfo: {
          type: ''
        },
        quotaForm:{balance:0},
        oldQuta:{balance:0}
      }
    },
    components: {
      // Map
    },
    computed: {

    },
    async created() {
      this.userInfo = JSON.parse(localStorage.getItem('info'))
     await this.getEnterprise()
     await this.getUserlist()
    },
    mounted() {

    },
    methods: {
      // 获取余额
      getUserlist() {
        var data = {
          q: JSON.stringify({
            id: this.userInfo.id
          })
        }
        httpGet(data, this.$api.getUserList).then(res => {
          if (res.code == 200) {
            if(res.data.total>0){
              this.balanceData = (res.data.list[0].balance/100).toFixed(2)
            }else{
              this.balanceData=0
            }
          } else {
            this.$message.error(res.message)
          }
        })
      },
      // 分配额度
      allocationQuota(index,row){
        this.dialogVisible2=true
        var data=JSON.parse(JSON.stringify(row))
        if(typeof(row.balance)=='number') {
          data.balance=(data.balance/100).toFixed(2)
          row.balance=(row.balance/100).toFixed(2)
        }
        data.distribution=0
        this.quotaForm=data
        this.oldQuta=row
      },
      modifyQuotaMethods(){
        if(Number(this.quotaForm.distribution)!=0){
          var pushData={
              alarmUserId:this.quotaForm.id,
              recharge:Number(this.quotaForm.distribution)*100
            }
          httpPost(pushData,this.$api.rechargeAlarmBalance).then(res1=>{
            if(res1.code==200){
                this.$message.success("分配成功");
                this.dialogVisible2=false
                this.getlist()
                this.getUserlist()
            }else{
              this.dialogVisible2=false
              if(res1.message == 'Insufficient balance'){
                this.$message.error("余额不足");
              }
            }
          })
        }else{
          this.dialogVisible2=false
        }
      },
      checkNodeRecordTop(e) {
        this.formInline.enterpriseId = e[e.length - 1]
      },
      checkNodeRecord(e) {
        this.formRoom.enterpriseId = e[e.length - 1]
      },
      InputFun(e) {
        if (e == 'toSms') {
          this.formInline['toSms'] = true
          this.formInline['toVoice'] = false
          this.formInline['toWechat'] = false
        } else if (e == 'toVoice') {
          this.formInline['toSms'] = false
          this.formInline['toVoice'] = true
          this.formInline['toWechat'] = false
        } else if (e == 'toWechat') {
          this.formInline['toSms'] = false
          this.formInline['toVoice'] = false
          this.formInline['toWechat'] = true
        }
      },
      modifswitch(index, row) {
        this.$confirm('是否确认修改？', '提示')
          .then(_ => {
            var data = [{
              // list: [{
                id: row.id,
                phone: row.phone,
                enterpriseId: row.enterpriseId,
                name: row.name,
                toSms: row.toSms || false,
                toVoice: row.toVoice || false,
                toWechat: row.toWechat || false
              // }]
            }];
            if (row.name == "") {
              this.$message.error("名称不能为空");
            } else if (row.phone == "") {
              this.$message.error("手机号不能为空");
            } else {
              httpPost(data, this.$api.editAlarmUser).then((res) => {
                if (res.success) {
                  this.$message.success("修改成功")
                  this.getlist();
                } else {
                  this.$message.error("修改失败")
                }
              });
            }
          }).catch(_ => {
            this.getlist();
          });
      },
      deleteAlarm(index, row) {
        var data = {
          ids: [row.id]
        }
        httpPost(data, this.$api.deleteAlarmUser).then(res => {
          if (res.success) {
            this.$message.success("删除成功")
            this.getlist();
          } else {
            this.$message.error("删除失败")
          }
        })
      },
      reset() {
        var formInline = {
          region: '',
          name: '',
          phone: '',
          mode: ''
        }
        this.formInline = formInline
      },
      // 修改房源
      modifyRoom(index, row) {
        var formRoom = {
          name: row.name,
          phone: row.phone,
          region: row.enterpriseId,
          enterpriseId:row.enterpriseId,
          toSms: row.toSms,
          toVoice: row.toVoice,
          toWechat: row.toWechat,
          balance:row.balance/100,
          atAlert:JSON.parse(row.atAlert)
        }
        this.formRoom = formRoom
        this.modifyRow = row
        this.dialogVisible = true
        this.modifyStatus = true
      },
      updateRoom() {
        var formRoom = this.formRoom
        var data = [{
          // list: [{
            id: this.modifyRow.id,
            phone: formRoom.phone,
            enterpriseId: formRoom.region,
            name: formRoom.name,
            toSms: formRoom.toSms,
            toVoice: formRoom.toVoice,
            toWechat: formRoom.toWechat
          // }]
        }];
        if (formRoom.name == "") {
          this.$message.error("名称不能为空");
        } else if (formRoom.phone == "") {
          this.$message.error("手机号不能为空");
        } else {
          httpPost(data, this.$api.editAlarmUser).then((res) => {
            if (res.success) {
              this.$message.success("修改成功")
              this.dialogVisible = false;
              this.getlist();
            } else {
              this.$message.error("修改失败")
            }
          });
        }
      },
      // 创建人员
      saveEdit() {
        var formRoom = this.formRoom
        if (formRoom.name == "") {
          this.$message.error("姓名不能为空");
        } else if (formRoom.phone == "") {
          this.$message.error("手机号不能为空");
        } else {
          var data = {
            phone: formRoom.phone,
            enterpriseId: formRoom.enterpriseId,
            name: formRoom.name,
            toSms: formRoom.toSms || false,
            toVoice: formRoom.toVoice || false,
            toWechat: formRoom.toWechat || false,
            atAlert:JSON.stringify(formRoom.atAlert)
          }
          httpPost(data, this.$api.lockAddAlarmUser).then((res) => {
            if (res.success) {
              this.dialogVisible = false;
              this.getlist();
              this.$message.success("创建成功")
            } else {
              this.$message.error("创建失败");
            }
          })
        }
      },
      yz(obj) {
        var str = {}
        Object.keys(obj).forEach(function(key) {
          if (obj[key] != '' && key != 'mode') {
            str[key] = obj[key]
          }
        })
        return str
      },
      // 获取列表
      getlist() {
        var q = this.yz(this.formInline)
        var data = {
          q: JSON.stringify(q),
          orderBy: "create_time desc",
          pageNum: this.currentPage,
          pageSize: this.pageSize
        };
        httpGet(data, this.$api.lockAlarmUsers).then((res) => {
          if (res.data.list.length > 0) {
            var list=res.data.list
            list.map(li=>{
              var name = utils.findIndexArray(this.enterpriselist, li.enterpriseId, [])
              var path = ''
              if (name) {
                path = name.join('/')
                li.enterpriseName=path
              }
            })
            this.tableData = list
            console.log(this.tableData)
            this.pageTotal = res.data.total
          } else {
            this.tableData = []
            this.pageTotal = 0
          }
        });
      },
      updateLocation(orgAddr, lon, lat, province, city, district) {
        this.form1 = {
          address: orgAddr,
          province: province,
          city: city,
          latitude: lat, // 纬度
          longitude: lon, // 经度
          district: district
        }
      },
      // 获取单位
      getEnterprise() {
        var data = {
          q: JSON.stringify({
            name: this.formInline.name
          })
        }
        httpGet(data, this.$api.getEnterprise).then((res) => {
          if (res.success) {
            res.data.list.map(li => {
              li['pid'] = li.parentId
              li['label'] = li.name
              li['value'] = li.id
            })
            var array = utils.uniqueArray(res.data.list, "id");
            var roomlistZNodes = ztreeToElementTree2(array, []);
            this.enterpriselist = roomlistZNodes
            this.getlist()
          } else {
            this.$message.error("获取失败")
          }
        });
      },
      // 未处理记录打开
      recordFun() {
        this.dialogVisible1 = true
      },
      // 未处理记录处理关闭
      handleClose1(done) {
        done();
      },
      // 批量处理关闭
      handleClose(done) {
        done();
        this.modifyStatus = false
      },
      // 批量处理
      batchProcessing() {
        this.dialogVisible = true
        this.formRoom = {
          name: '',
          address: '',
          floorNum: '',
          region: ''
        }
        this.modifyStatus = false
      },
      // 分页
      handleSizeChange(val) {
        this.pageSize = val
        this.getlist()
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getlist()
        console.log(`当前页: ${val}`);
      },
      // 表头样式
      rowClass({
        row,
        rowIndex
      }) {
        return "background:#f8f9fa;color:#333;font-blod:none;font-size:12px;"
      },
      // 表格勾选
      handleSelectionChange(val) {
        if (val.length > 0) {
          this.batch = false
        } else {
          this.batch = true
        }
      },
      // 高级查询显示
      advancedQueryFun() {
        if (this.advancedQueryStatus) {
          this.advancedQueryText = "高级查询"
          this.advancedQueryStatus = false
        } else {
          this.advancedQueryText = "同用查询"
          this.advancedQueryStatus = true
        }
      },
      // 批量处理备注监控
      textareaFun(e) {
        this.textarea = e
      },
      // 单个/多个查询切换
      switchFun() {
        this.selected = !this.selected
      }
    },
    mounted() {

    }
  }
</script>

<style scoped>
  .search {
    display: flex;
    align-items: center;
  }

  .search .inputInline {
    display: inline-block;
  }

  .topBottom {
    margin: 0 10px;
    cursor: pointer;
  }

  .topBottom .iconfont {
    display: block;
    font-size: 12px;
  }

  .topBottom .icon-xiangxia1 {
    margin-top: -3px;
  }

  .topBottom .selected {
    color: #409eff;
  }

  .textBlue {
    color: #409eff;
    font-size: 14px;
    margin-left: 10px;
    cursor: pointer;
  }

  .marginTop {
    margin-top: 20px;
  }

  .tablecell {
    border: 1px solid #eee;
  }

  .floatRight {
    float: right;
    margin: 10px;
  }

  .page {
    margin-top: 20px;
  }

  .page .el-pagination {
    margin-bottom: 0;
    float: none;
  }

  .tablecell>>>.BtnOrange {
    border: 1px solid #ffb6b6;
    color: #ff4949;
    background: #ffeded;
  }

  .tablecell>>>.BtnOrange:hover {
    background: #ff4949;
    border-color: #ff4949;
    color: #fff;
  }

  .tablecell>>>.BtnBlue {
    border: 1px solid #a3d3ff;
    color: #1890ff;
    background: #e8f4ff;
  }

  .tablecell>>>.BtnBlue:hover {
    background: #1890ff;
    border-color: #1890ff;
    color: #fff;
  }

  .dialogcontent {
    padding-bottom: 20px;
  }

  .curpoiner {
    cursor: pointer;
    display: flex;
    align-items: center;
    color: #508dfe;
  }

  .curpoiner .icon-erweima {
    font-size: 24px;
  }

  .curpoiner .operation {
    margin-left: 6px;
  }

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

  .tablecell>>>.el-table__expand-icon {
    display: inline-block;
  }
</style>
