<template>
  <div class="app-container">

    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        style="width:120px;"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;"> <sys-origin-icon :icon="item.value" :desc="item.value" /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>
      <el-cascader
        v-model="listQuery.groupList"
        clearable
        placeholder="分组"
        :options="enumConfigGroupNames"
        :props="cascaderProps"
        class="filter-item"
        @change="handleSearch"
      />
      <el-select
        v-model="listQuery.inoperable"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in enumConfigOperates"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>

      <el-select
        v-model="listQuery.returnApp"
        placeholder="返回APP"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option label="是" :value="true" />
        <el-option label="否" :value="false" />
      </el-select>
      <el-input
        v-model.trim="listQuery.name"
        placeholder="键"
        style="width: 200px;"
        class="filter-item"
      />
      <el-input
        v-model.trim="listQuery.val"
        placeholder="值"
        style="width: 200px;"
        class="filter-item"
      />
      <el-input
        v-model.trim="listQuery.description"
        placeholder="描述"
        style="width: 200px;"
        class="filter-item"
      />

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >
      <el-table-column prop="sysOrigin" label="系统" align="center" min-width="60">
        <template slot-scope="scope">
          <sys-origin-icon :icon="scope.row.sysOrigin" :desc="scope.row.sysOrigin" />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" align="center" />
      <el-table-column prop="val" label="值" align="center" />
      <el-table-column prop="groupName" label="分组" align="center">
        <template slot-scope="scope">
          <span>{{ getGroupNames(scope.row.groupList) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="dataType" label="数据类型" align="center" width="100" />
      <el-table-column prop="sort" label="序号" align="center" width="50" />
      <el-table-column prop="inoperable" label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.inoperable === false" type="success">可操作</el-tag>
          <el-tag v-if="scope.row.inoperable === true" type="danger">不可操作</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="returnApp" label="返回APP" align="center" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.returnApp === true">是</span>
          <span v-if="scope.row.returnApp === false">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" align="center" width="50">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top-start">
            <div slot="content" class="tooltip-content">{{ scope.row.description }}</div>
            <div class="el-icon-info cursor-pointer" />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="键" align="center" width="50">
        <template slot-scope="scope">
          <div @click="copyTextContent(scope.row.name)">
            <el-tooltip class="item" effect="dark" placement="top-start">
              <div slot="content" class="tooltip-content">{{ scope.row.name }}</div>
              <div class="el-icon-info cursor-pointer" />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="操作时间" align="center" width="100">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top-start">
            <div slot="content" class="tooltip-content">
              <div>创建时间：{{ scope.row.createTime | dateFormat }}</div>
              <div>修改时间：{{ scope.row.updateTime | dateFormat }}</div>
            </div>
            <div class="el-icon-info cursor-pointer" />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="120">
        <template slot-scope="scope">
          <el-button type="text" @click.native="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="text" @click.native="handlDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <el-dialog
      :title="formTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="550px"
    >
      <div v-loading="submitLoading">
        <el-form
          ref="form"
          style="width: 400px; margin-left:50px;"
          :model="form"
          :rules="rules"
          label-position="right"
          label-width="80px"
        >
          <el-form-item v-if="isHideProperty" label="键" prop="name">
            <el-input v-model.trim="form.name" type="text" />
          </el-form-item>
          <el-form-item label="数据类型" prop="dataType">
            <el-select
              v-model="form.dataType"
              placeholder="数据类型"
              style="width:100%;"
              @change="handleDataTypeChange"
            >
              <el-option
                v-for="item in enumConfigDataTypes"
                :key="item.value"
                :value="item.value"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="值" prop="val">
            <el-input v-model.trim="form.val" type="text" />
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="form.title" type="text" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model.trim="form.description" type="text" />
          </el-form-item>
          <el-form-item label="分组" prop="groupList">
            <el-cascader v-model="form.groupList" :options="enumConfigGroupNames" :props="cascaderProps" style="width:100%;" />
          </el-form-item>
          <el-form-item label="操作状态" prop="inoperable">
            <el-select
              v-model="form.inoperable"
              placeholder="操作状态"
              class="filter-item"
              style="width:100%;"
            >
              <el-option
                v-for="item in enumConfigOperates"
                :key="item.value"
                :value="item.value"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="返回APP" prop="returnApp">
            <el-select
              v-model="form.returnApp"
              placeholder="返回APP"
              clearable
              style="width:100%;"
              class="filter-item"
            >
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">保存</el-button>
            <el-button @click="handleClose()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { copyText, deepClone } from '@/utils'
import { getConfigInfo, addConfigInfo, updateConfigInfo, delConfig } from '@/api/table'
import { enumConfigGroupNames, enumConfigOperates, enumConfigDataTypes, enumConfigDataTypesExpression } from '@/constant/type'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'

function getFormData() {
  return {
    id: '',
    name: '',
    val: '',
    groupName: '',
    groupList: [],
    title: '',
    description: '',
    dataType: 'int',
    sort: '0',
    inoperable: false,
    returnApp: true,
    sysOrigin: 'HALAR'
  }
}

export default {
  name: 'CnfEnumsManager',
  components: { Pagination },
  data() {
    var validateValue = (rule, value, callback) => {
      const expression = enumConfigDataTypesExpression[this.form.dataType]
      if (expression.rex && !expression.rex.test(value)) {
        callback(new Error(expression.msg))
        return
      }
      callback()
    }
    return {
      cascaderProps: {
        value: 'value',
        label: 'name'
      },
      formTitle: '',
      thisRow: {},
      list: [],
      total: 0,
      people: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        name: '',
        val: '',
        description: '',
        groupName: '',
        groupList: [],
        sysOrigin: 'HALAR',
        inoperable: '',
        returnApp: ''
      },
      formVisible: false,
      enumConfigGroupNameMap: {},
      enumConfigGroupNames,
      enumConfigOperates,
      enumConfigDataTypes,
      form: getFormData(),
      submitLoading: false,
      rules: {
        name: [
          { required: true, message: '必填参数不可为空', trigger: 'blur' }
        ],
        val: [
          { required: true, validator: validateValue, trigger: 'blur' }
        ],
        title: [
          { required: true, message: '必填参数不可为空', trigger: 'blur' }
        ],
        groupList: [
          { required: true, message: '必填参数不可为空', trigger: 'blur' }
        ],
        inoperable: [
          { required: true, message: '必填参数不可为空', trigger: 'blur' }
        ],
        returnApp: [
          { required: true, message: '必填参数不可为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '必填参数不可为空', trigger: 'blur' }
        ]
      },
      listLoading: true
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms']),
    isHideProperty() {
      return !this.form.id || this.form.id <= 0
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
    that.enumConfigGroupNamesToMap()
  },
  methods: {
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.listQuery.cursor = 1
        that.list = []
      }
      that.listLoading = true
      that.listQuery.groupName = that.listQuery.groupList.join(',')
      getConfigInfo(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = that.convertResultList(body.records)
        that.listLoading = false
      })
    },
    convertResultList(list) {
      if (list) {
        list.forEach(item => {
          if (item.groupName) {
            item.groupList = item.groupName.split(',')
          }
        })
        return list
      }
      return []
    },
    enumConfigGroupNamesToMap(list, isChildren) {
      const that = this
      if (!list && !isChildren) {
        list = that.enumConfigGroupNames
      }
      list.forEach(item => {
        that.enumConfigGroupNameMap[item.value] = item.name
        if (item.children && item.children.length > 0) {
          that.enumConfigGroupNamesToMap(item.children, true)
        }
      })
    },
    getGroupNames(keys) {
      const that = this
      return keys ? keys.map(item => that.enumConfigGroupNameMap[item]).join('/') : ''
    },
    handleSearch() {
      this.renderData(true)
    },
    handleCreate() {
      this.formVisible = true
      this.formTitle = '添加'
      this.form = getFormData()
    },
    handleUpdate(row) {
      this.formVisible = true
      this.formTitle = '编辑'
      this.form = Object.assign({}, row)
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true
          const submitForm = deepClone(that.form)
          submitForm.sysOrigin = that.listQuery.sysOrigin
          submitForm.groupName = submitForm.groupList.join(',')
          if (!that.form.id) {
            addConfigInfo(submitForm).then(res => {
              that.submitLoading = false
              that.formVisible = false
              that.form = getFormData()
              that.renderData()
            }).catch(er => {
              that.submitLoading = false
              console.error(er)
            })
            return
          }
          updateConfigInfo(submitForm).then(res => {
            that.submitLoading = false
            that.formVisible = false
            that.form = getFormData()
            that.renderData()
          }).catch(er => {
            that.submitLoading = false
            console.error(er)
          })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    handleClose() {
      this.formVisible = false
      this.$refs.form.resetFields()
      this.$refs.form.clearValidate()
    },
    handlDel(item) {
      const that = this
      that.searchLoading = that.listLoading = false

      this.$confirm('您确定要删除该参数配置吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        delConfig(item.id).then(res => {
          that.renderData()
          that.$opsMessage.success()
        }).catch(er => {
          that.$opsMessage.success()
        })
      }).catch(() => {})
    },
    renderDataSuccess() {
      this.$message({
        message: 'Successful',
        type: 'success'
      })
      this.renderData()
    },
    handleMouseEnter(row) {
      this.thisRow = row
    },
    copyTextContent(text) {
      const that = this
      copyText(text).then(() => {
        that.$message({
          message: '复制成功',
          type: 'success'
        })
      }).catch(() => {
        that.$message({
          message: '复制失败',
          type: 'error'
        })
      })
    },
    handleDataTypeChange(value) {
      this.form.val = ''
    },
    handlerChangeSysOrigin(value) {
      if (this.golbalSetting === value) {
        this.listQuery.groupList = []
      }
      this.handleSearch()
    }
  }
}
</script>
<style scoped lang="scss">
.tooltip-content {
  max-width: 300px;
}
</style>
