<template>
    <d2-container>
        <div class="d2-table-view-full">
            <div class="d2-table-view-header">
                <el-form label-width="100px" labelPosition="right" size="small" :inline="true" :model="filter" @keyup.enter.native="handleList" class="demo-form-inline">
                    <el-form-item label="水控编号" prop="carTypNm">
                        <el-input style="width: 192px" v-model.trim="filter.equipId" placeholder="水控编号" clearable/>
                    </el-form-item>
                    <el-form-item label="房间名称" prop="paramCode">
                        <el-input style="width: 192px" v-model.trim="filter.roomName" placeholder="房间名称" clearable/>
                    </el-form-item>
                    <el-form-item>
                        <el-button   type="primary" @click="handleList('1')">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="d2-table-view-content">
                <div class="d2-table-view-handle">
                    <el-button @click="onCreateClick" size="small" icon="el-icon-plus">新增</el-button>
                    <el-button size="small" @click="onMutilDelClick">批量删除</el-button>
                </div>
                <d2-crud
                        title="水控设置登记"
                        ref="d2Crud"
                        :options="tableOptions"
                        :loading="loading"
                        :columns="columns"
                        :data="data"
                        :rowHandle="rowHandle"
                        @edit="handleRowEdit"
                        @delete="handleRowRemove"
                        selection-row
                        @selection-change="handleSelectionChange"
                >
                </d2-crud>
            </div>
            <div class="d2-table-view-footer">
                <el-pagination
                        @current-change="handleCurrentChange"
                        @size-change="handleSizeChange"
                        :page-size="tableOptions.pageList[0]"
                        :page-sizes="tableOptions.pageList"
                        :current-page.sync="currentPage"
                        layout="total,sizes, prev, pager, next,jumper"
                        :total="pagination.total"
                ></el-pagination>
            </div>
        </div>
        <el-dialog
                :title="diaLogName"
                :visible.sync="operVisible"
                @close="clearForm"
                width="40%"
                :close-on-click-modal="false"
        >
            <el-form ref="form" :model="form" label-width="162px" labelPosition="right" :rules="rules">
                <el-row :gutter="15">
                    <el-col :span="22">
                        <el-form-item label="水控机编号" prop="id">
                            <el-input maxlength="20" disabled v-model.trim="form.id" placeholder="系统自动生成"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="水控机名称" prop="equipmentName">
                            <el-input maxlength="15" v-model.trim="form.equipmentName" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备序列号" prop="equipmentCode">
                            <el-input maxlength="16" v-model.trim="form.equipmentCode" clearable/>                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="通讯类型" prop="communicationType">
                            <el-select v-model="form.communicationType" placeholder="请选择" style="width: 100%">
                            <el-option
                            label="串口通讯"
                            value="串口通讯">
                            </el-option>
                                <el-option
                                        label="网络通讯"
                                        value="网络通讯">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="串口编号" prop="serialNumber" v-if="!isHide">
                            <el-input maxlength="16" v-model.trim="form.serialNumber" clearable/>                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="波特率" prop="baudRate" v-if="!isHide">
                            <custom-select :value="form.baudRate" v-model="form.baudRate" typeName="水控设备波特率" style="width: 100%"></custom-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="通讯地址" prop="ip" v-if="isHide">
                            <el-input maxlength="16" v-model.trim="form.ip" clearable/>                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="通讯端口" prop="port" v-if="isHide">
                            <el-input maxlength="16" v-model.trim="form.port" clearable/>                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="房间" prop="venderCode">
                            <room-tree  ref="saffTree"  :str="form.venderCode" v-model="form.venderCode"></room-tree>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                 <el-button :loading="staLoading" @click="operInstance(1)" v-if="isShow">继续添加</el-button>
        <zl-button :loading="staLoading" @click="operInstance(2)">完成</zl-button>
      </span>
        </el-dialog>
    </d2-container>
