<template>
  <div>
    <!--工具栏-->
    <div class="head-container" style="display: flex; justify-content: space-between; align-items: center;">
      <div class="head-search" style="margin-bottom: 0;">
        <el-select v-model="deviceType" class="filter-item" placeholder="设备类型选择" @change="crud.toQuery">
          <el-option :key="0" label="全部" value="" />
          <el-option v-for="item in deviceTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-input v-model="query.ruleName" clearable size="small" placeholder="输入设备编号或名称" prefix-icon="el-icon-search" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation />
      </div>
      <crudOperation :permission="permission">
        <template v-slot:left>
          <el-button v-permission="permission.add" size="mini" @click="deviceSelectVisible = true">
            <i class="iconfont icon-xinzeng" />
            新增
          </el-button>
        </template>
        <template v-slot:right>
          <el-button slot="reference" v-permission="permission.del" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)">
            <i class="iconfont icon-shanchu" />
            删除
          </el-button>
        </template>
      </crudOperation>
    </div>
    <!--表单组件-->
    <el-dialog
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      append-to-body
      :before-close="handleCloseDialog"
      :visible.sync="deviceSelectVisible"
      title="新增设备-选择设备类型"
    >
      <div class="setting-dialog">
        <el-form ref="deviceForm" inline :model="deviceForm" size="small" label-width="90px">
          <el-form-item label="设备类型" prop="deviceType" :rules="[{ required:true, message:'请选择设备类型', trigger:'change'}]">
            <el-select v-model="deviceForm.deviceType" class="filter-item" value-key="id" placeholder="设备类型" style="width: 550px;">
              <el-option v-for="item in deviceTypeOptions" :key="item.id" :label="item.name" :value="item" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="handleCloseDialog">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="handleComfirmDevice">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      append-to-body
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="addDeviceTitle"
    >
      <div class="setting-dialog">
        <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="90px">
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="设备编号" prop="code">
            <el-input v-model="form.code" />
          </el-form-item>
          <el-row>
            <el-form-item label="品牌厂商" prop="supplier">
              <el-select v-model="form.supplier" class="filter-item" placeholder="请选择" style="width: 225px;">
                <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item v-if="selectedDeviceType === '密集架' || selectedDeviceType === '回转柜' || selectedDeviceType === '网络视频录像机（NVR）' || selectedDeviceType ==='环境监控主机' || isInsidedevices" label="IPv4地址" prop="deviceIp">
            <el-input v-model="form.deviceIp" />
          </el-form-item>
          <el-form-item v-if="selectedDeviceType === '密集架' || selectedDeviceType === '回转柜' || selectedDeviceType === '环境监控主机' || isInsidedevices" label="端口" prop="port" style="margin-right: 0; margin-left: 30px;">
            <el-input v-model="form.port" />
          </el-form-item>
          <el-form-item v-if="selectedDeviceType === '网络视频录像机（NVR）'" label="RTSP端口" prop="port" style="margin-right: 0; margin-left: 30px;">
            <el-input v-model="form.port" placeholder="RTSP端口一般均为554" />
          </el-form-item>

          <el-form-item v-if="selectedDeviceType === '回转柜' || selectedDeviceType === '网络视频录像机（NVR）'" label="账号" prop="deviceAccount">
            <el-input v-model="form.deviceAccount" />
          </el-form-item>
          <el-form-item v-if="selectedDeviceType === '回转柜' || selectedDeviceType === '网络视频录像机（NVR）'" label="密码" prop="devicePassword" style="margin-right: 0; margin-left: 30px;">
            <el-input v-model="form.devicePassword" />
          </el-form-item>

          <!-- 密集架 -->
          <el-row>
            <el-form-item v-if="selectedDeviceType === '密集架'" label="区号" prop="areaNo">
              <el-input v-model="form.areaNo" :disabled="crud.status.edit === 1" />
            </el-form-item>
          </el-row>
          <el-form-item v-if="selectedDeviceType === '密集架'" label="总列数" prop="sumColumnNo">
            <el-input v-model.number="form.sumColumnNo" :disabled="crud.status.edit === 1" />
          </el-form-item>
          <el-form-item v-if="selectedDeviceType === '密集架'" label="起始列号" prop="firstColumnNo">
            <el-input v-model.number="form.firstColumnNo" :disabled="crud.status.edit === 1" />
          </el-form-item>
          <el-form-item v-if="selectedDeviceType === '密集架'" label="节数" prop="partNo">
            <el-input v-model.number="form.partNo" :disabled="crud.status.edit === 1" />
          </el-form-item>

          <!-- 密集架 || 回转柜 -->
          <el-form-item v-if="selectedDeviceType === '密集架' || selectedDeviceType === '回转柜'" label="层数" prop="rowNo">
            <el-input v-model.number="form.rowNo" :disabled="crud.status.edit === 1" />
          </el-form-item>
          <!-- 回转柜 -->
          <el-form-item v-if="selectedDeviceType === '回转柜'" label="每层列数" prop="columnRowNo">
            <el-input v-model.number="form.columnRowNo" :disabled="crud.status.edit === 1" />
          </el-form-item>
          <!-- 密集架 || 回转柜 -->
          <el-row>
            <el-form-item v-if="selectedDeviceType === '密集架' || selectedDeviceType === '回转柜'" class="checkbox-style" label="系统联动" prop="isLinkage">
              <el-checkbox v-model="form.isLinkage.lend" @change="checked=>isLinkageChange(checked,'lend')">借出</el-checkbox>
              <el-checkbox v-model="form.isLinkage.borrow" @change="checked=>isLinkageChange(checked,'borrow')">归还</el-checkbox>
              <el-checkbox v-model="form.isLinkage.inBound" @change="checked=>isLinkageChange(checked,'inBound')">入库</el-checkbox>
              <el-checkbox v-model="form.isLinkage.outBound" @change="checked=>isLinkageChange(checked,'outBound')">出库</el-checkbox>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item v-if="selectedDeviceType === '密集架' || selectedDeviceType === '回转柜'" class="checkbox-style" label="设备回调" prop="isCallback">
              <el-checkbox v-model="form.isCallback.lend" @change="checked=>isCallbackChange(checked,'lend')">借出</el-checkbox>
              <el-checkbox v-model="form.isCallback.borrow" @change="checked=>isCallbackChange(checked,'lend')">归还</el-checkbox>
              <el-checkbox v-model="form.isCallback.inBound" @change="checked=>isCallbackChange(checked,'lend')">入库</el-checkbox>
              <el-checkbox v-model="form.isCallback.outBound" @change="checked=>isCallbackChange(checked,'lend')">出库</el-checkbox>
            </el-form-item>
          </el-row>
          <el-form-item v-if="selectedDeviceType === '密集架' || selectedDeviceType === '回转柜'" label="下发通知" prop="isNotice" style="display: block;">
            <el-checkbox v-model="form.isNotice">通知</el-checkbox>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="4" style="width: 585px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="crud.status.edit === 1 && ( selectedDeviceType === '网络视频录像机（NVR）' || selectedDeviceType ==='环境监控主机')" class="device-child-btn" @click="handleChildDevice"><i class="iconfont icon-zishebeiguanli" />子设备管理</el-button>
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <!--表格渲染-->
    <div class="container-right">
      <span class="right-top-line" />
      <span class="left-bottom-line" />
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        row-key="id"
        highlight-current-row
        style="min-width: 100%;"
        @selection-change="crud.selectionChangeHandler"
        @row-click="clickRowHandler"
        @cell-dblclick="tableDoubleClick"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column label="子设备" prop="child" min-width="80" />
        <el-table-column label="设备类型" prop="deviceTypeId.name" min-width="200" />
        <el-table-column label="设备名称" prop="deviceName" min-width="140" />
        <el-table-column label="设备编号" prop="deviceCode" min-width="85" />
        <el-table-column label="接口IP" prop="deviceIp" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.deviceIp"> {{ scope.row.deviceIp }} </span>
            <span v-else>——</span>
          </template>
        </el-table-column>
        <el-table-column label="端口" prop="devicePort" min-width="85">
          <template slot-scope="scope">
            <span v-if="scope.row.devicePort"> {{ scope.row.devicePort }} </span>
            <span v-else>——</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="categoryName" min-width="60" align="center">
          <template slot-scope="scope">
            <span :class="{ 'spk-a': scope.row.deviceState === 1, 'off-line': scope.row.deviceState !== 1 }" />
          </template>
        </el-table-column>
        <el-table-column label="所属库房" prop="categoryName" min-width="120" />
        <el-table-column label="所属区域" prop="storeroomId.name" min-width="120" />
        <el-table-column label="设备厂商" prop="supplierId.name" min-width="120" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建日期" min-width="180">
          <template slot-scope="scope">
            <div>{{ scope.row.createTime | parseTime }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="最后一次同步时间" min-width="180">
          <template slot-scope="scope">
            <div>{{ scope.row.createTime | parseTime }}</div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination v-if="crud.data.length!==0" />
    </div>
    <!-- 子设备管理 -->
    <ChildDevice ref="childDevice" :selected-device-type="selectedDeviceType" />
    <!-- 详情 -->
    <DetailModule ref="detailModule" :selected-device-type="selectedDeviceType" @childDevice="handleChildDevice" />
  </div>
</template>

<script>
import typeJson from './type.json'
import crudDevice from '@/api/storeManage/deviceManage/device'
import CRUD, { presenter, header, form } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import ChildDevice from './module/childDevice'
import DetailModule from './module/detail'
import { mapGetters } from 'vuex'

const defaultForm = {
  id: null,
  name: null,
  code: null,
  deviceIp: null,
  port: null,
  remark: null,
  supplier: null,
  deviceAccount: null,
  devicePassword: null,
  isLinkage: { stateType: 1, lend: false, borrow: false, inBound: false, outBound: false },
  isCallback: { stateType: 2, lend: false, borrow: false, inBound: false, outBound: false },
  isNotice: false,
  rowNo: null,
  columnRowNo: null,
  areaNo: null, sumColumnNo: null, firstColumnNo: null, partNo: null
}

export default {
  name: 'DeviceTableList',
  components: { rrOperation, crudOperation, pagination, ChildDevice, DetailModule },
  cruds() {
    return CRUD({ title: '设备', url: 'api/device/list', crudMethod: { ...crudDevice }, optShow: {
      add: false,
      edit: true,
      del: false,
      reset: true,
      download: false,
      group: false
    }})
  },
  mixins: [presenter(), header(), form(defaultForm)],
  props: {
    selectedStore: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      deviceType: null,
      deviceTypeOptions: [],
      deviceSelectVisible: false,
      deviceForm: {
        deviceType: null
      },
      addDeviceTitle: '',
      supplierOptions: [],
      selectedDeviceType: '网络视频录像机（NVR）',
      permission: {
        add: ['admin', 'device:add'],
        edit: ['admin', 'device:edit'],
        del: ['admin', 'device:del']
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ]),
    isInsidedevices() {
      if (this.selectedDeviceType === '桌面式RFID读写器') {
        return true
      } else {
        return false
      }
    },
    isOutsidedevices() {
      if (this.selectedDeviceType === '通道门' || this.selectedDeviceType === '手持式RFID读写器') {
        return true
      } else {
        return false
      }
    },
    rules() {
      // const checkDeviceIp = (rule, value, callback) => {
      //   const reg = /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/
      //   if (reg.test(value)) {
      //     callback()
      //   } else {
      //     callback(new Error('设备IP格式错误'))
      //   }
      // }
      const checkDevicePort = (rule, value, callback) => {
        const reg = /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('端口号输入错误'))
        }
      }
      const validateRule = {
        // supplier: [
        //   { required: true, message: '请选择设备产商', trigger: 'blur' }
        // ]
        code: [{ required: true, message: '设备编号不可为空', trigger: 'blur' }],
        name: [{ required: true, message: '设备名称不可为空', trigger: 'blur' }]
      }
      // if (this.isInsidedevices || this.isOutsidedevices) {
      //   this.$set(validateRule, 'deviceId', [
      //     { required: true, message: '请输入设备ID', trigger: 'blur' }
      //   ])
      // }
      if (this.selectedDeviceType === '密集架' || this.selectedDeviceType === '回转柜' || this.selectedDeviceType === '网络视频录像机（NVR）' || this.selectedDeviceType === '环境监控主机' || this.isInsidedevices) {
        this.$set(validateRule, 'deviceIp', [
          { required: true, message: '请输入接口IP', trigger: 'blur' }
          // ,
          // { validator: checkDeviceIp, trigger: 'blur' }
        ])
        this.$set(validateRule, 'port', [
          { required: true, message: '请输入端口号', trigger: 'blur' },
          { validator: checkDevicePort, trigger: 'blur' }
        ])
        if (this.selectedDeviceType === '密集架') {
          this.$set(validateRule, 'areaNo', [
            { required: true, message: '请输入区号', trigger: 'blur' }
          ])
          this.$set(validateRule, 'firstColumnNo', [
            { required: true, message: '请输入起始列号', trigger: 'blur' }
          ])
          this.$set(validateRule, 'sumColumnNo', [
            { required: true, message: '请输入总列数', trigger: 'blur' }
          ])
          this.$set(validateRule, 'partNo', [
            { required: true, message: '请输入节数', trigger: 'blur' }
          ])
          this.$set(validateRule, 'rowNo', [
            { required: true, message: '请输入层数', trigger: 'blur' }
          ])
        } else if (this.selectedDeviceType === '回转柜' || this.selectedDeviceType === '网络视频录像机（NVR）') {
          // 回转柜 || 网络视频录像机（NVR）
          this.$set(validateRule, 'deviceAccount', [
            { required: true, message: '请输入账号', trigger: 'blur' }
          ])
          this.$set(validateRule, 'devicePassword', [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ])
          if (this.selectedDeviceType === '回转柜') {
            this.$set(validateRule, 'cupboardNo', [
              { required: true, message: '请输入柜号', trigger: 'blur' }
            ])
            this.$set(validateRule, 'rowNo', [
              { required: true, message: '请输入层数', trigger: 'blur' }
            ])
            this.$set(validateRule, 'columnRowNo', [
              { required: true, message: '请输入每层列数', trigger: 'blur' }
            ])
          } else {
            // 网络视频录像机（NVR）
            // this.$set(validateRule, 'videoRoute', [
            //   { required: true, message: '请输入频道', trigger: 'blur' }
            // ])
          }
        }
      }
      return validateRule
    }
  },
  watch: {
    selectedStore: function(newValue, oldValue) {
      this.crud.refresh()
    }
  },
  created() {
    this.deviceTypeOptions = typeJson.data
    this.crud.data = [
      { id: '7305DE3D273B0CAC079538', deviceTypeId: { name: '网络视频录像机（NVR）' }},
      { id: 'C09A1946216E496BB3FA88', deviceTypeId: { name: '环境监控主机' }},
      { id: 'DD656054BE3D1DF1E2F1FC', deviceTypeId: { name: '密集架' }},
      { id: '65D1886B0F864291766421', deviceTypeId: { name: '通道门' }},
      { id: 'E2767FEACA9CE0E3B16B89', deviceTypeId: { name: '桌面式RFID读写器' }},
      { id: '3B85FA21FDAFBB618B5D40', deviceTypeId: { name: '手持式RFID读写器' }}
    ]
  },
  methods: {
    // 获取数据前设置默认参数
    [CRUD.HOOK.beforeRefresh]() {
    },
    [CRUD.HOOK.afterRefresh](crud) {
      // this.crud.data = [
      //   { id: 1, deviceTypeId: { name: '网络视频录像机（NVR）' }},
      //   { id: 2, deviceTypeId: { name: '环境监控主机' }},
      //   { id: 3, deviceTypeId: { name: '密集架' }},
      //   { id: 4, deviceTypeId: { name: '通道门' }},
      //   { id: 5, deviceTypeId: { name: '桌面式RFID读写器' }},
      //   { id: 6, deviceTypeId: { name: '手持式RFID读写器' }}
      // ]
    },
    async [CRUD.HOOK.beforeToEdit](crud, form, btn) {
      // crud.status.edit = CRUD.STATUS.PREPARED
      // crud.getDataStatus(this.crud.selections[0].id).edit = CRUD.STATUS.PREPARED

      if (form.deviceTypeId.name === '密集架' || form.deviceTypeId.name === '回转柜') {
        if (form.deviceTypeId.name === '密集架') {
          // 获取密集架行号列号等信息
          await crudDevice.getDesecabinetById({ deviceInfoId: this.crud.selections[0].id }).then((data) => {
            form.rowNo = data.rowNo
            form.areaNo = data.areaNo
            form.sumColumnNo = data.sumColumnNo
            form.firstColumnNo = data.firstColumnNo
            form.partNo = data.partNo
            form.storeroomCode = data.storeroomCode
          })
        } else if (form.deviceTypeId.name === '回转柜') {
          // 获取回转柜行号列号等信息
          await crudDevice.getRotarycabinetById({ deviceInfoId: this.crud.selections[0].id }).then((data) => {
            form.columnRowNo = data.columnRowNo
            form.cupboardNo = data.cupboardNo
            form.rowNo = data.rowNo
            form.storeroomCode = data.storeroomCode
          })
        }
        // 获取联动和回调结果
        await crudDevice.getDeviceById({ deviceInfoId: this.crud.selections[0].id }).then((data) => {
          if (data.length === 3) {
            form.isLinkage = data.find(element => element.stateType === 1)
            form.isCallback = data.find(element => element.stateType === 2)
          }
        })
      }
      // form.supplier = form.supplierId.id

      // this.deviceForm.deviceType = null
      // this.$refs.deviceForm.resetFields()
      this.selectedDeviceType = form.deviceTypeId.name
      this.addDeviceTitle = '编辑设备 - ' + form.deviceTypeId.name
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      return false
    },
    // 防止编辑时，isLinkage是null,isLinkage.lend报错
    [CRUD.HOOK.afterRefresh](crud) {
      crud.data.forEach(element => {
        element.isLinkage = { stateType: 1, lend: null, borrow: null, inBound: null, outBound: null }
        element.isCallback = { stateType: 2, lend: null, borrow: null, inBound: null, outBound: null }
      })
    },
    // table - 双击查看详情
    tableDoubleClick(row) {
      this.selectedDeviceType = row.deviceTypeId.name
      this.$refs.detailModule.detailTitle = '设备详情-' + row.deviceTypeId.name
      this.$refs.detailModule.detailVisible = true
      this.$refs.detailModule.activeIndex = 0
      // this.$refs.archivesInfo.getDetial(row.id)
    },
    handleComfirmDevice() {
      this.$refs.deviceForm.validate((valid) => {
        console.log('valid', valid)
        if (valid) {
          this.deviceSelectVisible = false
          this.selectedDeviceType = this.deviceForm.deviceType.name
          this.addDeviceTitle = '新增设备 - ' + this.selectedDeviceType
          this.crud.toAdd()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    isLinkageChange(value, type) {
      if (!value && this.form.isCallback[type]) {
        this.$message.error('取消对应回调选项后才能取消联动操作')
        this.form.isLinkage[type] = true
      }
    },
    isCallbackChange(value, type) {
      if (value && !this.form.isLinkage[type]) {
        this.$message.error('选中对应联动选项后才能勾选回调操作')
        this.form.isCallback[type] = false
      }
    },
    clickRowHandler(row) {
      this.$refs.table.toggleRowSelection(row)
    },
    selectionChangeHandler(val) {
      this.crud.selections = val
    },
    toDelete(datas) {
      this.$confirm('此操作将删除当前所选' + this.crud.title + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.crud.delAllLoading = true
        const ids = []
        datas.forEach(val => {
          ids.push(val.id)
        })
        crudDevice.del(ids).then(() => {
          this.crud.notify('删除成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.delAllLoading = false
          this.crud.refresh()
        }).catch(err => {
          this.crud.delAllLoading = false
          console.log(err)
        })
      }).catch(() => {
      })
    },
    handleChildDevice() {
      this.$refs.childDevice.childDeviceVisible = true
      this.$refs.childDevice.childDeviceTitle = '子设备管理 - ' + this.selectedDeviceType
    },
    handleCloseDialog(done) {
      // 重置表单数据
      if (this.$refs.deviceForm) {
        this.deviceSelectVisible = false
        this.$refs.deviceForm.resetFields()
      }
      if (this.$refs.form) {
        this.crud.cancelCU()
        this.$refs.form.resetFields()
      }
      // 关闭弹框
      // done()
    }
  }
}
</script>

<style lang="scss" scoped>

::v-deep .el-dialog .el-dialog__body{
  .checkbox-style.el-form-item{
    .el-form-item__content{
      width: 550px !important;
    }
  }
}

</style>
