<template>
  <template v-if="mode === 'DESIGN'">
    <draggable class="l-drag-from" :list="_columns" group="form"
               :options="{animation: 300, chosenClass:'choose', sort:true}"
               @start="drag = true; selectFormItem = null" @end="drag = false">
      <template #item="{ element, index }">
        <div class="l-form-item" @click.stop="selectItem(element)"
             :style="getSelectedClass(element)">
          <div class="l-form-header">
            <p><span v-if="element.props.required">*</span>{{ element.title }}</p>
            <div class="l-option">
              <el-icon size="25px" @click="delItem(index)">
                <Close/>
              </el-icon>
            </div>
            <form-design-render :config="element"/>
          </div>
        </div>
      </template>
    </draggable>
    <div style="color: #c0bebe;text-align: center; width: 90%; padding: 5px;">☝ 拖拽控件到表格内部</div>
  </template>
  <template v-else>
    <template v-if="perm === 'E'">
      <div v-if="rowLayout">
        <el-table size="medium" :header-cell-style="{background:'#f5f7fa', padding:'3px 0'}" :border="showBorder"
                  :data="_value" style="width: 763px" v-tabh>
          <el-table-column fixed type="index" label="序号" width="55"></el-table-column>
          <el-table-column :min-width="getMinWidth(column)" v-for="(column, index) in _columns" :key="index"
                           :prop="column.id" :label="column.title" >
            <template #default="scope">
              <form-design-render :class="{'valid-error': showError(column, _value[scope.$index][column.id])}"
                                  v-model:value="_value[scope.$index][column.id]" :mode="mode" :config="column"/>
            </template>
          </el-table-column>
          <el-table-column fixed="right" min-width="90" label="操作">
            <template #default="scope">
              <el-button size="mini" type="primary" @click="copyData(scope.$index, scope.row)" link>复制</el-button>
              <el-button size="mini" type="primary" @click="delRow(scope.$index, scope.row)" link>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="small" icon="Plus" @click="addRow">{{ placeholder }}</el-button>
      </div>
      <div v-else>
        <el-form :rules="rules" :model="row" :ref="`table-form-${i}`" class="table-column" v-for="(row, i) in _value"
                 :key="i">
          <div class="table-column-action">
            <span>第 {{ i + 1 }} 项</span>
            <el-icon size="25px" @click="delRow(i, row)">
              <Close/>
            </el-icon>
          </div>
          <el-form-item v-for="(column, index) in _columns" :key="'column_' + index" :prop="column.id"
                        :label="column.title">
            <form-design-render v-model="row[column.id]" :mode="mode" :config="column"/>
          </el-form-item>
        </el-form>
        <el-button size="small" icon="Plus" @click="addRow">{{ placeholder }}</el-button>
      </div>
    </template>
    <template v-else-if="perm === 'R'">
      <div v-if="rowLayout">
        <el-table size="medium" :header-cell-style="{background:'#f5f7fa', padding:'3px 0'}" :border="showBorder"
                  :data="_value" style="width: 763px" v-tabh>
          <el-table-column fixed type="index" label="序号" width="50"></el-table-column>
          <el-table-column :min-width="getMinWidth(column)" v-for="(column, index) in _columns" :key="index"
                           :prop="column.id" :label="column.title">
          </el-table-column>
        </el-table>
      </div>
    </template>
  </template>
</template>

<script setup>
import draggable from "vuedraggable";
import {ValueType} from "../ComponentsConfigExport";
import FormDesignRender from '../FormDesignRender.vue'
import {useProcessStore} from '@/stores/processStore.js'
import {computed, defineEmits, defineExpose, defineProps, ref} from "vue";
import {ElMessage} from "element-plus";

const processStore = useProcessStore()
const emit = defineEmits(["input"])
const props = defineProps({
  mode: {
    type: String,
    default: 'DESIGN'
  },
  required: {
    type: Boolean,
    default: false
  },
  value: {
    type: Array,
    default: () => {
      return []
    }
  },
  perm: {
    type: String,
    default: 'E'
  },
  placeholder: {
    type: String,
    default: '添加数据'
  },
  columns: {
    type: Array,
    default: () => {
      return []
    }
  },
  showBorder: {
    type: Boolean,
    default: true
  },
  maxSize: {
    type: Number,
    default: 0
  },
  rowLayout: {
    type: Boolean,
    default: true
  },
})
const select = ref(null)
const drag = ref(false)
const _value=ref([])

