<template>
  <div>
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <h2>基础属性</h2>
      <a-form-model-item ref="attrCode" label="属性代码" prop="attrCode">
        <a-input :disabled="this.submitType === 'edit' && this.selectedData.tableattrStatus ==='0'" v-model.trim="form.attrCode" placeholder="请输入属性代码" @blur="checkUnique(0,{attrCode:form.attrCode},'属性代码')"/>
      </a-form-model-item>

      <a-form-model-item ref="attrName" label="属性名称" prop="attrName">
        <a-input v-model.trim="form.attrName" placeholder="请输入属性名称" @blur="checkUnique(1,{attrName:form.attrName},'属性名称')"/>
      </a-form-model-item>

      <!-- <a-form-model-item ref="attrType" label="属性类型" prop="attrType">
        <a-input v-model="form.attrName" placeholder="请输入属性名称" @blur="checkUnique(1,{attrType:form.attrType})"/>
      </a-form-model-item> -->
      <a-form-model-item ref="attrType" label="属性类型" prop="attrType">
        <a-select :disabled="this.submitType === 'edit'" v-model="form.attrType" placeholder="请选择属性类型">
          <a-select-option value="0">
            字符型
          </a-select-option>
          <a-select-option value="1">
            整数数值型
          </a-select-option>
          <a-select-option value="2">
            日期型
          </a-select-option>
          <a-select-option value="3">
            时间型
          </a-select-option>
          <a-select-option value="4">
            文本型
          </a-select-option>
          <a-select-option value="5">
            小数数值型
          </a-select-option>
          <a-select-option value="6">
            日期时间型
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item ref="dataLength" label="属性长度" prop="dataLength">
        <a-input-number v-model.trim="form.dataLength" :min="minLength" placeholder="请输入属性长度" @blur="checkUnique(1,{attrLength:form.dataLength},'属性长度')" style="width:100%"/>
      </a-form-model-item>

      <a-form-model-item ref="attrSort" label="属性排序" prop="attrSort">
        <a-input-number v-model.trim="form.attrSort" placeholder="请输入属性排序" style="width:100%"/>
      </a-form-model-item>

      <a-form-model-item ref="attrDesc" label="属性描述" prop="attrDesc">
        <a-input v-model.trim="form.attrDesc" placeholder="请输入属性描述"/>
      </a-form-model-item>

      <!-- --------------------------------------------------------- -->
      <!-- <h2>数据属性</h2>
      <a-form-model-item ref="codingIstrues" label="是否自动编码字段" prop="codingIstrues">
        <a-switch v-model="form.codingIstrues" @change="changeEncoding" />
      </a-form-model-item> -->

      <!-- <template v-if="!form.codingIstrues">
        <a-form-model-item ref="attrType" label="属性类型" prop="attrType">
          <a-select v-model="form.attrType" placeholder="请选择属性类型">
            <a-select-option value="0">
              字符型
            </a-select-option>
            <a-select-option value="1">
              数值型
            </a-select-option>
            <a-select-option value="2">
              时间型
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item ref="ctrlsType" label="控件类型" prop="ctrlsType">
          <a-select v-model="form.ctrlsType" placeholder="请选择控件类型">
            <a-select-option value="0" :disabled="form.attrType==='2'">
              文本框
            </a-select-option>
            <a-select-option value="1" :disabled="form.attrType==='2'">
              选择框
            </a-select-option>
            <a-select-option value="2" :disabled="form.attrType!=='2'">
              时间选择框
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <template v-if="form.ctrlsType==='1'">
          <a-form-model-item ref="sourceType" label="属性内容" prop="sourceType">
            <a-select v-model="form.sourceType" placeholder="请选择属性内容">
              <a-select-option value="1">
                引用其他模型内容
              </a-select-option>
              <a-select-option value="0">
                自定义字典内容
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <template v-if="form.sourceType==='1'">
            <a-form-model-item ref="dataModelId" label="选择模型" prop="dataModelId">
              <a-select v-model="form.dataModelId" placeholder="请选择模型" @change="selectModel">
                <a-select-option
                  :value="item.id"
                  v-for="(item, index) in modelList"
                  :key="index">
                  {{ item.modelName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item ref="attrIds" label="选择属性" prop="attrIds">
              <a-select
                v-model="form.attrIds"
                placeholder="请选择属性"
                mode="multiple"
                @change="selectAttr">
                <a-select-option
                  :value="item.attrCode"
                  v-for="(item, index) in attrList"
                  :key="index">
                  {{ item.attrName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </template>

          <template v-if="form.sourceType==='0'">
            <a-form-model-item ref="parentName" label="自定义内容" prop="parentName">
              <a-button class="editable-add-btn" @click="handleAdd">
                新增
              </a-button>
              <a-table
                :columns="columns"
                :data-source="form.attCustdictInfo"
                :pagination="{
                  'hideOnSinglePage': true
                }"
                bordered>
                <template
                  v-for="col in ['dictLabel', 'action']"
                  :slot="col"
                  slot-scope="text, record"
                >
                  <div :key="col">
                    <a-input
                      v-if="record.editable"
                      style="margin: -5px 0"
                      :value="text"
                      @change="e => handleChange(e.target.value, record.key, col)"
                    />
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>
                <template slot="action" slot-scope="text, record">
                  <div class="editable-row-operations">
                    <span v-if="record.editable">
                      <a @click="() => save(record.key)">保存</a>
                      <a-popconfirm title="确定取消?" @confirm="() => cancel(record.key)">
                        <a>取消</a>
                      </a-popconfirm>
                    </span>
                    <span v-else>
                      <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
                      <a :disabled="editingKey !== ''" @click="() => onDelete(record.key)">删除</a>
                    </span>
                  </div>
                </template>
              </a-table>
            </a-form-model-item>
          </template>
        </template>
      </template>

      <template v-else>
        <a-form-model-item ref="eg" label="编码预览示例" prop="eg">
          <a-input v-model="form.eg" disabled/>
        </a-form-model-item>

        <a-form-model-item ref="parentName" label="编码方式" prop="parentName">
          <div class="mult">
            <a-button
              type="code"
              v-for="(item, index) in encodingButton"
              class="encoding"
              :disabled="item.disabled"
              @click="selectEncoding(item,index)"
              :key="index">{{ item.name }}</a-button>
          </div>
        </a-form-model-item>

        <a-form-model-item ref="attCoderuleInfo" label="编码规则" prop="attCoderuleInfo">
          <div class="mult">
            <span
              type="view"
              v-for="(item, index) in form.attCoderuleInfo"
              class="encoding encoding-select"
              :key="index">{{ item.codeType | computedCodeName }}</span>
          </div>
        </a-form-model-item>

        <div
          class="my-model"
          v-for="(item, index) in dynamicFormData"
          :key="index">
          <component
            :is="item.template"
            :value="item"
            :ref="item.template"
            @changeValue="changeValue">
          </component>
          <span class="delete" @click="deleteAttr(index)">删除</span>
        </div>

      </template> -->
      <!-- --------------------------------------------------------- -->
      <!-- <h2>校验属性</h2>
      <a-form-model-item ref="dataLength" label="数据长度" prop="dataLength">
        <a-input-number v-model="form.dataLength" :min="1" :max="255" style="width:100%" placeholder="请输入数据长度"/>
      </a-form-model-item>

      <a-form-model-item ref="dataPrecision" label="数值精度" prop="dataPrecision">
        <a-input-number v-model="form.dataPrecision" :min="1" :max="255" style="width:100%" placeholder="请输入数值精度"/>
      </a-form-model-item>

      <a-form-model-item ref="ifOnly" label="是否唯一" prop="ifOnly">
        <a-select @change="handleChange" v-model="form.ifOnly" placeholder="请选择是否唯一">
          <a-select-option value="0">唯一</a-select-option>
          <a-select-option value="1">不唯一</a-select-option>
        </a-select>
      </a-form-model-item>

      <a-form-model-item ref="ifRequired" label="是否必填" prop="ifRequired">
        <a-select @change="handleChange" v-model="form.ifRequired" placeholder="请选择是否必填">
          <a-select-option value="0">必填</a-select-option>
          <a-select-option value="1">非必填</a-select-option>
        </a-select>
      </a-form-model-item> -->
      <h2>安全属性</h2>
      <a-form-model-item ref="storeEncrypted" label="储存加密" prop="storeEncrypted">
        <a-select v-model="form.storeEncrypted" placeholder="请选择储存加密方式">
          <a-select-option value="0">
            无
          </a-select-option>
          <a-select-option value="1" >
            AES
          </a-select-option>
          <a-select-option value="2" >
            RSA
          </a-select-option>
        </a-select>
      </a-form-model-item>

      <a-form-model-item :wrapper-col="{ span: 12, offset: 8 }">
        <a-button type="stop" style="margin-right: 20px;" @click="handleOk">
          取消
        </a-button>
        <a-button type="add" @click="onSubmit">
          确定
        </a-button>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script type="text/ecmascript-6">
import * as itemElements from './index.js'
import { getModelListApi } from '@/api/model/modelManger'
import {
  getAttributeApi,
  addAttr,
  editAttr,
  checkUnique,
  getAttributeDetail
} from '@/api/model/attribute'
const encoding = ['固定码', '分类码', '流水码', '日期码', '时间码', '随机码']
const removePropertyOfNull = (obj) => {
    Object.keys(obj).forEach(item => {
        if (!obj[item]) delete obj[item]
    })
    return obj
}
	export default {
    components: { ...itemElements },
		data() {
      return {
        submitType: '',
        labelCol: { span: 6 },
				wrapperCol: { span: 16 },
        form: {
          codingIstrues: false,
          codingIstrue: '1',
          attCoderuleInfo: [],
          attCustdictInfo: [],
          ctrlsType: '0',
          setEncryption: '0'
        },
        columns: [
          { title: '数据项', dataIndex: 'dictLabel', width: '50%', scopedSlots: { customRender: 'dictLabel' } },
          { title: '操作', dataIndex: 'action', width: '50%', scopedSlots: { customRender: 'action' } }
        ],
        cacheData: [],
        editingKey: '',
        rules: {
          attrType: [
            { required: true, message: '请选择属性类型', trigger: 'blur' }
          ],
          attrCode: [
            { required: true, message: '请输入属性代码', trigger: 'blur' }
          ],
          attrName: [
            { required: true, message: '请输入属性名称', trigger: 'blur' }
          ],
          dataLength: [
            { required: true, message: '请输入数据长度', trigger: 'blur' }
          ],
          ifOnly: [
            { required: true, message: '请选择是否唯一', trigger: '["blur","change"]' }
          ],
          ifRequired: [
            { required: true, message: '请选择是否必填', trigger: '["blur","change"]' }
          ]
        },
        encodingButton: [
          { name: '固定码', disabled: false, codeType: 0, label: '固定码取值', props: 'Fixed', template: 'FormFixedCode' },
          { name: '分类码', disabled: false, codeType: 1, label: '分类码引用', props: 'Class', template: 'FormClassCode' },
          { name: '流水码', disabled: false, codeType: 2, label: '流水码长度', props: 'Stream', template: 'FormStreamCode' },
          { name: '日期码', disabled: false, codeType: 3, label: '日期码类型', props: 'Date', template: 'FormDateCode' },
          { name: '时间码', disabled: false, codeType: 4, label: '时间码类型', props: 'Time', template: 'FormTimeCode' },
          { name: '随机码', disabled: false, codeType: 5, label: '随机码位数', props: 'Random', template: 'FormRandomCode' }
        ],
        modelList: [],
        attrList: [],
        dataId: '',
        selectedData: {},
        minLength: null
			}
		},
    filters: {
      computedCodeName(val) {
        const name = val * 1
        return encoding[name]
      }
    },
    computed: {
      dynamicFormData() {
        console.log(`object`, this.form.attCoderuleInfo)
        return this.form.attCoderuleInfo.map((i, v) => ({ ...i, ...this.encodingButton.filter(o => o.codeType === i.codeType * 1)[0] }))
      }
    },
    mounted() {
      this.getTableList(0)
      // setTimeout(() => {
      // this.minLength = this.form.dataLength
      // console.log('%c [ this.minLength ]-361', 'font-size:13px; background:pink; color:#bf2c9f;', this.minLength)
      // }, 500)
    },
    methods: {
      changeEncoding(e) {
        this.form.codingIstrues = e
        this.form.codingIstrue = e ? '0' : '1'
      },
      selectEncoding(item) {
        this.form.attCoderuleInfo.push({ ...item, codeSort: this.form.attCoderuleInfo.length })
      },
      deleteAttr(index) {
        this.form.attCoderuleInfo.splice(index, 1)
        this.form.attCoderuleInfo.map((i, v) => { i.codeSort = v })
        this.computedEg()
      },
      computedEg() {
        const arr = []
        this.form.attCoderuleInfo.map((i, v) => {
          if (i.codeType === 2) {
            arr.push(i.startValue || '')
          } else {
            arr.push(i.codeValue)
          }
        })
        this.$set(this.form, 'eg', arr.join(''))
      },
      changeValue(val) {
        console.log(`val`, this.$refs)
        const index = this.form.attCoderuleInfo.findIndex((i) => i.codeSort === val.codeSort)
        console.log(`this.form.attCoderuleInfo`, this.form.attCoderuleInfo)
        this.form.attCoderuleInfo[index] = val
        const length = this.form.attCoderuleInfo.length
        console.log(`startValue`, this.form.attCoderuleInfo[length - 1].startValue)
        this.computedEg()
      },
      getTableList(catalogId) {
        getModelListApi({ catalogId, ...this.params }).then((res) => {
          if (res.code === 200) {
            this.modelList = res.rows
          }
        })
      },
      getAttribute(modelId) {
        getAttributeApi({ modelId }).then((res) => {
          if (res.code === 200) {
            this.attrList = res.rows
          }
        })
      },
      getAttributeDetail(id) {
        getAttributeDetail(id).then((res) => {
          if (res.code === 200) {
            this.form = { ...this.form, ...removePropertyOfNull(res.data) }// 删除返回数据为null的键值对,防止前端报错
            this.minLength = this.form.dataLength * 1
            console.log(`this.form`, this.form)
          }
        })
      },
      selectModel(modelId) {
        this.getAttribute(modelId)
      },
      selectAttr(selectedItems) {
        this.$set(this.form, 'attrIds', selectedItems.slice(0, 2))
      },
      handleAdd() {
        const { attCustdictInfo } = this.form
        const newData = {
          key: attCustdictInfo.length + 1,
          source: ``
        }
        this.$set(this.form, 'attCustdictInfo', [...attCustdictInfo, newData])
      },
      handleChange(value, key, column) {
        console.log(`value`, value)
        const newData = [...this.form.attCustdictInfo]
        const target = newData.filter(item => key === item.key)[0]
        if (target) {
          target[column] = value
          this.$set(this.form, 'attCustdictInfo', newData)
        }
      },
      edit(key) {
        const newData = [...this.form.attCustdictInfo]
        this.cacheData = [...this.form.attCustdictInfo]
        const target = newData.filter(item => key === item.key)[0]
        this.editingKey = key
        if (target) {
          target.editable = true
          this.$set(this.form, 'attCustdictInfo', newData)
        }
      },
      save(key) {
        const newData = [...this.form.attCustdictInfo]
        const newCacheData = [...this.cacheData]
        const target = newData.filter(item => key === item.key)[0]
        const targetCache = newCacheData.filter(item => key === item.key)[0]
        if (target && targetCache) {
          delete target.editable
          this.$set(this.form, 'attCustdictInfo', newData)
          Object.assign(targetCache, target)
          this.cacheData = newCacheData
        }
        this.editingKey = ''
      },
      onDelete(key) {
        const attCustdictInfo = [...this.form.attCustdictInfo]
        this.$set(this.form, 'attCustdictInfo', attCustdictInfo.filter(item => item.key !== key))
      },
      cancel(key) {
        const newData = [...this.form.attCustdictInfo]
        const target = newData.filter(item => key === item.key)[0]
        this.editingKey = ''
        if (target) {
          Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
          delete target.editable
          this.$set(this.form, 'attCustdictInfo', this.cacheData)
        }
      },
      onSubmit() {
        console.log(`this.form`, this.form)
				this.$refs.ruleForm.validate(valid => {
					if (valid) {
            this.submitType === 'add' && this.addAttr()
            this.submitType === 'edit' && this.editAttr()
					} else {
						console.log('error submit!!')
						return false
					}
				})
			},
      handleOk() {
				this.$emit('handleOk')
			},
      addAttr() { // 属性新增
        addAttr({ ...this.form, modelId: this.$route.query.id }).then((res) => {
          if (res.code === 200) {
            this.$message.info('属性新增成功')
            this.$emit('handleOk')
            this.$emit('getAttribute')
          }
        })
      },
      editAttr() { // 属性修改
        editAttr({ ...this.form, modelId: this.$route.query.id }).then((res) => {
          if (res.code === 200) {
            this.$message.info('属性修改成功')
            this.$emit('handleOk')
            this.$emit('getAttribute')
          }
        })
      },
      checkUnique(type, data, fromName) {
        // console.log(`data`, type, data)
        checkUnique({ id: this.dataId, ...data, modelId: this.$route.query.id }).then((res) => {
          if (res.code === 200) {
            if (res.status === '1') {
              this.$message.info(`${fromName}已存在,请重新填写`)
              type === 0 && this.$set(this.form, 'attrCode', '')
              type === 1 && this.$set(this.form, 'attrName', '')
            }
          }
        })
      }
    },
    watch: {
      'form.attCoderuleInfo': {
        deep: true,
        immediate: true,
        handler(newVal, oldVal) {
          if (this.form.attCoderuleInfo) {
            this.encodingButton[0].disabled = this.form.attCoderuleInfo.filter(i => i.name === '固定码').length >= 4
            this.encodingButton[1].disabled = this.form.attCoderuleInfo.filter(i => i.name === '分类码').length >= 1
            this.encodingButton[2].disabled = this.form.attCoderuleInfo.filter(i => i.name === '流水码').length >= 1
            this.encodingButton[3].disabled = this.form.attCoderuleInfo.filter(i => i.name === '日期码').length >= 1
            this.encodingButton[4].disabled = this.form.attCoderuleInfo.filter(i => i.name === '时间码').length >= 1
            this.encodingButton[5].disabled = this.form.attCoderuleInfo.filter(i => i.name === '随机码').length >= 1
          }
        }
      },
      submitType: {
        immediate: true,
        handler(val) {
          console.log(`val`, val)
        }
      }
    }
	}
</script>

<style lang="less" scoped>
.mult{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.encoding{
  box-sizing: border-box;
  height: 30px;
  line-height: 22px;
  margin-right: 10px;
  border: 1px solid #ccc;
  padding: 3px 5px;
  margin-bottom: 10px;
}
.encoding-select{
  margin-right: 30px;
  position: relative;
  &:not(:last-child)::after{
    content: '+';
    position: absolute;
    right: -20px;
    top: 50%;
    transform: translateY(-50%);
  }
}
.editable-row-operations a {
  margin-right: 8px;
}
</style>
