<template>
  <view class="w-table">
    <uni-collapse
      ref="collapse"
      v-model="opened"
      @change="resize"
      style="height: max-content"
    >
      <uni-collapse-item
        :ref="`tableRow${i}`"
        :show-animation="true"
        class="w-table-row"
        v-for="(row, i) in _value"
        :key="`row_${i + 1 * pageInfo.pageNo}`"
      >
        <template v-slot:title>
          <view class="w-table-row-tt">
            <view style="display: flex; flex: 1; align-items: center">
              <text style="padding: 16rpx 15px">第 {{ i + 1 }} 项</text>
              <uni-icons
                v-if="errRow.has(i)"
                type="info"
                :size="20"
                color="#CE5266"
              ></uni-icons>
            </view>
            <view
              @click.stop="delTbRow(i)"
              style="color: #999999"
              v-if="!readonly"
              >删除</view
            >
          </view>
        </template>
        <uni-forms
          :ref="`wflowTableForm_${i}`"
          :rules="rules"
          :modelValue="_value[i]"
          label-position="top"
          label-width="200"
        >
          <uni-forms-item
            class="w-form-item"
            :ref="`wflowItem${col.id}`"
            v-for="col in formProps.columns"
            :name="col.id"
            :key="col.id"
            :required="col.props.required"
          >
            <template v-slot:label>
              <view
                style="display: flex; align-items: center; padding: 13rpx 0"
              >
                <text style="color: #ce5266" v-if="col.props.required">* </text>
                <text style="font-size: 32rpx">{{ col.title }}</text>
              </view>
            </template>
            <w-form-item
              @resize="$refs.collapse.resize()"
              @myblur="myblur"
              :cid="col.id"
              :type="col.name"
              v-model="_value[i][col.id]"
              :form-props="col.props"
              :title="col.title"
              :readonly="col.perm !== 'E'"
              :formData="formData"
              :index="i + 1"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-collapse-item>
    </uni-collapse>
    <view class="w-table-add" @click="addRow" v-if="!readonly">+ 添加明细</view>
    <van-pagination v-if="formProps.pageFlag" v-model="pageInfo.pageNo" :total-items="modelValue.length" :items-per-page="pageInfo.pageSize" />
  </view>
</template>