const init = () => {
  if (!Array.isArray(props.value)) {
    _value.value = []
  }
}
// const _value = computed({
//   get() {
//     return props.value;
//   },
//   set(value) {
//     console.log('成都督导',value)
//     props.value=value
//   }
// })
// watch(() => _value.value, (value) => {
//   _value.value = value
// })
// const rules = computed({
// const rules = {}
// this.columns.forEach(col => {
//   if (col.props.required) {
//     rules[col.id] = [{
//       type: col.valueType === 'Array' ? 'array' : undefined,
//       required: true,
//       message: `请填写${col.title}`, trigger: 'blur'
//     }]
//   }
// })
// })
const _columns = computed({
  get() {
    return props.columns;
  },
  set(val) {
    this.columns = val;
  }
})
const selectFormItem = computed({
  get() {
    return processStore.selectFormItem
  },
  set(val) {
    processStore.selectFormItem = val
  },
})
const getMinWidth = (col) => {
  switch (col.name) {
    case 'DateTime':
      return '250px'
    case 'DateTimeRange':
      return '280px'
    case 'MultipleSelect':
      return '200px'
    default:
      return '150px'
  }
}
const showError = (col, val) => {
  // console.log('showError', val)
  if (col.props.required) {
    switch (col.valueType) {
      case ValueType.dept:
      case ValueType.user:
      case ValueType.dateRange:
      case ValueType.array:
        return !(Array.isArray(val) && val.length > 0)
      default:
        return !this.isNotEmpty(val)
    }
  }
  return false
}
const copyData = (i, row) => {
  // _value.value.push(this.deepCopy(row))
}
const delRow = (i) => {
  _value.value.splice(i, 1)
}
const addRow = () => {
  // console.log('添加', props.maxSize, _value.value)
  if (props.maxSize > 0 && _value.value.length >= props.maxSize) {
    console.log('限制大小')
    ElMessage.warning(`最多只能添加${props.maxSize}行`)
  } else {
    let row = {}
    _columns.value.map(col => {
      row[col.id] = undefined
    })
    _value.value.push(row)
    console.log('_value', _value.value)
  }
}
const delItem = (id) => {
  _columns.value.splice(id, 1)
}
const selectItem = (cp) => {
  selectFormItem.value = cp
}
const getSelectedClass = (cp) => {
  return selectFormItem.value && selectFormItem.value.id === cp.id ? 'border-left: 4px solid #f56c6c' : ''
}
const validate = (call) => {
  if (props.rowLayout) {
    let result = true
    for (let i = 0; i < props.columns.length; i++) {
      if (props.columns[i].props.required) {
        for (let j = 0; j < _value.value.length; j++) {
          result = !showError(props.columns[i], _value.value[j][props.columns[i].id])
          if (!result) {
            call(false)
            return
          }
        }
      }
    }
    call(result)
  } else {
    let success = 0
    _value.value.forEach((v, i) => {
      console.log("i", i);
      // let formRef = this.$refs[`table-form-${i}`]
      // if (formRef && Array.isArray(formRef) && formRef.length > 0) {
      //   formRef[0].validate(valid => {
      //     if (valid) {
      //       success++;
      //     }
      //   })
      // }
    })
    if (success === _value.value.length) {
      call(true)
    } else {
      call(false)
    }
  }
}
init()
defineExpose({
  validate
})
</script>

<style lang="scss" scoped>

.valid-error {
  .el-input__inner {
    border-color: #F56C6C;
  }
}

.choose {
  border: 1px dashed var(--theme-primary) !important;
}

.table-column {
  padding: 5px;
  margin-bottom: 10px;
  border-left: 3px solid #409eff;
  border-radius: 5px;
  background: #fafafa;

  .el-form-item {
    margin-bottom: 0;

    .el-form-item__label {
      height: 25px;
    }
  }

  .table-column-action {
    float: right;

    span {
      color: #afafaf;
      margin-right: 10px;
      font-size: 13px;
    }

    i {
      color: #afafaf;
      padding: 5px;
      font-size: large;
      cursor: pointer;

      &:hover {
        color: #666666;
      }
    }
  }
}

.l-drag-from {
  min-height: 50px;
  background-color: rgb(245, 246, 246);

  .l-form-item, li {
    cursor: grab;
    background: #ffffff;
    padding: 10px;
    border: 1px solid #ebecee;
    margin: 5px 0;
  }
}

.l-form-header {
  font-size: small;
  color: #818181;
  text-align: left;
  position: relative;
  background-color: #fff;

  p {
    position: relative;
    margin: 0 0 10px 0;

    span {
      position: absolute;
      left: -8px;
      top: 3px;
      color: rgb(217, 0, 19);
    }
  }

  .l-option {
    position: absolute;
    top: -10px;
    right: -10px;

    i {
      font-size: large;
      cursor: pointer;
      color: #8c8c8c;
      padding: 5px;

      &:hover {
        color: var(--theme-primary);
      }
    }
  }
}

</style>
