<template>
  <el-config-provider :locale="zhCn">
    <el-container class="content">
      <div class="work-area">
        <fieldset class="search-area">
          <el-form ref="configQueryFormRef" :model="configQueryFormEntity" :label-position="labelPosition"
                   label-width="158px" style="max-width: 100%" status-icon>
            <div style="display: flex;justify-content: space-between;">
              <el-row>
                <el-form-item label="配置键">
                  <el-input v-model="configQueryFormEntity.configKey" clearable/>
                </el-form-item>
                <el-form-item label="配置名">
                  <el-input v-model="configQueryFormEntity.configName" clearable/>
                </el-form-item>
              </el-row>
              <div style="align-content: center;">
                <el-row>
                  <el-button type="primary" class="btn-search" @click="search()">查询</el-button>
                  <el-button type="warning" class="btn-search" @click="clearQuery()">清除输入</el-button>
                </el-row>
              </div>
            </div>
          </el-form>
        </fieldset>
        <div class="table-area">
          <el-table :data="displayConfigs" stripe border v-loading="tableLoading" class="table-class"
                    :max-height="maxHeight" highlight-current-row @row-click="getCurrentRow"
                    :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
                    @sort-change="handleSortChange">
            <el-table-column width="65px" fixed="left">
              <template v-slot="scope">
                <el-radio :label="scope.row.configId" v-model="configId">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="configId" label="配置id" fixed="left" min-width="80px"
                             show-overflow-tooltip sortable="custom" />
            <el-table-column prop="configName" label="配置名称" fixed="left" min-width="120px"
                             show-overflow-tooltip sortable="custom" />
            <el-table-column prop="configKey" label="配置键" show-overflow-tooltip min-width="120px" sortable="custom" />
            <el-table-column prop="configValue" label="配置值" show-overflow-tooltip min-width="140px" sortable="custom" />
            <el-table-column prop="configType" label="配置类型" :formatter="configTypeFormat" min-width="100px"
                             show-overflow-tooltip sortable="custom" />
            <el-table-column fixed="right" label="操作" width="120px">
              <template v-slot="scope">
                <el-button plain type="primary" @click="editCurrentRow(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          <br/>
          <el-pagination v-model:current-page="baseTableQuery.currentPage"
                         v-model:page-size="baseTableQuery.pageSize" :page-sizes="[10, 25, 50]" :small="false"
                         :disabled="false" :background="false" :default-page-size="10" @size-change="search"
                         @current-change="search" layout="total, sizes, prev, pager, next, jumper"
                         :total="baseTableQuery.total"/>
        </div>
        <el-dialog v-model="showConfigEditFlag" title="编辑配置信息" width="40%" draggable :show-close="false">
          <el-form ref="configEditFormRef" :model="configEditFormEntity" :label-position="labelPosition"
                   label-width="100px" style="max-width: 100%" :rules="editRules" status-icon>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="配置名称" prop="configName">
                  <el-input v-model="configEditFormEntity.configName" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="配置类型" prop="configType">
                  <el-select-v2 v-model="configEditFormEntity.configType" placeholder="请选择配置类型"
                                :options="configTypeOptions" disabled></el-select-v2>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="配置键" prop="configKey">
                  <el-input v-model="configEditFormEntity.configKey" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="配置值" prop="configValue">
                  <el-input v-if="configEditFormEntity.configType === 1" type="textarea" :rows="1"
                            v-model="configEditFormEntity.configValue" placeholder="" :maxlength="-1"
                            :show-word-limit="false" :autosize="{ minRows: 1, maxRows: 4 }">
                  </el-input>
<!--                  类型2需要增加subKey-->
<!--                  <el-select v-if="configEditFormEntity.configType === 2"-->
<!--                             v-model="configEditFormEntity.configValue" multiple collapse-tags-->
<!--                             collapse-tags-tooltip :placeholder="'请选择' + configEditFormEntity.configName">-->
<!--                    <el-option v-for="(value, index) in mails" :key="index" :label="value"-->
<!--                               :value="value"/>-->
<!--                  </el-select>-->
                  <el-switch v-if="configEditFormEntity.configType === 3" style="margin-left: 5px;"
                             v-model="configEditFormEntity.configValue" active-value="1" inactive-value="0"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="showConfigEditFlag = false">取消</el-button>
                            <el-button type="primary" @click="submitChange()">
                                确定
                            </el-button>
                        </span>
          </template>
        </el-dialog>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import store from '@/store'
import {configTypeFormatter} from '@/utils/formatter.js'
import {ref, reactive, onMounted, nextTick, onBeforeUnmount} from 'vue'
import {ElMessage} from 'element-plus'
import {genTableRequest} from '@/utils/generator.js'
import {labelPosition} from '@/constant/form'
import {queryConfigsByPage, updateConfig} from "@/api/config";
/**
 * 常量定义
 */
