<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">数据id</label>
        <el-input
          v-model="query.dataId"
          clearable
          placeholder="数据id"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">采集端（硬件）点名</label>
        <el-input
          v-model="query.callTheRoll"
          clearable
          placeholder="采集端（硬件）点名"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">关联分组id</label>
        <!-- <el-input
          v-model="query.groupId"
          clearable
          placeholder="关联分组id"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        /> -->
        <el-cascader
          v-model="value"
          clearable
          :options="drive"
          :props="props"
          :show-all-levels="true"
          @keyup.enter.native="crud.toQuery"
          @change="handleChange"
        />
        <date-range-picker
          v-model="query.updateTime"
          start-placeholder="updateTimeStart"
          end-placeholder="updateTimeStart"
          class="date-item"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="80px"
        >
          <el-form-item label="采集端（硬件）点名" prop="callTheRoll">
            <el-input v-model="form.callTheRoll" style="width: 370px" />
          </el-form-item>
          <el-form-item label="采集端描述">
            <el-input v-model="form.describe" style="width: 370px" />
          </el-form-item>
          <el-form-item label="采集端数据类型" prop="dataType">
            <el-select v-model="form.dataType" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.modbus_data_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集端寄存器类型" prop="hardwareRegisterType">
            <el-select
              v-model="form.hardwareRegisterType"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in dict.hardware_register_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集端寄存器地址" prop="hardwareRegisterAddress">
            <el-input
              v-model="form.hardwareRegisterAddress"
              style="width: 370px"
            />
          </el-form-item>
          <el-form-item label="采集端启用取位用逗号分隔" prop="isFetchBit">
            <el-switch
              v-model="fetch_bit"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <el-select
              v-model="form.isFetchBit"
              :disabled="!fetch_bit"
              multiple
              placeholder="请选择"
              @change="submitBtn"
            >
              <el-option
                v-for="item in dict.hardware_fetch_bit"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集端关联线性转换id">
            <el-switch
              v-model="ConversionId"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <el-button
              :disabled="!ConversionId"
              type="success"
              @click="innerVisible = true"
            >设置</el-button>
          </el-form-item>
          <el-form-item
            label="转发端(软件)寄存器类型"
            prop="softwareRegisterType"
          >
            <el-select
              v-model="form.softwareRegisterType"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in dict.software_register_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="转发端(软件)寄存器地址"
            prop="softwareRegisterAddress"
          >
            <el-input
              v-model="form.softwareRegisterAddress"
              style="width: 370px"
            />
          </el-form-item>
          <el-form-item label="关联分组id" prop="groupId">
            <el-cascader
              v-model="value2"
              clearable
              :options="drive"
              :props="props"
              :show-all-levels="true"
              @change="handleTableChange"
            />
            <!-- <el-cascader :props="props" /> -->
          </el-form-item>
        </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
          width="30%"
          title="Tag线性转换设置"
          :visible.sync="innerVisible"
          append-to-body
          center
        >
          <el-tabs type="border-card">
            <el-tab-pane label="比例缩放">
              <div class="Offset">
                <el-form ref="form" :model="Offset" label-width="80px">
                  <el-form-item label="偏移量：">
                    <el-input v-model="Offset.name" />
                  </el-form-item>
                </el-form>
              </div>
              <div class="double">
                <ul>
                  <li>
                    <fieldset id="downbox">
                      <legend>原始数据</legend>
                      <div class="wximg">
                        <el-form ref="form" :model="Offset" label-width="80px">
                          <el-form-item label="最小值">
                            <el-input v-model="Offset.originalMin" />
                          </el-form-item>
                          <el-form-item label="最大值">
                            <el-input v-model="Offset.originalMax" />
                          </el-form-item>
                        </el-form>
                      </div>
                    </fieldset>
                  </li>
                  <li>
                    <fieldset id="downbox">
                      <legend>工程数据</legend>
                      <div class="wximg">
                        <el-form ref="form" :model="Offset" label-width="80px">
                          <el-form-item label="最小值">
                            <el-input v-model="Offset.engineeringMin" />
                          </el-form-item>
                          <el-form-item label="最大值">
                            <el-input v-model="Offset.engineeringMax" />
                          </el-form-item>
                        </el-form>
                      </div>
                    </fieldset>
                  </li>
                </ul>
              </div>
            </el-tab-pane>
          </el-tabs>
          <span slot="footer" class="dialog-footer">
            <el-button @click="innerVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="innerVisible = false"
            >确 定</el-button>
          </span>
        </el-dialog>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="dataId" label="数据id" />
        <el-table-column prop="callTheRoll" label="采集端（硬件）点名" />
        <el-table-column prop="describe" label="采集端描述" />
        <el-table-column prop="dataType" label="采集端数据类型">
          <template slot-scope="scope">
            {{ dict.label.modbus_data_type[scope.row.dataType] }}
          </template>
        </el-table-column>
        <el-table-column prop="hardwareRegisterType" label="采集端寄存器类型">
          <template slot-scope="scope">
            {{
              dict.label.hardware_register_type[scope.row.hardwareRegisterType]
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="hardwareRegisterAddress"
          label="采集端寄存器地址"
        />
        <!--        <el-table-column prop="isFetchBit" label="采集端启用取位用逗号分隔">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ dict.label.hardware_fetch_bit[scope.row.isFetchBit] }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column-->
        <!--          prop="linearConversionId"-->
        <!--          label="采集端关联线性转换id"-->
        <!--        />-->
        <el-table-column
          prop="softwareRegisterType"
          label="转发端(软件)寄存器类型"
        >
          <template slot-scope="scope">
            {{
              dict.label.software_register_type[scope.row.softwareRegisterType]
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="softwareRegisterAddress"
          label="转发端(软件)寄存器地址"
        />
        <el-table-column prop="updateBy" label="更新人" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column prop="groupId" label="关联分组id" />
        <el-table-column
          v-if="checkPer(['admin', 'dmModbusData:edit', 'dmModbusData:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDmModbusData from '@/api/dmModbusData'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import dateRangePicker from '@/components/DateRangePicker'
import { get } from '@/api/dmModbusDrive'

const defaultForm = {
  dataId: null,
  callTheRoll: null,
  describe: null,
  dataType: null,
  hardwareRegisterType: null,
  hardwareRegisterAddress: null,
  isFetchBit: null,
  linearConversionId: null,
  softwareRegisterType: null,
  softwareRegisterAddress: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null,
  groupId: null
}
export default {
  name: 'DmModbusData',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    dateRangePicker
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: [
    'modbus_data_type',
    'hardware_register_type',
    'hardware_fetch_bit',
    'software_register_type'
  ],
  cruds() {
    return CRUD({
      title: '分组下的数据管理',
      url: 'api/dmModbusData',
      idField: 'dataId',
      sort: 'dataId,desc',
      crudMethod: { ...crudDmModbusData }
    })
  },
  data() {
    return {
      drive: [], // 多选下拉框的值
      value: [], // 搜索选中的ID值
      value2: [], // dialog选中的ID值
      props: {
        // lazy: true,
        // lazyLoad(node, resolve) {
        //   const { level } = node;
        //   setTimeout(() => {
        //     const nodes = Array.from({ length: level + 1 }).map((item) => ({
        //       value: ++node,
        //       label: `选项` + node,
        //       leaf: level >= 2,
        //     }));
        //     // 通过调用resolve将子节点数据返回，通知组件数据加载完成
        //     resolve(nodes);
        //   }, 1000);
        // },
      },
      fetch_bit: false,
      ConversionId: !this.fetch_bit,
      permission: {
        add: ['admin', 'dmModbusData:add'],
        edit: ['admin', 'dmModbusData:edit'],
        del: ['admin', 'dmModbusData:del']
      },
      rules: {
        dataId: [
          { required: true, message: '数据id不能为空', trigger: 'blur' }
        ],
        callTheRoll: [
          {
            required: true,
            message: '采集端（硬件）点名不能为空',
            trigger: 'blur'
          }
        ],
        dataType: [
          {
            required: true,
            message: '采集端数据类型不能为空',
            trigger: 'blur'
          }
        ],
        hardwareRegisterType: [
          {
            required: true,
            message: '采集端寄存器类型不能为空',
            trigger: 'blur'
          }
        ],
        hardwareRegisterAddress: [
          {
            required: true,
            message: '采集端寄存器地址不能为空',
            trigger: 'blur'
          }
        ],
        softwareRegisterType: [
          {
            required: true,
            message: '转发端(软件)寄存器类型不能为空',
            trigger: 'blur'
          }
        ],
        softwareRegisterAddress: [
          {
            required: true,
            message: '转发端(软件)寄存器地址不能为空',
            trigger: 'blur'
          }
        ],
        groupId: [
          { required: true, message: '关联分组id不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'dataId', display_name: '数据id' },
        { key: 'callTheRoll', display_name: '采集端（硬件）点名' },
        { key: 'groupId', display_name: '关联分组id' }
      ],
      innerVisible: false, // 内嵌dialog
      Offset: {
        name: '',
        originalMax: '',
        originalMin: '',
        engineeringMax: '',
        engineeringMin: ''
      }
    }
  },
  watch: {
    fetch_bit: function() {
      if (this.fetch_bit) {
        this.ConversionId = !this.fetch_bit
      } else {
        this.ConversionId = !this.fetch_bit
      }
    },
    ConversionId: function() {
      if (this.ConversionId) {
        this.fetch_bit = !this.ConversionId
      } else {
        this.fetch_bit = !this.ConversionId
      }
    }
  },
  created() {
    this.getDrive()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    getDrive() {
      const param = 'page=0&size=9999'
      // eslint-disable-next-line no-unused-vars
      const _that = this
      get(param).then((res) => {
        _that.drive = res.content
        // console.log(JSON.stringify(_that.drive))
        // 一级菜单
        _that.drive.forEach((item) => {
          item.value = item.driveId
          item.label = item.driveName
          item.children = item.channels
          // 二级菜单
          item.children.forEach((second) => {
            second.value = second.channelId
            second.label = second.channelName
            second.children = second.dmModbusDevice
            // 三级菜单
            second.children.forEach((third) => {
              third.value = third.deviceId
              third.label = third.deviceName
              third.children = third.dmModbusGroup
              // 四级菜单
              third.children.forEach((forth) => {
                forth.value = forth.groupId
                forth.label = forth.groupName
                // forth.children = forth.dmModbusGroup;
              })
            })
          })
        })

        // console.log(_that.drive)
      })
    },
    handleChange(value) {
      const dataValue = [value[value.length - 1]] // 选择后的ID
      // const dataValue = [value[0]]; // 选择后的ID
      // const dataValue = value; // 选择后的ID
      this.query.groupId = dataValue
      console.log(this.query.groupId)
    },
    handleTableChange(value) {
      const dataValue = [value[value.length - 1]] // 选择后的ID
      this.form.groupId = dataValue.join()
      console.log(dataValue)
    },
    submitBtn() {
      console.log(this.form.isFetchBit.join()) // 数组转字符串
      const stringIsFetchBit = this.form.isFetchBit.join()
      this.form.isFetchBit = stringIsFetchBit
      console.log(stringIsFetchBit.split()) // 字符串转数组
    }
  }
}
</script>

<style scoped lang="scss">
* {
  list-style: none;
}

.double {
  ul {
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: space-between;
    li {
      width: 48%;
      #downbox {
        display: block;
        margin-top: 5px;
        // height: 70px;
        // width: 315px;
        border: solid #1890ff 1px;
      }
      #downbox legend {
        font-weight: 600;
        color: black;
        opacity: 0.5;
        font-size: 12px;
        margin: 0 auto;
      }
    }
  }
}
</style>
