<template>
  <GlobalWindow
    :title="title"
    v-model:visible="visible"
    width="750px"
    :confirm-working="isWorking.create"
    @confirm="confirm"
  >
    <el-form :model="form" ref="form" :rules="rules">
      <el-form-item label="数据项编码" prop="value" required>
        <el-input v-model="form.value" placeholder="请输入数据项编码" v-trim maxlength="50"/>
      </el-form-item>
      <el-form-item label="数据项名" prop="label" required>
        <el-input v-model="form.label" placeholder="请输入数据项名" v-trim maxlength="50"/>
      </el-form-item>
      <el-form-item label="其它配置" prop="config">
        <el-table :data="parameters">
          <el-table-column prop="name" label="参数变量">
            <template #default="{ row }">
              <el-input v-model="row.name" placeholder="请输入参数变量" @input="handleParameterNameInput"/>
            </template>
          </el-table-column>
          <el-table-column prop="label" label="参数名">
            <template #default="{ row }">
              <el-input v-model="row.label" placeholder="请输入参数名"/>
            </template>
          </el-table-column>
          <el-table-column prop="component" label="参数输入类型">
            <template #default="{ row }">
              <DictSelect code="TEMPLATE_PARAMETER_INPUT_COMPONENTS" v-model="row.component"/>
            </template>
          </el-table-column>
          <el-table-column prop="required" label="是否必填">
            <template #default="{ row }">
              <el-switch v-model="row.required"/>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ $index }">
              <el-button
                type="danger"
                link
                icon="Delete"
                @click="deleteParameterLine($index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="form.remark" :rows="5" show-word-limit placeholder="请输入备注" v-trim maxlength="200"/>
      </el-form-item>
      <el-form-item label="状态" prop="disabled" required class="form-item-status">
        <el-switch v-model="form.disabled" :active-value="false" :inactive-value="true"/>
        <span class="status-text">{{$filters.disabledText(form.disabled)}}</span>
      </el-form-item>
    </el-form>
  </GlobalWindow>
</template>

<script>
import BaseOpera from '@/components/base/BaseOpera'
export default {
  name: 'OperaTemplateDataWindow',
  extends: BaseOpera,
  data () {
    return {
      // 参数列表
      parameters: [],
      // 表单数据
      form: {
        id: null,
        dictId: null,
        value: '',
        label: '',
        config: '',
        disabled: false,
        remark: ''
      },
      // 验证规则
      rules: {
        label: [
          { required: true, message: '请输入数据标签' }
        ],
        value: [
          { required: true, message: '请输入数据值' }
        ]
      }
    }
  },
  methods: {
    /**
     * 打开窗口
     *
     * @param title 窗口标题
     * @param dictId 所属字典ID
     * @param target 行对象（仅编辑需该参数）
     */
    open (title, dictId, target) {
      this.title = title
      this.visible = true
      // 新建
      if (target == null) {
        this.$nextTick(() => {
          this.$refs.form.resetFields()
          this.form.id = null
          this.form.dictId = dictId
          this.parameters = []
          this.__addNewParameterLine()
        })
        return
      }
      // 编辑
      this.$nextTick(() => {
        for (const key in this.form) {
          this.form[key] = target[key]
        }
        // 将配置解析为参数数组
        this.parameters = this.form.config == null || this.form.config === '' ?
          [] : JSON.parse(this.form.config).parameters
        // 添加空行
        this.__addNewParameterLine()
      })
    },
    // 处理参数变量输入
    handleParameterNameInput () {
      const lastParameter = this.parameters[this.parameters.length - 1]
      if (lastParameter.name.trim() !== '') {
        this.__addNewParameterLine()
      }
    },
    // 删除行
    deleteParameterLine (index) {
      // 删除的是最后一行，则清空内容，但不删除
      if (index === this.parameters.length - 1) {
        this.parameters[this.parameters.length - 1] = {
          name: '',
          label: '',
          component: 'TextInput',
          required: false
        }
        return
      }
      this.parameters.splice(index, 1)
    },
    // 添加新的参数行
    __addNewParameterLine () {
      this.parameters.push({
        name: '',
        label: '',
        component: 'TextInput',
        required: false
      })
    },
    // 获取新建&编辑时的表单
    __getForm () {
      const form = JSON.parse(JSON.stringify(this.form))
      // 将参数保存为数据配置
      form.config = JSON.stringify({
        parameters: this.parameters.filter(p => p.name.trim() !== '')
      })
      return form
    }
  },
  async created () {
    this.config({
      api: await import('@/api/system/dict.data')
    })
  }
}
</script>

<style scoped lang="scss">
:deep(.form-item-status) {
  .el-form-item__content{
    display: flex;
    & > * {
      width: auto !important;
    }
  }
  .status-text {
    color: #999;
    margin-left: 6px;
    font-size: 13px;
    vertical-align: middle;
  }
}
</style>