const USER_NAME = store.getters.getUserName
const STAND_ID = store.getters.getStandId
const configTypeOptions = [
  {
    value: '1',
    label: '输入框'
  },
  {
    value: '2',
    label: '下拉多选'
  },
  {
    value: '3',
    label: '开关'
  }
]
const editRules = {
  configId: [
    {required: true, message: '请输入配置id'}
  ],
  configName: [
    {required: true, message: '请输入配置名称'}
  ],
  configKey: [
    {required: true, message: '请输入配置键'}
  ],
  configValue: [
    {required: true, message: '请输入配置值'}
  ],
  configType: [
    {required: true, message: '请输入配置类型'}
  ]
}
/**
 * 变量定义
 */
let maxHeight = ref(window.innerHeight * 0.55)
let tableLoading = ref(false)
let displayConfigs = ref([])
let baseTableQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  sortBy: new Map([['configId', true]]),// 按照工单顺序排序
  standId: store.getters.getStandId,
  userName: store.getters.getUserName
})
let configQueryFormEntity = reactive({
  configKey: '',
  configName: ''
})
let configQueryFormRef = ref()
let showConfigEditFlag = ref(false)
let configId = ''
let configEditFormRef = ref()
let configEditFormEntity = reactive({
  configId: '',
  configName: '',
  configKey: '',
  configValue: '',
  configType: null
  // subKey: ''
})
/**
 * 系统方法
 */
onMounted(() => {
  nextTick(() => {
    window.addEventListener('resize', resizeHeight)
    search()
  })
})
onBeforeUnmount(() => {
  nextTick(() => {
    window.removeEventListener('resize', resizeHeight)
  })
})
const resizeHeight = () => {
  maxHeight.value = window.innerHeight * 0.55
}
/**
 * 自定义方法
 */
// 查询
const search = () => {
  tableLoading.value = true
  let request = genTableRequest(baseTableQuery)
  // 设定查询参数
  request.configKey = configQueryFormEntity.configKey
  request.configName = configQueryFormEntity.configName
  queryConfigsByPage(request).then((res) => {
    const response = res.data
    if (response.code === 0) {
      const data = response.data
      if (data != null) {
        displayConfigs.value = data.lists
        baseTableQuery.total = data.total
      } else {
        displayConfigs.value = []
        baseTableQuery.total = 0
      }
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('查询配置数据异常。')
  }).finally(() => {
    tableLoading.value = false
  })
}
const clearQuery = () => {
  configQueryFormEntity.configKey = ''
  configQueryFormEntity.configName = ''
}
const handleSortChange = (data) => {
  if (baseTableQuery.sortBy.has(data.prop)) {
    baseTableQuery.sortBy.delete(data.prop)
  }
  baseTableQuery.sortBy.set(data.prop, data.order.toLowerCase() === 'ascending')
  search()
}
const getCurrentRow = (row) => {
  configId = row.configId
}
const configTypeFormat = (row, column, cellValue, index) => {
  return configTypeFormatter(cellValue)
}
const editCurrentRow = (row) => {
  showConfigEditFlag.value = true
  configEditFormEntity.configId = row.configId
  configEditFormEntity.configName = row.configName
  configEditFormEntity.configKey = row.configKey
  configEditFormEntity.configValue = row.configValue
  configEditFormEntity.configType = row.configType
}
const submitChange = () => {
  const request = {
    configId: configEditFormEntity.configId,
    configName: configEditFormEntity.configName,
    configKey: configEditFormEntity.configKey,
    configValue: configEditFormEntity.configValue,
    configType: configEditFormEntity.configType,
    userName: USER_NAME,
    standId: STAND_ID
  }
  updateConfig(request).then(res => {
    const response = res.data
    if (response.code === 0) {
      showConfigEditFlag.value = false
      ElMessage.success('更新系统配置成功')
      search()
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('更新系统配置失败')
  })
}
</script>
<style scoped>
.content {
  display: flex;
  width: 100%;
}

.work-area {
  width: 100%;
  /* padding: 5px; */
}

.search-area {
  margin: auto;
  min-height: fit-content;
  max-height: 40%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.table-area {
  margin: auto;
  min-height: fit-content;
  max-height: 60%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.el-form-item {
  margin: 5px 5px 5px 5px;
}

.el-form-item .el-input {
  width: 196px;
}

.el-form-item .el-select-v2 {
  width: 196px;
}

.table-class {
  margin: 5px 5px 5px 5px;
  width: inherit;
}

.el-pagination {
  padding-left: 5px;
}

.my-autocomplete li {
  width: 196px;
  line-height: normal;
  padding: 7px;
}

.my-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
}

.my-autocomplete li .addr {
  font-size: 12px;
  color: #b4b4b4;
}

.my-autocomplete li .highlighted .addr {
  color: #ddd;
}

.my-autocomplete li .goods_id {
  color: brown;
}

.my-autocomplete li .goods_name {
  color: cornflowerblue;
}

.btn-search {
  height: 30px;
  width: 80px;
  margin: auto 5px 5px auto;
  color: black;
}
</style>