<template>
  <div>
    <van-form class="cellGroup" :readonly="disabled" ref="vanform">
      <!-- <div class="cellGroup"> -->
      <template v-for="(item, index) in formData">
        <template v-if="!item.hidden">
          <div
            :key="index + '111'"
            v-if="item.type === 'title'"
            class="questionnaireTitle"
          >
            <span>{{ item.label }}</span>
          </div>
          <van-cell-group
            v-if="item.type !== 'button'"
            :key="index"
            :border="border"
            :class="item.isTop ? 'top' : 'seat'"
            :style="{ 'border-radius': item.radius }"
          >
            <van-field
              v-if="item.type == 'text'"
              :class="{ 'vertical-field': item.title.length > 9 }"
              clearable
              center
              v-model="form[item.prop]"
              :label-width="item.labelWidth || 160"
              :name="item.name"
              :readonly="disabled || item.disabled"
              :label="item.title"
              :value="form[item.prop]"
              :placeholder="
                disabled ? '' : item.placeholder || `请输入${item.title}`
              "
              :input-align="item.inputAlign || 'right'"
              :maxlength="item.maxlength"
              :required="item.required"
              :rules="item.rules"
              :type="item.inputType || 'number'"
              error-message-align="right"
              :style="{
                height: cellHeight,
                'border-radius': item.cellBorder,
                margin: item.cellMargin
              }"
              @input="item.input ? item.input(form[item.prop], index) : {}"
              @blur="
                item.blur ? item.blur(form[item.prop], index, item.prop) : {}
              "
            >
              <template slot="extra">
                {{ item.suffix }}
              </template>
            </van-field>
            <!-- 数据展示 -->
            <van-field
              v-if="item.type == 'readField'"
              class="vertical-field"
              readonly
              v-model="form[item.prop]"
              :name="item.name"
              :label="item.label"
              :value="form[item.prop]"
              :input-align="item.inputAlign || 'right'"
              :rules="item.rules"
              :style="{
                'border-radius': item.cellBorder,
                margin: item.cellMargin
              }"
            >
              <template slot="input">
                <span>{{ form[item.prop] }}</span>
                <van-tag
                  v-show="item.tagShow == true"
                  plain
                  type="primary"
                  color="white"
                  text-color="#0079fe"
                  round
                  >{{ item.tag }}</van-tag
                >
              </template>
              <template slot="right-icon">
                <!-- <van-checkbox-group v-model="formList.checkbox"> -->
                <van-checkbox
                  name="checkbox"
                  v-model="formList.checkbox"
                  v-show="item.checkboxShow == true"
                />
                <!-- </van-checkbox-group> -->
              </template>
            </van-field>
            <!-- 选择器 -->
            <van-field
              v-if="item.type == 'pickerField'"
              readonly
              is-link
              clickable
              center
              :name="item.name"
              :label="item.label"
              :value="transPicker(pickerData[item.prop], item.columns)"
              :placeholder="
                item.placeholder ? item.placeholder : `请选择${item.label}`
              "
              input-align="right"
              error-message-align="right"
              @click="
                () => {
                  if (!disabled) {
                    item.showPicker = true
                  }
                }
              "
              :rules="item.rules"
              :style="{
                height: cellHeight,
                'border-radius': item.cellBorder,
                margin: item.cellMargin
              }"
              @change="pickerCellChange(item, form[item.prop])"
            >
            </van-field>
            <van-popup v-model="item.showPicker" round position="bottom">
              <van-picker
                show-toolbar
                :columns="item.columns"
                v-model="form[item.prop]"
                @cancel="item.showPicker = false"
                @confirm="onConfirm($event, index, item.prop)"
                ref="picker"
              />
            </van-popup>

            <!-- 链接跳转 -->
            <van-cell
              :title="item.label"
              :is-link="item.isLink"
              @click="item.func ? item.func(item) : {}"
              :icon="item.icon"
              :style="{ height: cellHeight, 'border-radius': item.cellBorder }"
              border
              clickable
              center
              v-if="item.type == 'cell'"
            >
              <template slot="right-icon" v-if="item.tag">
                <van-tag
                  :type="item.tag.type"
                  :color="item.tag.color"
                  :text-color="item.tag.textColor"
                  >{{ item.tag.text }}</van-tag
                >
              </template>
              <!-- <template v-if="index==0" #value>
            <span>{{item.num}}人</span>
            <van-tag plain type="primary" color="white" text-color="#0079fe">+{{item.new}}</van-tag>
            </template>-->
            </van-cell>
            <!-- 时间 -->
            <div v-else-if="item.type === 'date'">
              <van-field
                readonly
                clickable
                name="datetimePicker"
                :value="form[item.prop]"
                :label="item.label"
                :label-width="item.labelWidth || 160"
                :rules="item.rules"
                placeholder="点击选择时间"
                input-align="right"
                @click="openPopup(item.prop)"
              />
            </div>
            <!-- 单选 -->
            <van-field
              class="vertical-field"
              v-if="item.type == 'radio'"
              :label="item.title"
              :name="item.name"
              :required="item.required"
              :rules="item.rules"
            >
              <template slot="input">
                <van-radio-group
                  v-model="form[item.prop]"
                  :disabled="disabled || item.disabled"
                  :label-width="item.labelWidth || 160"
                >
                  <van-radio
                    v-for="(rItem, rIndex) in item.options"
                    :key="rIndex"
                    :name="rItem.id"
                    >{{ rItem.option }}

                    <span class="tips">{{ rItem.tips }}</span>
                  </van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <!-- 含显隐控制单选 -->
            <van-field
              class="vertical-field"
              v-if="item.type == 'complexRadio'"
              :label="item.label"
              :name="item.name"
              :required="item.required"
              :rules="item.rules"
            >
              <template slot="input">
                <van-radio-group
                  v-model="form[item.prop]"
                  :disabled="disabled || item.disabled"
                  :label-width="item.labelWidth || 160"
                  @change="
                    valueChangedFunc(
                      item.children,
                      form[item.prop],
                      item.showChildrenValue
                    )
                  "
                >
                  <van-radio
                    v-for="(rItem, rIndex) in item.opts"
                    :key="rIndex"
                    :name="rItem.value"
                    >{{ rItem.label }}

                    <span class="tips">{{ rItem.tips }}</span>
                  </van-radio>
                  <template
                    v-if="item.showChildrenValue.includes(form[item.prop])"
                  >
                    <template v-for="(child, i) in item.children">
                      <div
                        v-if="child.type === 'devider'"
                        :key="i + '00'"
                        style="color: #666666"
                      >
                        {{ child.label }}
                      </div>
                      <van-field
                        :key="i + '00'"
                        v-if="child.type === 'radio'"
                        class="vertical-field"
                        :label="child.label"
                        :name="child.name"
                        :required="child.required"
                        :rules="child.rules"
                      >
                        <template slot="input">
                          <van-radio-group
                            v-model="form[child.prop]"
                            class="init-radio"
                          >
                            <van-radio
                              v-for="(oItem, oIndex) in child.opts"
                              :key="'0' + oIndex"
                              :name="oItem.value"
                              >{{ oItem.label }}</van-radio
                            >
                          </van-radio-group>
                        </template>
                      </van-field>

                      <van-field
                        :key="'a' + i"
                        v-if="child.type == 'input'"
                        :class="{ 'vertical-field': child.label.length > 15 }"
                        clearable
                        center
                        v-model="form[child.prop]"
                        :label-width="child.labelWidth || 160"
                        :name="child.name"
                        :readonly="disabled || child.disabled"
                        :label="child.label"
                        :value="form[child.prop]"
                        :placeholder="
                          disabled
                            ? ''
                            : child.placeholder || `请输入${child.label}`
                        "
                        :input-align="child.inputAlign || 'right'"
                        :maxlength="child.maxlength"
                        :required="child.required"
                        :rules="child.rules"
                        :type="child.inputType"
                        error-message-align="right"
                        :style="{
                          height: cellHeight,
                          'border-radius': child.cellBorder,
                          margin: child.cellMargin
                        }"
                        @input="
                          child.input
                            ? child.input(form[child.prop], index)
                            : {}
                        "
                        @blur="
                          child.blur
                            ? child.blur(form[child.prop], index, child.prop)
                            : {}
                        "
                      />
                    </template>
                  </template>
                </van-radio-group>
              </template>
            </van-field>
            <!-- 复选 -->
            <van-field
              class="vertical-field"
              v-if="item.type == 'checkbox'"
              :label="item.label"
              :name="item.name"
              :required="item.required"
              :rules="item.rules"
            >
              <template slot="input">
                <van-checkbox-group
                  v-model="form[item.prop]"
                  :disabled="disabled || item.disabled"
                  :label-width="item.labelWidth || 160"
                >
                  <van-checkbox
                    v-for="(cItem, cIndex) in item.opts"
                    @click="item.func(form[item.prop], item.opts, item.prop)"
                    :key="cIndex"
                    :name="cItem.value"
                    shape="square"
                    >{{ cItem.label }}
                    <span class="tips">{{ cItem.tips }}</span>
                  </van-checkbox>
                </van-checkbox-group>
              </template>
            </van-field>
            <!-- 分隔 占位 -->
          </van-cell-group>

          <!-- 按钮 -->
          <van-button
            :key="index"
            v-if="item.type == 'button'"
            :type="item.buttonType"
            :plain="item.plain"
            :size="item.size"
            :disabled="disabled"
            :loading="btnLoading"
            @click="item.func ? item.func() : onSubmit()"
            :class="item.isAbsolute ? 'absolute-button' : ''"
            :style="{
              margin: item.buttonMargin,
              background: item.buttonBackground,
              color: item.buttonColor,
              border: item.buttonBorder,
              width: item.buttonWidth,
              'font-size': item.textSize
            }"
            >{{ item.buttonText }}</van-button
          >
        </template>
      </template>
      <!-- </div> -->
    </van-form>
    <van-popup v-model="showPicker" position="bottom">
      <van-datetime-picker
        @confirm="handlePickerConfirm"
        v-model="currentDate"
        type="date"
        @cancel="showPicker = false"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  name: "VForm",
  props: {
    //表单
    formData: {
      type: Array,
      isLink: { type: String, default: "false" },
      isAbsolute: { type: Boolean, default: false }, //固定按钮
      // type:{ type: String, default: 'cell' },
      //   cornertext: String,
      showPicker: { type: Boolean, default: false }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    formEdit: Object, //数据
    border: Boolean,
    cellHeight: {
      type: String,
      default: "48px"
    },
    isPart: {
      type: Boolean,
      default: false
    }, //只返回有项目的表单数据
    loading: {
      type: Boolean,
      default: false
    }
  },
  components: {},
  data() {
    return {
      minDate: new Date(1910, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      formList: {
        type: Array,
        validateText: "",
        checkbox: 1 || 0
      },
      form: {},
      pickerData: {},
      showPicker: false,
      prop: "",
      btnLoading: false
    }
  },

  computed: {},
  methods: {
    valueChangedFunc(children, value, showChildrenValue) {
      console.log(children, value, showChildrenValue)
      if (!showChildrenValue.includes(value)) {
        // 清除值
        children.forEach((e, index) => {
          this.form[e.prop] = ""
        })
      }
    },
    //picker数据转化
    transPicker(data, list) {
      console.log("输入", data)
      let value = data
      if (parseFloat(Number(data)).toString() != "NaN" && list) {
        const item = list.find((_) => String(_.value) == String(data))
        value = item ? item.text : data
      }
      console.log("转化", value)
      return value
    },
    onSubmit() {
      // this.btnLoading = true
      //表单验证
      this.$refs.vanform
        .validate()
        .then(() => {
          this.$emit("handleConfirm", this.form)
        })
        .catch(() => {
          this.btnLoading = false
          // this.$toast.fail("验证失败")
        })
    },

    handlePickerConfirm(time) {
      this.form[this.prop] = new Date(time).toLocaleDateString()
      this.showPicker = false
    },
    openPopup(prop) {
      if (this.disabled) return
      this.prop = prop
      this.showPicker = true
    },
    pickerCellChange(item, data) {
      console.log("弹出返回值", item, data)
    },
    // 弹出框
    onConfirm(value, index, prop) {
      // console.log("pick", value, index, prop)
      // this.form[index].value = value;
      if (Array.isArray(value)) {
        this.form[prop] = value.join("")
        this.pickerData[prop] = value.join("")
      } else {
        this.pickerData[prop] = value.text
        this.form[prop] = value.value
      }
      // console.log('选择变更',this.pickerData,this.form)
      this.formData[index].showPicker = false
      this.$emit("handlePicker", value, prop)
    },
    // 初始化整个表单（可在初始化时赋值）
    initforms() {
      const form = {}
      const data = {}
      this.formData.forEach((item) => {
        if (!item.prop || item.hidden) return false
        if (
          item.type === "checkbox" ||
          item.type === "cascader" ||
          item.multiple
        ) {
          form[item.prop] = []
        } else {
          form[item.prop] = ""
          if (item.type === "pickerField") {
            data[item.prop] = ""
          }
        }
      })
      if (this.formEdit) {
        // this.form=form
        this.form = Object.assign(form, this.formEdit) //包含非表单
      } else {
        this.form = Object.assign({}, form)
      }
      this.pickerData = Object.assign({}, data, this.formEdit)
    },
    // 给表单部分字段赋值（此时表单已初始化）
    initFields(obj) {
      for (const key in obj) {
        this.form[key] = obj[key]
      }
    }
  },
  watch: {
    formEdit: {
      handler() {
        this.initforms()
      },
      deep: true
    },
    pickerData(val) {},
    loading(val) {
      if (val != this.btnLoading) {
        this.btnLoading = val
      }
    },
    form(val) {
      // console.log("最终", val)
    }
  },
  created: function () {
    this.initforms()
  }
}
</script>

<style lang="scss" scoped>
.cellGroup {
  // display: flex;
  // flex-wrap: wrap;
  // margin: 10px 0px;
  border-radius: 5px;
  overflow: hidden;
  // background: white;
  //   display: inline;
}
.formButton {
  text-align: center;
}
.top {
  // border-radius: 5px 5px 0px 0px;
  border-color: white !important;
  overflow: hidden;
}
.seat {
  border-radius: 0px 0px 5px 5px;
  overflow: hidden;
  // margin-bottom: 10px;
}
.absolute-button {
  position: fixed;
  z-index: 999;
  top: 4px;
  right: 20px;
  padding: 0px;
  font-size: 14px;
  width: 40px;
}
::v-deep .van-field__label {
  // width: 4.5em;
  margin-right: 3px;
  width: fit-content;
}
.vertical-field {
  display: flex;
  flex-direction: column;
  ::v-deep .van-field__label {
    width: 100%;
  }
  ::v-deep .van-field__value {
    width: 100%;
  }
  .van-radio-group {
    border: 1px solid #d3d3d3;
    padding: 4px 8px;
    border-radius: 4px;
    width: 100%;
    margin: 12px 0px 0px;
    ::v-deep {
      .van-radio__label {
        margin-left: 12px;
      }
    }
  }
  .van-radio {
    padding: 5px;
    padding: 10px 4px 10px;
  }
  .van-radio:not(:last-child) {
    border-bottom: 1px solid #d3d3d3;
  }
  .van-checkbox-group {
    border: 1px solid #d3d3d3;
    padding: 5px;
    border-radius: 5px;
    width: 100%;
    margin: 5px 10px 0px;
  }
  .van-checkbox {
    padding: 5px;
    border-bottom: 1px solid #d3d3d3;
  }
  .van-checkbox:last-child {
    border: none !important;
  }
  ::v-deep .van-checkbox__icon--square {
    border-radius: 3px;
    overflow: hidden;
  }
}
.tips {
  font-size: 12px;
  font-weight: 400;
  color: #3577f1;
  margin-left: 5px;
}
::v-deep .van-cell {
  // border-radius: 5px;
  //   height: 55px;
  padding: 12px;
  min-height: 44px;
  overflow: visible;
}
// ::v-deep .van-cell__title {
//   margin-left: 10px;
// }
::v-deep .van-cell::after {
  padding: 12px;
  border: none !important;
}
::v-deep .van-divider {
  background: white;
  padding: 7px;
  margin: 0;
}
::v-deep .van-radio__label--disabled {
  color: #323233;
}
::v-deep .van-checkbox__label--disabled {
  color: #323233;
}
::v-deep .van-tag {
  margin-left: 25px;
  padding: 7px 20px;
}

.code-button {
  background: none !important;
  border: none !important;
  height: 30px !important;
  color: rgba(0, 121, 254, 1);
}
::v-deep {
  .van-radio__icon--disabled .van-radio__icon--checked .van-icon {
    background: #1e80ff !important;
  }
  .van-radio__icon--disabled.van-radio__icon--checked .van-icon {
    background: #1e80ff !important;
  }
}
.init-radio {
  border: none !important;
  .van-radio:not(:last-child) {
    border-bottom: none !important;
  }
}
.questionnaireTitle {
  background: #fff;
  padding: 12px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  color: #666666;
}
.van-cell {
  border-bottom: 1px solid #f5f5f5;
}
::v-deep .van-button {
  border-radius: 50px !important;
}
</style>
