<template>
  <a-modal
    class="StoreAssociatedEquipmentModal-wrap"
    centered
    title="关联摄像设备"
    :width="1000"
    :footer="null"
    :destroyOnClose="true"
    @cancel="isShow = false"
    v-model="isShow">
    <!-- 搜索设备 -->
    <div class="search-con" @blur="isFocus=false">
      <a-input-search
        id="equipment-search"
        class="search-s"
        allow-clear
        placeholder="请通过设备国标ID搜索"
        enter-button="查询"
        size="large"
        @blur="noData=0"
        @focus="isFocus=true"
        @search="onSearch"
      />
      <a-card class="search-sub" :bordered="false">
        <div class="noData" v-if="noData==1" style="text-align: center;">未查询到结果</div>
        <div class="search-sub-item" v-if="resultData && isFocus">
          <p>{{ resultData.name }}</p>
          <a-button
            id="equipment-bind"
            v-if="!resultData.params"
            type="primary"
            ghost
            size="small"
            @click="onBundling(resultData)"
            v-hasPermission="'B_store_device_bind'">立即绑定</a-button>
          <a-button v-else disabled type="link">已绑定</a-button>
        </div>
      </a-card>
    </div>
    <!-- 已绑设备 -->
    <div class="eq-tit">已绑设备：</div>
    <a-table
      class="table"
      ref="table"
      bordered
      size="small"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data-source="equipmentData"
      :pagination="false"
      :expandedRowKeys="expandedRowKeys"
      @expand="eqExpand"
      @expandedRowsChange="expandedRowsChange">
      <div slot="expandedRowRender" slot-scope="record" style="margin: 30px 30px;">
        <div class="eq-subTit">设备通道（机位）：</div>
        <a-table
          ref="tables"
          bordered
          size="small"
          :rowKey="(record) => record.gbId"
          :columns="passagewayColumns"
          :data-source="record.passagewayData"
          :pagination="false">
          <template slot="action" slot-scope="record">
            <a-button type="link" id="equipment-edit" @click="onEdit(record)" v-hasPermission="'B_store_deviceTd_edit'">编辑</a-button>
          </template>
        </a-table>
      </div>
      <template slot="action" slot-scope="record">
        <a-button
          type="primary"
          ghost
          size="small"
          id="equipment-unBind"
          @click="onUnbundling(record)"
          v-hasPermission="'B_store_device_unbind'">解绑</a-button>
      </template>
    </a-table>
    <!-- 编辑  通道/机位名称 -->
    <a-modal
      class="passagewayModal"
      title="编辑"
      centered
      :visible="visible"
      :footer="null"
      :closable="true"
      @cancel="visible=false"
      width="600px">
      <!-- 表单 -->
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item label="名称" prop="deviceName">
          <a-input v-model.trim="form.deviceName" id="equipment-name" :maxLength="30" placeholder="请输入名称,30个字以内" />
        </a-form-model-item>
        <a-form-model-item class="btn-cont">
          <a-button type="primary" id="equipment-save" @click="onSubmit">保存</a-button>
          <a-button class="cancel" id="equipment-cancel" @click="visible=false">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-modal>
</template>