<script>
import "vant/lib/index.css";
export default {
  name: "TableList",
  props: {
    modelValue: {
      //表单双向绑定的值
      type: Array,
      default: () => {
        return [];
      },
    },
    formData: {
      //表单值
      type: Object,
      default: () => {
        return {};
      },
    },
    formProps: {
      //表单联动相关配置
      type: Object,
      default: () => {
        return {};
      },
    },
    readonly: Boolean,
  },
  computed: {
    _value: {
      get() {
        console.log(this.modelValue, 123123456);
        if(this.formProps.pageFlag) {
          return this.modelValue ? this.modelValue.slice((this.pageInfo.pageNo - 1) * this.pageInfo.pageSize, this.pageInfo.pageNo * this.pageInfo.pageSize) : [];
        }
        return this.modelValue ? this.modelValue : [];
      },
      set(val) {
        this.$emit("update:modelValue", val);
      },
    },
    rules() {
      const formRule = {};
      this.formProps.columns.forEach((v) => {
        formRule[v.id] = {
          rules: [
            {
              required: v.props.verify ? true : v.props.required,
              errorMessage: "请填写" + v.title,
            },
          ],
        };
        if (v.props.verify) {
          console.log(JSON.stringify(v.props.verify), 123456);
          formRule[v.id].rules.push({
            validateFunction: (rule, value, data, callback) => {
              // console.log(
              // 	"校验",
              // 	rule,
              // 	value,
              // 	v.props.verify,
              // 	new RegExp(v.props.verify).test(value)
              // );
              if (!eval(v.props.verify).test(value)) {
                callback(`请输入正确的${v.title}格式`);
              }
              return true;
            },
          });
        }
      });
      return formRule;
    },
  },
  data() {
    return {
      opened: [],
      errRow: new Set(),
      currentPage: 1,
      pageInfo: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
      }
    };
  },
  beforeMount() {
    // console.log(this.formProps.columns,303030)
    // this.doAddRow();
    if (!this._value) {
      this._value = [];
    }
  },
  //// #ifdef MP
  mounted() {
    console.log(this.formProps.columns, 202020);
    this.$nextTick(() => {
      this.$refs.collapse.resize();
      uni.$emit("showFp");
    });
  },
  //// #endif
  methods: {
    myblur(options) {
    //   console.log(7854578, options.cid, options.value, this._value.length - 1);

		
    //    console.log(this.$refs[`wflowItem${options.cid}`][this._value.length - 1], 123456789);
	   this.$refs[`wflowItem${options.cid}`][this._value.length - 1].form.setValue(options.cid, options.value);
    },
    resize() {
      setTimeout(() => this.$emit("resize"), 800);
    },
    validate(call) {
      //校验表格所有行数据
      const valids = [];
      this.$refs.collapse.resize();
      this._value.forEach((v, i) => {
        valids.push(
          new Promise((resolve) => {
            //对表格数据进行循环校验
            const formRef =
              this.$refs[`wflowTableForm_${this._value.length - 1}`];
            formRef[0]
              .validate()
              .then((res) => {
                this.errRow.delete(i);
                resolve(true);
              })
              .catch((err) => {
                //展开所有错误的行
                if (this.opened.indexOf(i) < 0) {
                  this.opened.push(i);
                }
                this.errRow.add(i);
                resolve(false);
              });
          })
        );
      });
      if (valids.length > 0) {
        Promise.all(valids).then((results) => {
          // 检查结果所有校验都成功为true
          const isSuccess = results.every((valid) => valid === true);
          call(isSuccess);
        });
      }
    },
    addRow() {
      let that = this;
      if ((this._value || []).length > 0) {
        const formRef = this.$refs[`wflowTableForm_${this._value.length - 1}`];
        //校验上一行表单
        this.validate((valid) => {
          if (valid) {
            this.doAddRow();
          } else {
            that.$nextTick(() => {
              that.$refs.collapse.resize();
              uni.$emit("showFp");
            });
            uni.showToast({
              icon: "none",
              title: "请完成之前的数据",
            });
          }
        });
      } else {
        this.doAddRow();
      }
    },
    delTbRow(i) {
      uni.showModal({
        title: "提示",
        content: "确定要删除当前表格行数据吗？",
        success: (res) => {
          if (res.confirm) {
            if (this.formProps.pageFlag) {
              this._value.splice(i + (this.pageInfo.pageNo - 1) * this.pageInfo.pageSize, 1);
            } else {
              this._value.splice(i, 1);
            }
            this._value = this._value;
            this.resize();
            setTimeout(() => uni.$emit("showFp"), 500);
          }
        },
      });
    },
    doAddRow() {
      if (
        (this.formProps.maxSize || 0) > 0 &&
        this._value.length >= this.formProps.maxSize
      ) {
        uni.showToast({
          icon: "none",
          title: "已达到限制行数",
        });
        return;
      }
      // if ((this.formProps.maxSize || 0) > 0 && this.formProps.columns.length >= this.formProps.maxSize) {
      // 	uni.showToast({
      // 		icon: 'none',
      // 		title: '已达到限制行数'
      // 	})
      // 	return
      // }
      const row = {};
      this.formProps.columns.forEach((v) => (row[v.id] = null));
      this._value.push(row);
      this._value = this._value;
      this.resize();
      this.$forceUpdate();
      setTimeout(() => uni.$emit("showFp"), 500);
    },
  },
  watch: {
    opened: {
      deep: true,
      handler() {
        setTimeout(() => uni.$emit("showFp"), 500);
        this.$emit("validateFn", this.validate);
      },
    },
    // _value: {
    // 	deep: true,
    // 	handler() {

    // 	}
    // }
  },
  emits: ["update:modelValue", "resize"],
};
</script>

<style lang="less" scoped>
:deep(.van-pagination__item--active) {
  color: white !important;
}
.w-table {
  //background-color: #F4F5F7;
}

.w-table-add {
  display: flex;
  color: #4478f7;
  justify-content: center;
  align-items: center;
  padding-top: 10rpx;
}

:deep(.w-table-row) {
  .w-table-row-tt {
    display: flex;
    align-items: center;

    & > view:first-child {
      flex: 1;
    }

    & > view:last-child {
    }
  }

  .uni-collapse-item__title-box {
    height: 70rpx;
    line-height: 70rpx;
    background-color: #f8f9fa;
  }

  .uni-collapse-item__title {
    border-bottom: 4rpx solid white;
    background-color: #f8f9fa;
    border-radius: 10rpx;

    .uni-collapse-item__title-wrap {
      display: flex;
      align-items: center;
      margin-right: 20rpx;
    }
  }

  .uni-collapse-item__wrap-content.uni-collapse-item--border {
    border-bottom-color: white;
  }

  .w-form-item {
    border-bottom: 4rpx solid #f8f9fa;
    // margin-bottom: 0;
    // height: auto;
  }

  .w-form-item:last-child {
    border-bottom: none;
  }
}
</style>