</template>
<script>
  import { tableOptions } from '@/assets/options'
  import {getWaterDeviceRegister,saveOrUpdateWaterDevice,getWaterDeviceById,onDeleteWaterDevice,onDeleteMutilWaterDevice} from '@/api/water/waterDeviceRegister'
  export default {
    name: 'cateUser',
    components: {

    },
    data () {
      let checkCardId = (rule, value, callback) => {
        if(!value){
          return callback(new Error('不能为空'))
        }
        let reg = /^[0-9a-zA-Z]+$/
        if (!reg.test(value)) {
          return callback(new Error('请输入数字或英文'))
        } else {
          callback ()
        }
      }
      let checkIP = (rule, value, callback) => {
        let reg = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/
        if (!reg.test(value)) {
          return callback(new Error('请输入正确的IP'))
        } else {
          callback ()
        }
      }
      let checkNumber = (rule, value, callback) => {
        if(!value&&value!==0){
          return callback(new Error('不能为空'))
        }
        let reg = /^[0-9]*$/
        if (!reg.test(value)) {
          return callback(new Error('请输入数字'))
        } else {
          callback ()
        }
      }
      return {
        isShow:true,
        carTypIds:[],
        equipmentOptions:[],
        workStationOptions:[],
        options:[],
        options3:[],
        time:"",
        stationId:[],
        stationIds:"",
        isCreate:false,
        userId:"",
        checkList:[],
        // classVisible:false,
        staLoading: false,
        multipleSelection:[],
        func: {
          add: false,
          delete: false,
          update: false,
          select: false
        },
        falg: true,
        isHide:false,
        isExpend: true,
        tableOptions,
        loading: false,
        operVisible: false,
        diaLogName: '新增水控设备',
        lanuchs: [],
        form: {
          equipmentCode:"",
          equipmentName:"",
          port:"",
          baudRate:"",
          venderCode:"",
          id:"",
          communicationType:"串口通讯",
          serialNumber:"",
          ip:""
        },
        filter: {
          pageSize: 10,
          pageNum: 1,
          roomName:"",
          equipId:""
        },
        pagination: {
          total: 0
        },
        currentPage: 1,
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        columns: [
          {
            title: '水控机编号',
            key: 'id',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            title: '水控机名称',
            key: 'equipmentName',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '设备序列号',
            key: 'equipmentCode',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '通讯类型',
            key: 'communicationType',
            minWidth: '90',
          },
          {
            title: '房间编号',
            key: 'venderCode',
            minWidth: '150',
          },
          {
            title: '房间名称',
            key: 'venderName',
            minWidth: '120',
            // formatter (row, column, cellValue, index) {
            //   if (cellValue === "0") {
            //     return '固定车型'
            //   }else if(cellValue === "1"){
            //     return '收费车型'
            //   }
            // }
          }
        ],
        rowHandle: {
          columnHeader: '操作',
          minWidth: '180',
          align: 'center',
          custom: [
            {
              text: '编辑',
              type: 'primary',
              size: 'small',
              emit: 'edit'
            },
            {
              text: '删除',
              type: 'danger',
              size: 'small',
              emit: 'delete'
            }
          ]
        },
        data: [],
        rules: {
          equipmentName:[{required: true, message: '设备名称不能为空', trigger: 'blur'}],
          port:[{validator:checkNumber,required: true, message: '请输入端口', trigger: 'blur'}],
          baudRate:[{required: true, message: '请选择波特率', trigger: 'blur'}],
          venderCode:[{required: true, message: '请选择房间', trigger: 'blur'}],
          ip:[{validator:checkIP,required: true,trigger: 'blur'}],
          equipmentCode:[{validator:checkNumber,required: true, trigger: 'blur'}],
          communicationType:[{required: true, message: '请选择通讯类型', trigger: 'blur'}],
          serialNumber:[{validator:checkCardId,required: true, trigger: 'blur'}],

        }
      }
    },
watch:{
      'form.communicationType':function(val){
        if(val==='网络通讯'){
          this.isHide=true
        }else{
          this.isHide=false
        }
      }
},
    methods: {
      dateChange (val) {
        if(val == null){
          this.filter.bgTm = ''
          this.filter.endTm = ''
        }else{
          this.filter.bgTm = val[0]
          this.filter.endTm = val[1]
        }
      },
      onCreateClick(){
        this.operVisible=true
      },
      handleTreeNode () {
        this.handleList()
      },
      handleList (val) {
        if (val) {
          this.filter.pageNum = 1
          this.currentPage = 1
        }
        this.loading = true
        getWaterDeviceRegister(this.filter)
          .then(res => {
            // console.log(res)
            this.loading = false
            this.data = res.page.list
            this.pagination.total = res.page.total
          })
          .catch(err => {
            this.loading = false
          })
      },
      handleSelectionChange(val) {
        this.isCreate=false
        this.multipleSelection = val;
      },
      handleCurrentChange (val) {
        this.filter.pageNum = val
        this.handleList()
      },
      handleSizeChange (val) {
        this.filter.pageNum = 1
        this.filter.pageSize = val
        this.handleList()
      },
      operInstance (val) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.staLoading = true
            saveOrUpdateWaterDevice(this.form).then(res => {
              this.staLoading = false
              this.clearForm()
              if (val == 2) {
                this.operVisible = false
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.handleTreeNode()
              } else {
                this.clearForm()
              }
            }).catch(err => {
              this.staLoading = false
            })
          }
        })
      },
      handleRowEdit ({index, row}) {
        this.diaLogName = '修改水控设备'
        this.isShow=false
        getWaterDeviceById({id:row.id}).then(res => {
          this.form = res.waterEquipment
          if(this.form.communicationType=='网络通讯'){
            this.isHide=true
          }else{
            this.isHide=false
          }
        })
        this.operVisible = true
      },
      onMutilDelClick(){
        if(!this.multipleSelection.length){
          this.$message({
            message: '请选择记录',
            type: 'warning'
          })
        }else{
          this.$confirm(`确认删除当前水控设备?`, '确认操作', {
            confirmButtonText: '确定',
            cancelButtonText: '放弃',
            type: 'warning'
          }).then(() => {
            this.carTypIds=[]
            this.multipleSelection.forEach((item,index)=>{
              this.carTypIds.push(item.id)
            })
            onDeleteMutilWaterDevice({equipIds:this.carTypIds}).then(res=>{
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.handleTreeNode()
            })
          })
        }
      },
      handleRowRemove ({index, row}) {
        // console.log(row)
        this.$confirm(`确认删除当前水控设备?`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '放弃',
          type: 'warning'
        }).then(() => {
          onDeleteWaterDevice({id:row.id}).then(res=>{
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.handleTreeNode()
          })
        })
      },
      clearForm () {
        if (this.$refs['form']!==undefined) {
          this.$refs['form'].resetFields()
        }
        this.form ={
          equipmentCode:"",
          equipmentName:"",
          port:"",
          baudRate:"",
          venderCode:"",
          id:"",
          communicationType:"串口通讯",
          serialNumber:"",
          ip:""
        },
        this.diaLogName = '新增水控设备'
        this.isShow=true
        // this.$refs.saffTree.cleanName()
      },
    },
    mounted () {
      this.clearForm()
      this.filter.pageSize = this.tableOptions.pageList[0]
      this.tableOptions = this.$calcTableHeight(tableOptions, 51)
      this.handleTreeNode()
    }
  }
