<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.tag"
          clearable
          size="small"
          placeholder="请输入标签名"
          style="width: 170px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.description"
          clearable
          size="small"
          placeholder="请输入标签描述"
          style="width: 170px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.connId"
          clearable
          size="small"
          placeholder="所属连接"
          class="filter-item"
          style="width: 120px"
          @change="handleConnIdChenge1"
        >
          <el-option
            v-for="item in optionsObj.NetConn"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.deviceId"
          clearable
          size="small"
          placeholder="所属设备"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in deviceOpt1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.dataType"
          clearable
          size="small"
          placeholder="数据类型"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.DataType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.function"
          clearable
          size="small"
          placeholder="功能码"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.ModbusFunction"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="query.address"
          clearable
          size="small"
          placeholder="请输入数据地址"
          style="width: 170px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.tagEnable"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in statusOpt"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      width="640px"
    >
      <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="100px">
        <el-row>
          <el-form-item label="变量名" prop="tag">
            <el-input v-model="form.tag" style="width: 400px" />
          </el-form-item>
          <el-form-item label="变量描述" prop="description">
            <el-input v-model="form.description" style="width: 400px" />
          </el-form-item>
          <el-form-item label="所属连接" prop="connId">
            <el-select v-model="form.connId" style="width: 150px" placeholder="请选择" @change="handleConnIdChenge2">
              <el-option
                v-for="item in optionsObj.NetConn"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属设备" prop="deviceId">
            <el-select v-model="form.deviceId" style="width: 150px" placeholder="请选择">
              <el-option
                v-for="item in deviceOpt2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="数据类型" prop="dataType">
            <el-select v-model="form.dataType" style="width: 150px" placeholder="请选择">
              <el-option
                v-for="item in optionsObj.DataType"
                :key="item.value"
                :label="item.label"
                :value="+item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="功能码" prop="function">
            <el-select v-model="form.function" style="width: 150px" placeholder="请选择">
              <el-option
                v-for="item in optionsObj.ModbusFunction"
                :key="item.value"
                :label="item.label"
                :value="+item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="数据地址" prop="address">
            <el-tooltip
              class="item"
              effect="dark"
              content="起始地址为0，范围：0-65535"
              placement="top"
            >
              <el-input v-model="form.address" style="width: 150px" />
            </el-tooltip>
            <!-- <el-input
            v-model="form.address"
            style="width: 150px;"
          />&nbsp;&nbsp;起始地址为0，范围：0-65535 -->
          </el-form-item>

          <el-form-item label="位索引" prop="bitIndex">
            <el-tooltip
              class="item"
              effect="dark"
              content="功能码为x3或x4时，确定Bool类型位置，范围：0-15"
              placement="top"
            >
              <el-input v-model="form.bitIndex" style="width: 150px" />
            </el-tooltip>
            <!-- &nbsp;&nbsp;功能码为x3或x4时，确定Bool类型位置，范围：0-15 -->
          </el-form-item>
          <el-form-item label="数据长度" prop="length">
            <el-tooltip
              class="item"
              effect="dark"
              content="数据类型为字符串时的长度，单位：字，范围：1-100"
              placement="top"
            >
              <el-input v-model="form.length" style="width: 150px" />
            </el-tooltip>
            <!-- &nbsp;&nbsp;数据类型为字符串时的长度，单位：字，范围：1-100 -->
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="form.unit" style="width: 150px" />
          </el-form-item>
          <el-form-item label="小数位数" prop="decimals">
            <el-input-number v-model="form.decimals" controls-position="right" :min="1" :max="16" style="width: 150px" />
          </el-form-item>
          <el-form-item label="数据处理脚本" prop="valueScript">
            <el-input v-model="form.valueScript" type="textarea" autosize clearable style="width: 400px" />
          </el-form-item>
          <el-form-item label="数据启用" prop="enable">
            <el-switch
              v-model="form.enable"
              active-color="#409EFF"
              inactive-color="#E8E8E8"
              :active-value="true"
              :inactive-value="false"
              style="width: 150px"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="报警启用" prop="alarmEnable">
            <el-switch
              v-model="form.alarmEnable"
              active-color="#409EFF"
              inactive-color="#E8E8E8"
              :active-value="true"
              :inactive-value="false"
              style="width: 150px"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <template v-if="form.dataType === 1">
            <el-form-item label="报警类型" prop="boolAlarmType">
              <el-radio-group v-model="form.boolAlarmType">
                <el-radio
                  v-for="item in optionsObj.BoolAlarmType"
                  :label="+item.value"
                  :key="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </template>
          <template v-if="form.dataType === 10">
            <el-form-item label="报警字符串" prop="alarmString">
              <el-input v-model="form.alarmString" style="width: 150px" />
            </el-form-item>
          </template>
          <template v-if="!(form.dataType === 1 || form.dataType === 10)">
            <el-form-item label="高报" prop="hAlarm">
              <el-input v-model="form.hAlarm" style="width: 150px" />
            </el-form-item>
            <el-form-item label="高高报" prop="hhAlarm">
              <el-input v-model="form.hhAlarm" style="width: 150px" />
            </el-form-item>
            <el-form-item label="低报" prop="lAlarm">
              <el-input v-model="form.lAlarm" style="width: 150px" />
            </el-form-item>
            <el-form-item label="低低报" prop="llAlarm">
              <el-input v-model="form.llAlarm" style="width: 150px" />
            </el-form-item>
            <el-form-item label="报警死区" prop="alarmDeadBand">
              <el-input v-model="form.alarmDeadBand" style="width: 150px" />
            </el-form-item>
          </template>
        </el-row>
        <el-row>
          <el-form-item label="模拟启用" prop="isSimulation">
            <el-switch
              v-model="form.isSimulation"
              active-color="#409EFF"
              inactive-color="#E8E8E8"
              :active-value="true"
              :inactive-value="false"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="模拟值" prop="simulationValue">
            <el-input v-model="form.simulationValue" type="textarea" autosize clearable style="width: 400px" />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        v-for="item in modbusTagTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        v-if="checkPer(['admin', 'datacommunicationmanage:modbustag:edit', 'datacommunicationmanage:modbustag:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation :data="scope.row" :permission="permission" />
        </template>
      </el-table-column>
    </el-table>
    <pagination />
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudModbusTag from '@/api/dataComm/modbus/tag'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import { getOptions } from '@/api/dataComm/modbus/options'

// 表头配置
import { modbusTagTableOptions } from '../../tableConfig'

const defaultForm = {
  address: 0,
  bitIndex: 0,
  description: '',
  deviceId: '',
  enable: true,
  function: 1,
  id: '',
  length: 1,
  tag: '',
  token: null,
  dataType: 8,
  typeStr: '',
  unit: null,
  decimals: 3,
  valueScript: '',
  alarmEnable: false,
  hhAlarm: 0,
  hAlarm: 0,
  lAlarm: 0,
  llAlarm: 0,
  alarmDeadBand: 0,
  boolAlarmType: 1,
  alarmString: '',
  isSimulation: false,
  simulationValue: '',
  enable: true,
}

export default {
  name: 'ModbusTag',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps },
  cruds() {
    return CRUD({
      title: 'Modbus变量',
      url: 'dataCommunicationManage/modbus/tag/getList',
      listOrder: [],
      crudMethod: { ...crudModbusTag },
      optShow: {
        add: true,
        edit: true,
        del: true,
        import: true,
        export: true
      },
    })
  },
  // dicts: ['ModbusTagStatus'],
  data() {
    return {
      modbusTagTableOptions,
      rules: {
        tag: [{ required: true, message: '请输入变量名', trigger: 'blur' }],
        deviceId: [{ required: true, message: '请选择所属设备', trigger: 'blur' }],
        dataType: [{ required: true, message: '请选择数据类型', trigger: 'blur' }],
        function: [{ required: true, message: '请选择功能码', trigger: 'blur' }],
        address: [{ required: true, message: '请输入数据地址', trigger: 'blur' }],
        bitIndex: [{ required: true, message: '请输入位索引', trigger: 'blur' }],
        length: [{ required: true, message: '请输入数据长度', trigger: 'blur' }],
      },
      permission: {
        add: ['admin', 'datacommunicationmanage:modbustag:add'],
        edit: ['admin', 'datacommunicationmanage:modbustag:edit'],
        del: ['admin', 'datacommunicationmanage:modbustag:del'],
      },
      optionsObj: {
        DataType: [],
        ModbusFunction: [],
        NetConn: [],
        BoolAlarmType: [],
      },
      statusOpt: [
          { label: '启用', value: true },
          { label: '禁用', value: false }
      ],
      deviceOpt1: [],
      deviceOpt2: [],
    }
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
  },
  created() {
    this.getOptions()
    this.getDeviceOptions1()
  },
  methods: {
    [CRUD.HOOK.beforeToCU](){
      this.getDeviceOptions2()
    },
    getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        try {
          let res = await getOptions(key)
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    async handleConnIdChenge1() {
      this.query.deviceId = null
      await this.getDeviceOptions1()
      this.crud.toQuery()
    },
    async handleConnIdChenge2() {
      this.form.deviceId = null
      await this.getDeviceOptions2()
    },
    async getDeviceOptions1() {
      try {
          let res = await getOptions('device', { id: this.query.connId })
          if (res.code === 20000) this.deviceOpt1 = res.data.content
        } catch (error) {
          console.log(error)
        }
    },
    async getDeviceOptions2() {
      try {
          let res = await getOptions('device', { id: this.form.connId })
          if (res.code === 20000) this.deviceOpt2 = res.data.content
        } catch (error) {
          console.log(error)
        }
    }
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
