<template>
  <a-card :bordered="false" v-show="visible" class="card" :title="modalTitle">
    <a-row :gutter="48" slot="extra">
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right">
          <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
          <a-button style="margin-left: 8px" type="default" @click="handleCancel()">返回</a-button>
        </span>
      </a-col>
    </a-row>
    <a-form :form="form">

      <a-form-item v-show="false">
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>
      <row-list :col="2">
        <row-item>
          <a-form-item
            label="类型"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['type', {rules: [{required: true, message: '类型不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in typeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['remark', {rules: [{required: true, message: '备注不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="二级类别"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['secondTypeId', {rules: [{required: false, message: '二级类别不能为空'}]}]"/>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <title-divider title="字段明细" width="90px"></title-divider>
    <div class="table-operator" style="margin-bottom: 8px;">
      <a-button size="small" type="primary" @click="handleParam">
        <a-icon type="plus"/>
        添加
      </a-button>
      <a-button class="margin-left8" size="small" type="danger" @click="handleDelParam">
        <a-icon type="delete"/>
        删除
      </a-button>
    </div>
    <a-table
      bordered
      :data-source="data"
      :columns="columns"
      tableLayout="auto"
      rowKey="fieldName"
      :row-selection="rowSelection">
      <span slot="action" slot-scope="record">
        <template>
          <a @click="handleParam(record)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm title="是否要删除该条数据？" @confirm="handleDelParam(record.fieldName)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </span>
    </a-table>
    <param-form ref="paramForm" @ok="handleParamList" />
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import ParamForm from './ParamForm'
import { addCustomFieldTemplate, updateCustomFieldTemplate } from '@/api/customize/fieldTemplate'
import DetailList from '@/components/tools/DetailList'
export default {
  name: 'BaseCustomFieldTemplate',
  components: {
    ParamForm,
    DetailList
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      data: [],
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      typeMap: {},
      typeFieldMap: {},
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '显示名称',
          dataIndex: 'label'
        },
        {
          title: '字段名称',
          dataIndex: 'fieldName'
        },
        {
          title: '类型',
          dataIndex: 'type',
          customRender: (text, record, index) => {
            return this.BaseTool.Object.getField(this.typeFieldMap, text)
          }
        },
        {
          title: '是否必填',
          dataIndex: 'required'
        },
        {
          title: '显示行数',
          dataIndex: 'rows',
          width: 120
        },
        {
          title: '排序',
          dataIndex: 'sort',
          width: 150
        },
        {
          title: '默认值',
          dataIndex: 'defaultValue',
          width: 150
        },
        {
          title: '最小长度',
          dataIndex: 'minLength',
          width: 150
        },
        {
          title: '最大长度',
          dataIndex: 'maxLength',
          width: 150
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  props: {},
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CUSTOM_FIELD_TEMPLATE_TYPE)
    this.typeFieldMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CUSTOM_FIELD_TEMPLATE_FILED_TYPE)
  },
  methods: {
    base (record) {
      this.visible = true
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        return
      }
      this.modalTitle = '编辑'
      const { form: { setFieldsValue } } = this
      this.data = JSON.parse(record.content)
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'content',
          'type',
          'remark',
          'secondTypeId'
        ])))
      })
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.content = JSON.stringify(this.data)
        // 日期处理
        if (this.BaseTool.String.isBlank(values.id)) {
          addCustomFieldTemplate(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateCustomFieldTemplate(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.data = []
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      } else {
        this.$emit('ok')
      }
    },
    handleParam (record) {
      const modal = this.$refs.paramForm
      modal.base(record)
    },
    handleParamList (values) {
      let dataSource = [...this.data]
      if (dataSource == null) {
        dataSource = []
      }
      if (values.label == null || values.label === '') {
        return
      }
      let find = false
      for (let j = 0; j < dataSource.length; j++) {
        if (values.fieldName === dataSource[j].fieldName) {
          find = true
          this.data = dataSource.map(item => {
            return item.fieldName === values.fieldName ? values : item
          })
          break
        }
      }
      if (!find) {
        dataSource.push(values)
      }
    },
    handleDelParam (fieldName) {
      const dataSource = [...this.data]
      this.data = dataSource.filter(item => item.fieldName !== fieldName)
    }
  }
}
</script>
