<template>
<div>
  <el-tabs type="border-card">
    <el-tab-pane label="系统配置">
      <el-card style="height: calc(100vh - 227.75px)">
        <el-form :model="sysForm" :inline="true" style="margin-top: 20px;">
          <el-form-item label="仓库编号" :rules="[{ required: true, message: '仓库编号不能为空', trigger: 'blur' }]">
            <el-input v-model="sysForm.storeCode" />
          </el-form-item>
          <el-form-item label="服务器" :rules="[{ required: true, message: '服务器IP不能为空', trigger: 'blur' }]">
            <el-input v-model="sysForm.serverIp" />
          </el-form-item>
          <el-form-item label="端口" :rules="[{ required: true, message: '端口不能为空', trigger: 'blur' }]">
            <el-input v-model="sysForm.serverPort" />
          </el-form-item>
          <el-tooltip effect="dark" content="选中显示所有数据，不选中仅显示单据数据" placement="top-start">
            <el-form-item label="是否切换">
              <el-checkbox v-model="sysForm.isHide" />
            </el-form-item>
          </el-tooltip>
          <el-form-item>
            <el-button round type="success" @click="resetConfig">读取</el-button>
            <el-button round type="success" @click="saveConfig" v-if="sysForm.id">保存</el-button>
            <el-button round type="success" @click="syncGoods">同步物资</el-button>
            <el-dropdown @command="handleCommand">
              <span style="cursor: pointer; background: #67c23a;margin-left: 12px;">
                <img src="../assets/icons/主题.png" style="width: 32px;">
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="#223170">藏蓝风格</el-dropdown-item>
                  <el-dropdown-item command="#025799">蓝色风格</el-dropdown-item>
                  <el-dropdown-item command="#1f8a36">军绿风格</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
        </el-form>
        <el-divider><span style="font-size: 20px;">库房/ip配置</span></el-divider>
        <div class="head-container">
          <el-button class="filter-item" type="primary" style="float: right" @click="addConfig">新增</el-button>
        </div>
        <el-table :header-cell-style="{backgroundColor: '#f5f7fa',color: '#000',fontSize: '18px',fontWeight: '600'}" :data="configList" border style="width: 100%;">
          <el-table-column type="index" label="序号" align="center" width="70"/>
          <el-table-column prop="storeCode" label="库房代码" align="center"/>
          <el-table-column prop="serverIp" label="服务器IP" align="center"/>
          <el-table-column prop="serverPort" label="服务器端口" align="center"/>
          <el-table-column prop="masterIp" label="物理主机IP" align="center" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="editConfig(scope.row)">编辑</el-button>
              <el-popconfirm title="你确定删除吗?" @confirm="removeConfig(scope.row)">
                <template #reference>
                  <el-button type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-tab-pane>
    <el-tab-pane label="通道配置">
      <el-card style="height: calc(100vh - 227.75px)">
        <div class="head-container">
          <el-button class="filter-item" type="primary" style="float: right" @click="add">新增</el-button>
        </div>
        <el-table :header-cell-style="{backgroundColor: '#f5f7fa',color: '#000',fontSize: '18px',fontWeight: '600'}" :data="channelList" border style="width: 100%;">
          <el-table-column prop="stationId" label="通道号" align="center" width="100"/>
          <el-table-column label="通道模式" align="center">
            <template #default="scope">
              {{scope.row.type == 'IN' ? '入库' : '出库' }}
            </template>
          </el-table-column>
          <el-table-column prop="readerIp" label="读写器" align="center">
            <template #default="scope">
              {{scope.row.readerIp + ':' + scope.row.readerPort }}
            </template>
          </el-table-column>
          <el-table-column prop="gpioIp" label="GPIO" align="center">
            <template #default="scope">
              {{scope.row.gpioIp + ':' + scope.row.gpioPort }}
            </template>
          </el-table-column>
          <el-table-column label="1号显示屏" align="center">
            <template #default="scope">
              {{scope.row.ledIp1 + ':' + scope.row.ledPort1 }}
            </template>
          </el-table-column>
          <el-table-column label="2号显示屏" align="center">
            <template #default="scope">
              {{scope.row.ledIp2 + ':' + scope.row.ledPort2 }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
              <el-popconfirm title="你确定删除吗?" @confirm="removeDevice(scope.row)">
                <template #reference>
                  <el-button type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-tab-pane>
  </el-tabs>
  
  <el-dialog v-model="visible" width="30%" :title="title" @close="closeConfig">
    <el-form label-position="right" size="large" label-width="90px" :model="configForm" :rules="rules" ref="storeIp">
      <el-form-item label="库房代码">
        <el-input v-model="configForm.storeCode" placeholder="请输入库房代码"/>
      </el-form-item>
      <el-form-item label="服务器IP" prop="serverIp">
        <el-input v-model="configForm.serverIp" placeholder="请输入服务器IP"/>
      </el-form-item>
      <el-form-item label="服务器端口" prop="serverPort">
        <el-input v-model="configForm.serverPort" placeholder="请输入服务器端口"/>
      </el-form-item>
      <el-form-item label="物理主机IP" prop="masterIp">
        <el-input v-model="configForm.masterIp" placeholder="请输入物理主机IP"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false" size="large">关闭</el-button>
        <el-button type="primary" @click="submitConfig" size="large">提交</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="innerVisible" width="38%" :title="title">
      <el-form label-position="right" size="large" label-width="120px" :model="formData">
        <el-row>
          <el-col :span="12">
            <el-form-item label="通道号">
              <el-input v-model="formData.stationId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通道模式">
              <el-select v-model="formData.type" style="width: 100%;">
                <el-option value="IN" label="入库模式"></el-option>
                <el-option value="OUT" label="出库模式"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>  
        <el-row>
          <el-col :span="12">
            <el-form-item label="读写器IP">
              <el-input v-model="formData.readerIp"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="读写器端口">
              <el-input v-model="formData.readerPort"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="读写器类型">
          <el-select v-model="formData.readerType" style="width: 100%;">
            <el-option :value="4" label="四通道"></el-option>
            <el-option :value="8" label="八通道"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="天线功率">
          <el-input v-model="formData.readerPower" placeholder="四通道格式为10,10,10,10,范围为0-30之间。8通道同理"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="GPIO的IP">
              <el-input v-model="formData.gpioIp"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="GPIO端口">
              <el-input v-model="formData.gpioPort"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="1号显示屏IP">
              <el-input v-model="formData.ledIp1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="1号显示屏端口">
              <el-input v-model="formData.ledPort1"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="2号显示屏IP">
              <el-input v-model="formData.ledIp2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="2号显示屏端口">
              <el-input v-model="formData.ledPort2"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="innerVisible = false" size="large">关闭</el-button>
          <el-button type="primary" @click="handleSubmit" size="large">提交</el-button>
        </div>
      </template>
  </el-dialog>
</div>
</template>

<script>
import { defineComponent, ref, getCurrentInstance, toRefs, reactive } from 'vue'
import { postAction, getAction } from '@/api/manage'
import { ElMessage } from 'element-plus'
export default defineComponent({
  setup() {
    const { proxy } = getCurrentInstance()
    const configList = ref([])
    const channelList = ref([])
    const title = ref('')
    const sysForm = ref({})
    const configForm = ref({})
    const formData = ref({})
    const visible = ref(false)
    const innerVisible = ref(false)
    
    // ip正则表达式
    function isIp(str) {
      const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      return reg.test(str)
    }
    
    // ip校验
    const validateIp = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入Ip'))
      } else if (!isIp(value)) {
        callback(new Error('ip格式不正确'))
      } else {
        callback()
      }
    }
    
    // port校验
    const validatePort = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入端口'))
      } else if (isNaN(value)) {
        callback(new Error('请输入数字值'));
      } else if(value < 0 || value > 65535 ) {
        callback(new Error('端口范围在(0-65535)'))
      } else {
        callback()
      }
    }

    const rules = reactive({
      serverIp: [{ validator: validateIp, trigger: 'blur' }],
      serverPort: [{ validator: validatePort, trigger: 'blur' }],
      masterIp: [{ validator: validateIp, trigger: 'blur' }]
    })

    const state = reactive({
      url: {
        getStoreCode: '/config/getStoreCode',
        getConfig: '/config/getConfig',
        getConfigPage: '/config/getConfigPage',
        updateConfig: '/config/updateConfig',
        saveConfig: '/config/saveConfig',
        removeConfig: '/config/removeConfig',

        getDevice: '/device/getDevice',
        updateDevice: '/device/updateDevice',
        removeDevice: '/device/removeDevice',
        saveDevice: '/device/saveDevice',

        
        syncGoods: '/platform/syncGoods'
      },
    });


    const loadData = (arg) => {
      getConfigPage()
      getDevice()
      resetConfig()
    }

    function getConfigPage() {
      postAction(state.url.getConfigPage, {}).then(res => {
        if (res.code !== 99200) return ElMessage.error(res.message);
        configList.value = res.data.records
      })
    }
    
    function addConfig() {
      title.value = '新增'
      visible.value = true
    }

    function editConfig(row) {
      title.value = '编辑'
      configForm.value = JSON.parse(JSON.stringify(row))
      visible.value = true
    }

    function submitConfig() {
      let url = configForm.value.id ? state.url.updateConfig : state.url.saveConfig
      proxy.$refs.storeIp.validate((valid) => {
        if (!valid) {
          ElMessage.warning('请正确填写信息')
        } else {
          postAction(url, configForm.value).then(res => {
            if (res.code !== 99200) return ElMessage.error(res.message);
            ElMessage.success(res.message)
            configForm.value = {}
            visible.value = false
            getConfigPage()
          })
        }
      })
    }

    function closeConfig() {
      configForm.value = {}
    }

    function removeConfig(row) {
      postAction(state.url.removeConfig, { id: row.id}).then(res => {
        if (res.code !== 99200) return ElMessage.error(res.message);
        ElMessage.success(res.message)
        getConfigPage()
      })
    }

    function getDevice() {
      if (!sessionStorage.getItem('storeInfo')) return;
      postAction(state.url.getDevice, {storeCode: JSON.parse(sessionStorage.getItem('storeInfo')).storeCode}).then(res => {
        if (res.code !== 99200) return ElMessage.error(res.message);
        channelList.value = res.data
      })
    }
    
    function resetConfig() {
      getAction(state.url.getStoreCode).then(res => {
        if (res.code !== 99200) return ElMessage.error(res.message);
        postAction(state.url.getConfig, {storeCode: res.data}).then(res => {
          if (res.code !== 99200) return ElMessage.error(res.message);
          if (res.data.length > 0) {
            sysForm.value = JSON.parse(JSON.stringify(res.data[0]))
            sysForm.value.isHide = JSON.parse(sessionStorage.getItem('storeInfo')).isHide
          }
        })
      })
    }

    function syncGoods() {
      getAction(state.url.syncGoods).then(res => {
        if (res.code !== 99200) return ElMessage.error(res.message);
        ElMessage.success(res.message)
      })
    }

    function saveConfig() {
      let url =  sysForm.value.id ? state.url.updateConfig : state.url.saveConfig
      if (!sysForm.value.storeCode) {
        return ElMessage.warning('库房编号不能为空')
      }
      if (!sysForm.value.serverIp) {
        return ElMessage.warning('服务器IP不能为空')
      }
      if (!sysForm.value.serverPort) {
        return ElMessage.warning('端口不能为空')
      }
      postAction(url, sysForm.value).then(res => {
        if (res.code !== 99200) return ElMessage.error(res.message);
        ElMessage.success(res.message)
        sessionStorage.setItem('storeInfo', JSON.stringify(sysForm.value))
      })
    }

    function edit(row) {
      title.value = '编辑通道'
      formData.value = JSON.parse(JSON.stringify(row))
      innerVisible.value = true
    }

    function add() {
      title.value = '新增通道'
      innerVisible.value = true
    }

    function handleSubmit() {
      let url = formData.value.id ? state.url.updateDevice : state.url.saveDevice
      formData.value.storeCode = JSON.parse(sessionStorage.getItem('storeInfo')).storeCode
      postAction(url, formData.value).then(res => {
        if (res.code !== 99200) return ElMessage.error(res.message);
        ElMessage.success(res.message)
        formData.value = {}
        innerVisible.value = false
        getDevice()
      })
    }

    function removeDevice(row) {
      postAction(state.url.removeDevice, {stationId: row.stationId, id: row.id}).then(res => {
        if (res.code !== 99200) return ElMessage.error(res.message);
        ElMessage.success(res.message)
        getDevice()
      })
    }

    function handleCommand(command) {
      if (command === '#223170') { // 藏蓝
        sessionStorage.setItem('bgColor', '#223170')
      }
      if (command === '#025799') { // 蓝色
        sessionStorage.setItem('bgColor', '#025799')
      }
      if (command === '#1f8a36') { // 军绿
        sessionStorage.setItem('bgColor', '#1f8a36')
      }
      window.location.reload()
    }
    
    return {
      ...toRefs(state),
      sysForm,
      configForm,
      formData,
      rules,
      visible,
      innerVisible,
      title,
      configList,
      channelList,

      resetConfig,

      addConfig,
      editConfig,
      removeConfig,
      saveConfig,
      submitConfig,
      closeConfig,

      add,
      edit,
      handleSubmit,
      removeDevice,
      loadData,
      getDevice,
      syncGoods,
      getConfigPage,
      handleCommand
    }
  },
})
</script>
