<template>
  <div>
    <div v-if="!isMobileFlag" style="position: relative">
      <a class="add-btn" v-if="!(readonly || disabled) || props.record?.formItemTable?.showAddFlag" @click="addClick">新增</a>
      <a-form-item-rest>
        <a-table
          :dataSource="dataValue"
          :bordered="props.record?.formItemTable?.showBorderFlag"
          :columns="columns"
          size="middle"
          :border="record.border"
          rowKey="id"
          :pagination="false"
        >
          <template #bodyCell="{ column, record: data, index }">
            <template v-if="column?.key == 'index'">
              {{ index + 1 }}
            </template>
            <template v-else-if="column?.key == 'action'">
              <a-space>
                <icon-font
                  iconClass="icon-opt-shanchu"
                  font-size="24px"
                  title="删除"
                  color="#60666b"
                  @click="remove(index)"
                  v-if="!(props.readonly || props.disabled) || props.record?.formItemTable?.showDeleteFlag"
                ></icon-font>
              </a-space>
            </template>
            <template v-if="column?.dataIndex">
              <FormItemComponent
                :record="props.record.columnList[index][column.dataIndex]"
                :formConfig="props.formConfig"
                :formData="data"
                :isDesgin="props.isDesgin"
                :formRef="props.formRef"
                @onClick="recordClick($event, data, props.record.columnList[index])"
                @onChange="recordChange($event, data, props.record.columnList[index])"
                @onBlur="recordBlur($event, data, props.record.columnList[index])"
                @onFocus="recordFocus($event, data, props.record.columnList[index])"
                @onInput="recordInput($event, data, props.record.columnList[index])"
                :readonly="props.readonly"
                v-if="!props.record.columnList[index][column.dataIndex].itemHiddenFlag"
                :disabled="tableItemDisabled(props.record.columnList[index][column.dataIndex])"
              ></FormItemComponent>
              <span v-else></span>
            </template>
          </template>
        </a-table>
      </a-form-item-rest>
    </div>
    <div v-if="isMobileFlag" class="mobile-table">
      <div class="table-line" v-if="dataValue?.length > 0"></div>
      <div class="mobile-table-list" v-if="dataValue">
        <div class="mobile-table-item" v-for="(item, index) in dataValue" :key="index">
          <div class="table-line" v-if="index != 0"></div>
          <div class="mobile-table-item-box">
            <div class="mobile-table-item-header">
              <div class="mobile-table-item-header-title">{{ props.record.itemLabelName }}{{ index + 1 }}</div>
              <div class="mobile-table-item-header-action">
                <icon-font
                  iconClass="icon-opt-shanchu"
                  font-size="20px"
                  title="删除"
                  color="#60666b"
                  @click="remove(index)"
                  v-if="!(props.readonly || props.disabled) || props.record?.formItemTable?.showDeleteFlag"
                ></icon-font>
              </div>
            </div>
            <a-form-item-rest>
              <div class="mobile-table-item-content" v-if="columns?.length">
                <div v-for="cItem in columns">
                  <template v-if="cItem?.dataIndex">
                    <FormItemComponent
                      :record="props.record.columnList[index][cItem.dataIndex]"
                      :formConfig="props.formConfig"
                      :formData="item"
                      @onClick="recordClick($event, item, props.record.columnList[index])"
                      @onChange="recordChange($event, item, props.record.columnList[index])"
                      @onBlur="recordBlur($event, item, props.record.columnList[index])"
                      @onFocus="recordFocus($event, item, props.record.columnList[index])"
                      @onInput="recordInput($event, item, props.record.columnList[index])"
                      :readonly="props.readonly"
                      v-if="!props.record.columnList[index][cItem.dataIndex]?.itemHiddenFlag"
                      :disabled="tableItemDisabled(props.record.columnList[index][cItem.dataIndex])"
                    >
                    </FormItemComponent>
                  </template>
                </div>
              </div>
            </a-form-item-rest>
          </div>
        </div>
      </div>
      <div class="table-add" @click="addClick" v-if="!(props.readonly || props.disabled) || props.record?.formItemTable?.showAddFlag">
        添加{{ props.record.itemLabelName }}
      </div>
    </div>
  </div>
</template>

<script setup name="FormTable">
import { ref, onMounted, watch, computed, onUnmounted } from 'vue';
import { Modal } from 'ant-design-vue/es';
import Request from '@/utils/request/request-util';
import FormItemComponent from '../../components/form-item.component.vue';
import { deepClone } from '@/utils/common/util';
import { useUserStore } from '@/store/modules/user';

const props = defineProps({
  value: {
    type: Array,
    default: () => []
  },
  //是否禁用
  disabled: Boolean,
  // 当前行数据
  record: {
    type: Object,
    default: {}
  },
  formConfig: {
    type: Object,
    required: true
  },
  // 是否只读
  readonly: Boolean,
  // 是否是设计
  isDesgin: {
    type: Boolean,
    default: false
  },
  // ref
  formRef: {
    type: Object,
    default: null
  }
});

const emits = defineEmits(['update:value']);

const userStore = useUserStore();

const windowWidth = ref(window.innerWidth);

const isMobileFlag = computed(() => {
  return windowWidth.value <= 768 ? true : false;
});

onMounted(() => {
  setColumnData(true);
  window.addEventListener('resize', resize);
});

onUnmounted(() => {
  window.removeEventListener('resize', resize);
});