<script>
import { findStoreVsDevice, unbindVsDevice, findVsDevice, bindVsDevice } from '@/api/storeVsDevice.js'
import { vsDeviceChannels, vsDeviceRename } from '@/api/vsDevice.js'
export default {
  name: 'StoreAssociatedEquipmentModal',
  props: {
    openModal: {
      //  弹框是否展示
      type: Boolean,
      default: false
    },
    storeId: {
      //  门店id
      type: String,
      default: ''
    },
    storeCode: {
      //  门店code
      type: String,
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  弹框是否展示
      columns: [
        { title: '序号', dataIndex: 'no', width: 60, align: 'center' },
        { title: '设备名称', dataIndex: 'vsDeviceName', width: 100, align: 'center' },
        { title: '设备ID', dataIndex: 'vsDeviceId', width: 150, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 80, align: 'center' }
      ],
      equipmentData: [], //  已绑设备
      passagewayData: [], //  设备通道
      passagewayColumns: [
        { title: '序号', dataIndex: 'no', width: 60, align: 'center' },
        { title: '设备通道名称', dataIndex: 'name', width: 100, align: 'center' },
        { title: '设备ID', dataIndex: 'deviceId', width: 150, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 80, align: 'center' }
      ],
      visible: false, //  编辑  通道/机位名称
      form: {
        deviceName: '' //  名称
      },
      rules: { //  表单校验规则
        deviceName: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      resultData: null, //  设备搜索结果
      noData: 0,
      isFocus: false, //  搜索框是否获取焦点
      vsDeviceId: '', //  设备id
      deviceId: '', //  设备通道id
      expandedRowKeys: []
    }
  },
  methods: {
    //  搜索设备
    onSearch (value) {
      if (value) {
        findVsDevice({ id: value }).then(res => {
          if (res.status == 200) {
            if (res.data) {
              this.noData = 2
              this.resultData = res.data
            } else {
              this.noData = 1
              this.resultData = null
            }
          }
        })
      } else {
        this.noData = 0
        this.resultData = null
        this.isFocus = false
      }
    },
    //  门店已绑设备
    getStoreEquipment (id) {
      findStoreVsDevice({ code: id }).then(res => {
        if (res.status == 200) {
          res.data.map((item, ind) => {
            item.no = ind + 1
          })
          this.equipmentData = res.data
        }
      })
    },
    //  解绑
    onUnbundling (item) {
      const _this = this
      _this.$confirm({
        title: '提示',
        centered: true,
        content: '确定解绑该设备吗？',
        onOk () {
          unbindVsDevice({ id: item.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.getStoreEquipment(_this.storeCode)
            }
          })
        }
      })
    },
    //  绑定
    onBundling (item) {
      const _this = this
      _this.$confirm({
        title: '提示',
        centered: true,
        content: '确定要绑定该设备吗？',
        onOk () {
          bindVsDevice({ storeCode: _this.storeCode, vsDeviceId: item.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.expandedRowKeys = []
              _this.resultData = null
              _this.isFocus = false
              _this.getStoreEquipment(_this.storeCode)
            }
          })
        }
      })
    },
    //  编辑  通道/机位名称
    onEdit (item) {
      this.form.deviceName = item.name
      this.deviceId = item.deviceId
      this.visible = true
    },
    //  提交更改的通道信息
    onSubmit () {
      const _this = this
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(_this.form))
          formData.deviceId = this.deviceId
          vsDeviceRename(formData).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.visible = false
              _this.getDeviceChannels()
            }
          })
        } else {
          return false
        }
      })
    },
    //  设备行展开事件
    eqExpand (expanded, record) {
      if (expanded) { //  展开行
        this.vsDeviceId = record.vsDeviceId
        this.getDeviceChannels()
      }
    },
    //  展开的行变化时触发
    expandedRowsChange (expandedRows) {
      this.expandedRowKeys = expandedRows
    },
    //  获取设备通道信息
    getDeviceChannels () {
      vsDeviceChannels({ id: this.vsDeviceId }).then(res => {
        if (res.status == 200) {
          if (res.data) {
            res.data.map((item, ind) => {
              item.no = ind + 1
            })
            const ind = this.equipmentData.findIndex(item => item.vsDeviceId == this.vsDeviceId)
            if (ind != -1) {
              this.$set(this.equipmentData[ind], 'passagewayData', res.data)
            }
            this.passagewayData = res.data
          } else {
            const ind = this.equipmentData.findIndex(item => item.vsDeviceId == this.vsDeviceId)
            if (ind != -1) {
              this.$set(this.equipmentData[ind], 'passagewayData', [])
            }
          }
        }
      })
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (val) {
      if (!val) {
        this.$emit('close')
      } else {
        //  重置信息
        this.expandedRowKeys = []
        this.resultData = null
        this.isFocus = false
      }
    },
    storeCode (newValue, oldValue) {
      if (newValue && this.isShow) {
        this.getStoreEquipment(newValue)
      }
    }
  }
}
</script>

<style lang="less">
  .StoreAssociatedEquipmentModal-wrap{
    .search-con{
      position: relative;
      .search-s{
        .ant-input-group-addon{
          padding: 0;
          border: none;
        }
      }
      .search-sub{
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        position: absolute;
        left: 0;
        top: 45px;
        width: 100%;
        z-index: 1;
        border-radius: 6px;
        .ant-card-body{
          padding: 15px 24px;
        }
        .search-sub-item{
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 8px 0;
          border-bottom: 1px dashed #f8f8f8;
          p{
            margin: 0;
          }
          &:last-child{
            border-bottom: none;
          }
        }
      }
    }
    .eq-tit{
      line-height: 40px;
      font-size: 16px;
      margin: 85px 0 5px;
    }
    .eq-subTit{
      margin: 0 0 10px;
    }
    .table{
      padding-bottom: 50px;
    }
  }
  .btn-cont{
    text-align: center;
    .cancel{
      margin-left: 40px;
    }
  }
</style>