</script>
<style>
    /*.d2-table-view-full{*/
    /*height: 100%;*/
    /*}*/
    /*.timeBox{*/
    /*margin-top: 10px;*/
    /*}*/
    /*.timePay{*/
    /*margin-left: 8px;*/
    /*}*/
    /*.avatar-uploader .el-upload {*/
    /*border: 1px dashed #d9d9d9;*/
    /*border-radius: 6px;*/
    /*cursor: pointer;*/
    /*position: relative;*/
    /*overflow: hidden;*/
    /*}*/

    /*.avatar-uploader .el-upload:hover {*/
    /*border-color: #409eff;*/
    /*}*/

    /*.avatar-uploader-icon {*/
    /*font-size: 28px;*/
    /*color: #8c939d;*/
    /*width: 178px;*/
    /*height: 178px;*/
    /*line-height: 178px;*/
    /*text-align: center;*/
    /*}*/

    /*.avatar {*/
    /*width: 178px;*/
    /*height: 178px;*/
    /*display: block;*/
    /*}*/
    /*.timeLabel label{*/
    /*width: 110px !important;*/
    /*}*/
    /*.bankLabel label{*/
    /*font-size: 13px;*/
    /*}*/
    /*.el-form-item__label {*/
    /*text-align: left !important;*/
    /*}*/
    /*.d2-table-view{*/
    /*overflow: hidden;*/
    /*}*/
    /*.d2-table-view-content{*/
    /*height: 100%;*/
    /*}*/
    /*.el-table{*/
    /*height: 450px !important;*/
    /*}*/
</style>