const resize = e => {
  windowWidth.value = e.target.innerWidth;
};

// 选中的值
const dataValue = ref([]);
// 排序配置
const sortData = ref({ title: '序号', width: 80, key: 'index' });
// 操作配置
const actionData = ref({
  title: '操作',
  align: 'center',
  fixed: 'right',
  width: 80,
  key: 'action'
});
// 表格配置
const columns = ref([]);

// 表格子禁用
const tableItemDisabled = computed(() => value => {
  if (value?.itemEditFlag) {
    return false;
  }
  return true;
});

// 设置表格配置
const setColumnData = (isInit = false) => {
  columns.value = [];
  let columnConfig = {};
  if (props.record?.formItemTable?.showNumberFlag) {
    columns.value.push(sortData.value);
  }
  if (props.record?.children) {
    props.record.children.forEach(item => {
      if (showFormItem(item)) {
        item.title = item.itemLabelName;
        item.dataIndex = item.fieldCode;
        columns.value.push(item);
        columnConfig[item.fieldCode] = item;
      }
    });
  }
  if (!(props.readonly || props.disabled || !props.record?.formItemTable?.showDeleteFlag)) {
    columns.value.push(actionData.value);
  }
  if (isInit) {
    props.record.columnConfig = columnConfig;

    if (props.record?.formItemTable?.defaultRowNumber) {
      for (let i = 0; i < props.record?.formItemTable?.defaultRowNumber; i++) {
          addClick();
      }
    }
  }
};

const showFormItem = item => {
  if (item.permissionCode) {
    if (!item.itemHiddenFlag && userStore.authorities.find(aItem => aItem == item.permissionCode)) {
      return true;
    } else {
      return false;
    }
  } else if (!item.itemHiddenFlag) {
    return true;
  }
  return false;
};

watch(
  () => dataValue.value,
  val => {
    dataValueChange();
  },
  { deep: true }
);

watch(
  () => props.value,
  val => {
    dataValue.value = val;
  },
  { deep: true, immediate: true }
);

watch(
  () => props.record.children,
  val => {
    setColumnData();
  },
  { deep: true }
);

// 更改值
const dataValueChange = () => {
  emits('update:value', dataValue.value);
};

// 新增列
const addClick = () => {
  let obj = {};
  if (props.record?.children) {
    props.record.children.forEach(item => {
      obj[item.fieldCode] = undefined;
    });
    dataValue.value.push(obj);
    if (!props.record.columnList) props.record.columnList = [];
    props.record.columnList.push(deepClone(props.record.columnConfig));
  }
};

// 删除
const remove = index => {
  if (!props.disabled) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的内容吗?',
      maskClosable: true,
      onOk: async () => {
        dataValue.value.splice(index, 1);
        props.record.columnList.splice(index, 1);
      }
    });
  }
};

// 点击
const recordClick = (column, record, rowColumn) => {
  if (column?.formItemEvent?.onClickEventCode) {
    const func = new Function('record', 'rowColumn', 'Request', column.formItemEvent.onClickEventCode);
    func(record, rowColumn, Request);
  }
};
// 改变
const recordChange = (column, record, rowColumn) => {
  if (column?.formItemEvent?.onChangeEventCode) {
    const func = new Function('record', 'rowColumn', 'Request', column.formItemEvent.onChangeEventCode);
    func(record, rowColumn, Request);
  }
};
// 失去焦点
const recordBlur = (column, record, rowColumn) => {
  if (column?.formItemEvent?.onBlurEventCode) {
    const func = new Function('record', 'rowColumn', 'Request', column.formItemEvent.onBlurEventCode);
    func(record, rowColumn, Request);
  }
};
// 获取焦点
const recordFocus = (column, record, rowColumn) => {
  if (column?.formItemEvent?.onFocusEventCode) {
    const func = new Function('record', 'rowColumn', 'Request', column.formItemEvent.onFocusEventCode);
    func(record, rowColumn, Request);
  }
};
// 输入值
const recordInput = (column, record, rowColumn) => {
  if (column?.formItemEvent?.onInputEventCode) {
    const func = new Function('record', 'rowColumn', 'Request', column.formItemEvent.onInputEventCode);
    func(record, rowColumn, Request);
  }
};
</script>

<style scoped lang="less">
.mobile-table {
  width: 100%;

  .mobile-table-item {
    background-color: #fff;

    .mobile-table-item-box {
      width: 100%;
      padding: 24rpx 0;
      box-sizing: border-box;

      .mobile-table-item-header {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
        justify-content: space-between;

        .mobile-table-item-header-title {
          color: #027efa;
          font-size: 32rpx;
          font-weight: bold;
        }
      }

      .mobile-table-item-content {
        :deep(.u-form-item__body) {
          background-color: #fff !important;
          padding: 30rpx 0;
        }
      }
    }
  }

  .table-line {
    width: calc(100% + 48rpx);
    margin-left: -24rpx;
    height: 24rpx;
    background-color: #edf0f2;
  }

  .table-add {
    text-align: right;
    width: calc(100% + 48rpx);
    margin-left: -24rpx;
    height: 80rpx;
    line-height: 80rpx;
    padding-right: 20rpx;
    color: #3296fa;
    cursor: pointer;
    box-sizing: border-box;
  }
}

.add-btn {
  position: absolute;
  top: -30px;
  right: 0;
}
</style>
