<template>
  <div>
    <van-form
      @submit="onSubmit"
      :disabled="formOption.disabled"
      :readonly="formOption.readonly"
      :label-width="formOption.labelWidth"
      :label-align="formOption.labelAlign || 'top'"
      :scroll-to-error="formOption.scroll"
      ref="testForm"
    >
      <van-cell-group inset>
        <div
          v-for="(i, index) in formConfig"
          :key="index"
          :style="i.style || ''"
        >
          <van-field v-if="i.type == 'title'" style="background: #ecebeb">
            <template #input>
              <div class="_title">
                {{ i.title }}
              </div>
            </template>
          </van-field>
          <van-field
            v-if="i.type == 'input'"
            v-model="formData[i.prop]"
            :label="i.label"
            :name="i.prop"
            :type="i.itemType ? i.itemType : 'text'"
            :placeholder="i.placeholder ? i.placeholder : '请输入'"
            :clearable="i.clearable ? i.clearable : false"
            :readonly="getFieldReadonly(i)"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
            :right-icon="i.isNeedRightBtn ? i.rightIcon : ''"
            @click-right-icon="i.isNeedRightBtn ? i.rightIconClick() : () => {}"
            @blur="
              i.isNeedBlurMethon ? i.blurMethon(formData[i.prop]) : () => {}
            "
            @input="
              () => {
                return i.inputFn ? i.inputFn(formData[i.prop]) : () => {};
              }
            "
          >
          </van-field>
          <!-- switch -->
          <van-field
            v-if="i.type == 'switch'"
            :label="i.label"
            :name="i.prop"
            :required="getRequired(i.prop)"
          >
            <template #input>
              <van-switch v-model="formData[i.prop]" />
            </template>
          </van-field>
          <!-- 多选checkbox -->
          <van-field
            v-if="i.type == 'checkbox'"
            :label="i.label"
            :name="i.prop"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
            <template #input>
              <van-checkbox-group
                v-model="formData[i.prop]"
                direction="horizontal"
              >
                <van-checkbox
                  shape="square"
                  v-for="j in i.data"
                  :key="j.value"
                  :name="j.value"
                  >{{ j.text }}</van-checkbox
                >
              </van-checkbox-group>
            </template>
          </van-field>
          <!-- 单选radio -->
          <van-field
            v-if="i.type == 'radio'"
            :label="i.label"
            :name="i.prop"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
            <template #input>
              <van-radio-group
                v-model="formData[i.prop]"
                direction="horizontal"
              >
                <van-radio
                  v-for="j in i.data"
                  :key="j.value"
                  :name="j.value || j.id"
                  >{{ j.label || j.title }}</van-radio
                >
              </van-radio-group>
            </template>
          </van-field>
          <!-- 单选 -->
          <van-field
            v-if="i.type == 'picker' && i.itemType == 'onePicker'"
            v-show="!i.showStatus"
            :label="i.label"
            :name="i.prop"
            v-model="formData[i.prop + 'Name']"
            is-link
            :readonly="true"
            :placeholder="i.placeholder ? i.placeholder : '请选择'"
            @click="
              () =>
                formOption.readonly || i.readonly ? '' : (i.showPicker = true)
            "
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
          </van-field>
          <van-popup
            v-model:show="i.showPicker"
            round
            position="bottom"
            v-if="i.type == 'picker' && i.itemType == 'onePicker'"
          >
            <van-picker
              :columns="i.data"
              :columns-field-names="
                i.fieldNames ? i.fieldNames : onePickerFieldNames
              "
              @cancel="i.showPicker = false"
              @confirm="
                (option) =>
                  i.changeFn
                    ? i.changeFn(option, i, index)
                    : onConfirmPicker(option, i, index)
              "
            />
          </van-popup>
          <!-- 多选 -->
          <van-field
            v-if="i.type == 'multipleChoice' && i.itemType == 'multiple'"
            v-show="!i.showStatus"
            :label="i.label"
            :name="i.prop"
            v-model="formData[i.prop + 'Name']"
            is-link
            :readonly="true"
            :placeholder="i.placeholder ? i.placeholder : '请选择'"
            @click="() => (!formOption.readonly ? (i.showPicker = true) : '')"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
          </van-field>
          <van-popup
            v-model:show="i.showPicker"
            round
            position="bottom"
            :style="{ height: '40%' }"
            v-if="i.type == 'multipleChoice' && i.itemType == 'multiple'"
          >
            <van-checkbox-group
              v-model="formData[i.prop]"
              @change="
                changeCheckboxGroup(formData, i.prop, i.data, i.fieldNames)
              "
              class="multipleChoice"
            >
              <van-checkbox
                v-for="item in i.data"
                :key="item.value"
                :name="item.value"
                >{{ item.text }}</van-checkbox
              >
            </van-checkbox-group>
          </van-popup>
          <!-- 时间选择器 -->
          <van-field
            v-if="i.type == 'picker' && i.itemType == 'datePicker'"
            :label="i.label"
            :name="i.prop"
            v-model="formData[i.prop]"
            is-link
            :readonly="true"
            :placeholder="i.placeholder ? i.placeholder : '请选择'"
            @click="() => (!formOption.readonly ? (i.showPicker = true) : '')"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
          </van-field>
          <van-popup
            v-model:show="i.showPicker"
            round
            position="bottom"
            v-if="i.type == 'picker' && i.itemType == 'datePicker'"
          >
            <van-date-picker
              @confirm="(option) => onConfirmPicker(option, i, index)"
              @cancel="i.showPicker = false"
              :min-date="i.minDate"
              :max-date="i.maxDate"
              :columns-type="i.columnsType"
            />
          </van-popup>
          <!-- 时间选择器 带时分秒 -->

          <van-field
            v-if="i.type == 'picker' && i.itemType == 'datePickerTime'"
            :label="i.label"
            :name="i.prop"
            v-model="formData[i.prop]"
            is-link
            :readonly="true"
            :placeholder="i.placeholder ? i.placeholder : '请选择'"
            @click="() => (!formOption.readonly ? (i.showPicker = true) : '')"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
          </van-field>
          <van-popup
            v-model:show="i.showPicker"
            round
            position="bottom"
            v-if="i.type == 'picker' && i.itemType == 'datePickerTime'"
          >
            <van-picker-group
              :tabs="['日期', '时间']"
              @confirm="() => datePickerTimeConfirm(i, index)"
              @cancel="i.showPicker = false"
            >
              <van-date-picker
                v-model="datePickerDateArr"
                :columns-type="i.columnsType"
              />
              <van-time-picker
                v-model="datePickerTimeArr"
                :columns-type="['hour', 'minute', 'second']"
              />
            </van-picker-group>
          </van-popup>
          <!-- 级联 城市 -->
          <van-field
            v-if="i.type == 'cascader' && i.itemType == 'city'"
            :label="i.label"
            :name="i.prop"
            v-model="formData[i.prop + 'Name']"
            is-link
            :readonly="true"
            :placeholder="i.placeholder ? i.placeholder : '请选择'"
            @click="() => (!formOption.readonly ? (i.showPicker = true) : '')"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          />
          <van-popup
            v-if="i.type == 'cascader' && i.itemType == 'city'"
            v-model:show="i.showPicker"
            round
            position="bottom"
          >
            <van-cascader
              v-model="formData[i.prop]"
              :title="i.title ? i.title : '请选择'"
              :options="cityOption"
              @close="i.showPicker = false"
              @change="(option) => cityOnChange(option, i, index)"
              @finish="
                (option) =>
                  i.finishFn ? i.finishFn(option) : () => (i.showPicker = false)
              "
            />
          </van-popup>
          <!-- 级联 公共 -->
          <van-field
            v-if="i.type == 'cascader' && i.itemType == 'common'"
            :label="i.label"
            :name="i.prop"
            v-model="formData[i.prop + 'Name']"
            is-link
            :readonly="true"
            :placeholder="i.placeholder ? i.placeholder : '请选择'"
            @click="() => (!formOption.readonly ? (i.showPicker = true) : '')"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          />
          <van-popup
            v-if="i.type == 'cascader' && i.itemType == 'common'"
            v-model:show="i.showPicker"
            round
            position="bottom"
          >
            <van-cascader
              v-model="formData[i.prop]"
              :title="i.title ? i.title : '请选择'"
              :options="i.data"
              :field-names="i.fieldNames ? i.fieldNames : fieldNames"
              @close="i.showPicker = false"
              @change="(option) => commonOnChange(option, i, index)"
              @finish="
                (option) =>
                  i.finishFn ? i.finishFn(i, option) : handleCommonFinish(index)
              "
            />
          </van-popup>
          <!-- 文件上传 -->
          <van-field
            name="uploader"
            v-if="i.type == 'upload'"
            :label="i.label"
            :readonly="i.readonly ? true : false"
          >
            <template #input>
              <van-uploader
                v-model="formData[i.prop]"
                :after-read="afterRead"
                multiple
                :max-count="9"
                :max-size="5 * 1024 * 1024"
                @oversize="onOversize"
              />
            </template>
          </van-field>
          <!-- 插槽 -->
          <van-field
            v-if="i.type == 'slot'"
            :label="i.label"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
            <template #input>
              <div style="width: 100%">
                <slot :name="i.slotName"> {{ i.slotName }}插槽占位符 </slot>
              </div>
            </template>
          </van-field>
        </div>
      </van-cell-group>
      <!-- 循环业务数据 -->
      <van-cell-group
        inset
        v-for="(item, index) in formData[btnConfigCopy.prop]"
        :key="index"
      >
        <div class="row">
          <div>{{ btnConfigCopy.listTitle || "明细" }}{{ index + 1 }}</div>
          <van-button
            plain
            type="primary"
            @click="handleRemove(index, btnConfigCopy)"
            size="mini"
            style="border: none; background: #ecebeb"
            v-if="
              formOption.btnConfig !== undefined && formOption.btnConfig.isNeed
            "
            >删除</van-button
          >
        </div>
        <!-- 循环表单数据 -->
        <div v-for="(i, sonIndex) in btnConfigCopy.listConfig" :key="i.prop">
          <van-field
            v-if="i.type == 'input'"
            v-model="formData[btnConfigCopy.prop][index][i.prop]"
            :label="i.label"
            :name="i.prop"
            :type="i.itemType ? i.itemType : 'text'"
            :placeholder="i.placeholder ? i.placeholder : '请输入'"
            :clearable="i.clearable ? i.clearable : false"
            :readonly="getFieldReadonly(i)"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
            @change="
              (val) => {
                return i.changeFn ? i.changeFn(index, val) : () => {};
              }
            "
          >
          </van-field>
          <!-- 单选 -->
          <van-field
            v-if="i.type == 'picker' && i.itemType == 'onePicker'"
            :label="i.label"
            :name="i.prop"
            v-model="formData[btnConfigCopy.prop][index][i.prop + 'Name']"
            is-link
            :readonly="true"
            :placeholder="i.placeholder ? i.placeholder : '请选择'"
            @click="handleListItemClick(i, index, sonIndex)"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
            <template #input v-if="i.isShowScanCode">
              <div style="display: flex; height: 24px">
                <div style="width: calc(100vw - 100px)">
                  {{ formData[btnConfigCopy.prop][index][i.prop + "Name"] }}
                </div>
                <div style="width: 100px; float: right; margin-top: -20px">
                  <van-button
                    plain
                    type="primary"
                    @click.native.stop="i.scanCode(index)"
                    size="mini"
                    style="border: none"
                    >扫码</van-button
                  >
                </div>
              </div>
            </template>
          </van-field>
          <!-- 时间选择器 -->
          <van-field
            v-if="i.type == 'picker' && i.itemType == 'datePicker'"
            :label="i.label"
            :name="i.prop"
            v-model="formData[btnConfigCopy.prop][index][i.prop]"
            is-link
            :readonly="true"
            :placeholder="i.placeholder ? i.placeholder : '请选择'"
            @click="handleListItemClick(i, index, sonIndex)"
            :rules="getRules(i.prop)"
            :required="getRequired(i.prop)"
          >
          </van-field>
        </div>
      </van-cell-group>
      <!-- 单独写个循环，保证弹窗唯一 -->
      <div v-for="(item, index) in btnConfigCopy.listConfig" :key="index">
        <van-popup
          v-model:show="item.showPicker"
          round
          position="bottom"
          v-if="item.type == 'picker' && item.itemType == 'onePicker'"
        >
          <van-picker
            :columns="item.data"
            :columns-field-names="
              item.fieldNames ? item.fieldNames : onePickerFieldNames
            "
            @cancel="item.showPicker = false"
            @confirm="
              (option) =>
                item.changeFn
                  ? item.changeFn(option, item, currentIndex, currentSonIndex)
                  : onConfirmListPicker(option, item)
            "
          />
          <!-- @confirm="(option) => onConfirmListPicker(option, item)"  -->
        </van-popup>
        <van-popup
          v-model:show="item.showPicker"
          round
          position="bottom"
          v-if="item.type == 'picker' && item.itemType == 'datePicker'"
        >
          <van-date-picker
            @confirm="(option) => onConfirmListPicker(option, item)"
            @cancel="item.showPicker = false"
            :min-date="item.minDate"
            :max-date="item.maxDate"
            :columns-type="item.columnsType"
          />
        </van-popup>
      </div>

      <!-- 按钮 -->
      <div
        class="btn-box"
        v-if="formOption.btnConfig !== undefined && formOption.btnConfig.isNeed"
      >
        <van-button
          :plain="btnConfigCopy.plain ? btnConfigCopy.plain : false"
          :type="btnConfigCopy.itemType ? btnConfigCopy.itemType : 'primary'"
          :size="btnConfigCopy.size ? btnConfigCopy.size : 'small'"
          style="width: 100%; border: none"
          @click="handlePush()"
        >
          <template #icon>
            <van-icon
              :name="btnConfigCopy.icon ? btnConfigCopy.icon : 'plus'"
              :size="12"
            />
          </template>
          {{
            btnConfigCopy.btnName ? btnConfigCopy.btnName : "添加"
          }}</van-button
        >
      </div>
      <div style="margin: 16px" v-show="!formOption.hiddenSubmitBtn">
        <van-button round block type="primary" native-type="submit">
          {{ formOption.submitBtnText || "提交" }}
        </van-button>
      </div>
      <div style="margin: 16px" v-show="formOption.otherBtn">
        <van-button round block type="warning" @click="handleOtherBtnClick">
          {{ formOption.otherBtnText || "其他" }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { showLoadingToast, closeToast, showNotify } from "vant";
import {
  ref,
  getCurrentInstance,
  onMounted,
  reactive,
  computed,
  toRefs,
  watch,
  defineExpose,
} from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: false,
  },
  formConfig: {
    type: Array,
    default: false,
  },
  formOption: {
    type: Object,
    default: false,
  },
  rules: {
    type: Object,
    default: false,
  },
});
const proxy = getCurrentInstance().proxy;
const { formConfig, formOption, rules } = toRefs(props);
const formData = computed(() => {
  return proxy.modelValue;
});
const cityOption = ref([]);
const fileList = ref([]);
const fieldNames = { text: "label", value: "id", children: "children" };
const onePickerFieldNames = {
  text: "text",
  value: "value",
};
const emit = defineEmits(["update:modelValue"]);

const onSubmit = () => {
  emit("onSubmit");
};
const handleOtherBtnClick = () => {
  emit("otherBtnClick");
};

// 获取验证规则
const getRules = (prop) => {
  if (rules.value.hasOwnProperty(prop) && rules.value[prop]) {
    return rules.value[prop];
  }
};
const getRequired = (prop) => {
  if (rules.value.hasOwnProperty(prop) && rules.value[prop]) {
    return true;
  }
  return false;
};
const getReadonly = (i) => {
  return i.readonly ? i.readonly : i.name == "picker" ? true : false;
};

const getFieldReadonly = (i) => {
  if (i.readonly && i.readonly === true) {
    return true;
  } else {
    if (formOption.value.readonly && formOption.value.readonly === true) {
      return true;
    } else {
      return false;
    }
  }
};

// 国家初始化
const cityOptionInit = () => {
  proxy.post("/customizeArea/list", { parentId: "0" }).then((res) => {
    cityOption.value = res.data.map((item, index) => {
      return {
        ...item,
        index: index,
        text: item.name,
        value: item.id,
        children: [],
      };
    });
  });
};
const recursionFn = (arr, val, valueAtt, childrenAtt) => {
  for (let i = 0; i < arr.length; i++) {
    const e = arr[i];
    if (e[valueAtt] !== val) {
      if (e[childrenAtt] && e[childrenAtt].length > 0) {
        const current = recursionFn(e.children, val, valueAtt, childrenAtt);
        if (current) {
          return current;
        }
      }
    } else {
      return e;
    }
  }
};
const selectDataEcho = (item, val) => {
  if (item.type === "picker" && item.itemType === "onePicker") {
    const textAtt = item.fieldNames
      ? item.fieldNames.text
      : onePickerFieldNames.text;
    const valueAtt = item.fieldNames
      ? item.fieldNames.value
      : onePickerFieldNames.value;
    const current = item.data.find((x) => x[valueAtt] === val);
    return current ? current[textAtt] : "";
  } else if (item.type === "cascader" && item.itemType === "common") {
    const textAtt = item.fieldNames ? item.fieldNames.text : fieldNames.text;
    const valueAtt = item.fieldNames ? item.fieldNames.value : fieldNames.value;
    const childrenAtt = item.fieldNames
      ? item.fieldNames.children
      : fieldNames.children;
    const arr = item.data ? item.data : [];
    const current = recursionFn(arr, val, valueAtt, childrenAtt);
    return current ? current[textAtt] : "";
  }
};

let btnConfigCopy = {};
let callNum = ref(0);
let callListNum = ref(0);
const formDataListShowLabel = () => {
  for (let i = 0; i < formData.value[btnConfigCopy.prop].length; i++) {
    const iele = formData.value[btnConfigCopy.prop][i];
    for (let j = 0; j < btnConfigCopy.listConfig.length; j++) {
      const jele = btnConfigCopy.listConfig[j];
      if (jele.type === "picker" && jele.itemType !== "datePicker") {
        if (jele.data && jele.data.length > 0) {
          formData.value[btnConfigCopy.prop][i][jele.prop + "Name"] =
            selectDataEcho(
              jele,
              formData.value[btnConfigCopy.prop][i][jele.prop]
            );
        } else {
          if (callListNum.value <= 3) {
            setTimeout(() => {
              callListNum.value++;
              return formDataListShowLabel();
            }, 1500);
          }
          return;
        }
      }
    }
  }
};
const formDataListShowLabelOne = () => {
  for (let i = 0; i < formData.value[btnConfigCopy.prop].length; i++) {
    for (let j = 0; j < btnConfigCopy.listConfig.length; j++) {
      const jele = btnConfigCopy.listConfig[j];
      if (jele.type === "picker" && jele.itemType !== "datePicker") {
        if (jele.data && jele.data.length > 0) {
          formData.value[btnConfigCopy.prop][i][jele.prop + "Name"] =
            selectDataEcho(
              jele,
              formData.value[btnConfigCopy.prop][i][jele.prop]
            );
        }
      }
    }
  }
};
// 循环 label值回显
const formDataShowLabel = () => {
  for (let i = 0; i < formConfig.value.length; i++) {
    const element = formConfig.value[i];
    if (element.type === "picker" && element.itemType !== "datePicker") {
      if (element.data && element.data.length > 0) {
        formData.value[element.prop + "Name"] = selectDataEcho(
          element,
          formData.value[element.prop]
        );
      } else {
        if (callNum.value <= 3) {
          setTimeout(() => {
            callNum.value++;
            return formDataShowLabel();
          }, 1500);
        }
        return;
      }
    } else if (element.type === "cascader" && element.itemType === "common") {
      if (element.data && element.data.length > 0) {
        formData.value[element.prop + "Name"] = selectDataEcho(
          element,
          formData.value[element.prop]
        );
      } else {
        if (callNum.value <= 3) {
          setTimeout(() => {
            callNum.value++;
            return formDataShowLabel();
          }, 1500);
        }
        return;
      }
    }
  }
};

const formDataShowLabelOne = () => {
  for (let i = 0; i < formConfig.value.length; i++) {
    const element = formConfig.value[i];
    if (element.type === "picker" && element.itemType !== "datePicker") {
      if (element.data && element.data.length > 0) {
        formData.value[element.prop + "Name"] = selectDataEcho(
          element,
          formData.value[element.prop]
        );
      }
    } else if (element.type === "cascader" && element.itemType === "common") {
      if (element.data && element.data.length > 0) {
        formData.value[element.prop + "Name"] = selectDataEcho(
          element,
          formData.value[element.prop]
        );
      }
    }
  }
};

const formDataInit = () => {
  var map = {
    input: "",
    radio: "",
    switch: false,
    checkbox: [],
    date: "",
    picker: "",
    cascader: "",
    upload: [],
  };
  // 判断是否需要按钮
  if (
    formOption.value.btnConfig &&
    Object.keys(formOption.value.btnConfig).length > 0
  ) {
    btnConfigCopy = { ...formOption.value.btnConfig };
    if (formData.value[btnConfigCopy.prop] === undefined) {
      formData.value[btnConfigCopy.prop] = [];
    }
  }
  // 初始化默认值
  let cityStatus = true;
  for (let i = 0; i < formConfig.value.length; i++) {
    const element = formConfig.value[i];
    if (
      element.type === "cascader" &&
      element.itemType === "city" &&
      cityStatus
    ) {
      cityStatus = false;
      cityOptionInit();
      // formData.value[element.prop] = map[element.type];
      // formData.value[element.prop + "Name"] = map[element.type];
    }
    if (
      formData.value[element.prop] === undefined ||
      formData.value[element.prop] === ""
    ) {
      if (element.type === "slot") {
        continue;
      } else if (element.type === "picker" || element.type === "cascader") {
        if (element.itemType !== "datePicker") {
          formData.value[element.prop] = map[element.type];
          formData.value[element.prop + "Name"] = map[element.type];
        }
      } else if (map[element.type] != undefined) {
        formData.value[element.prop] = map[element.type];
      }
    }
  }
  formDataShowLabel();
  emit("update:modelValue", formData.value);
};

formDataInit();

// 选择框  确定事件
const onConfirmPicker = (option, item, index) => {
  if (option.selectedOptions[0]) {
    switch (item.itemType) {
      case "onePicker": {
        formData.value[item.prop + "Name"] =
          option.selectedOptions[0][
            item.fieldNames.text
              ? item.fieldNames.text
              : onePickerFieldNames.text
          ];
        formData.value[item.prop] =
          option.selectedOptions[0][
            item.fieldNames.value
              ? item.fieldNames.value
              : onePickerFieldNames.value
          ];
        formConfig.value[index].showPicker = false;
      }
      case "datePicker": {
        formData.value[item.prop] = option.selectedValues.join(
          item.split ? item.split : "-"
        );
        formConfig.value[index].showPicker = false;
      }
    }
  } else {
    formConfig.value[index].showPicker = false;
  }
};
const currentIndex = ref(-1);
const currentSonIndex = ref(-1);
const handleListItemClick = (i, index, sonIndex) => {
  if (i.readonly !== undefined && i.readonly === true) {
    return;
  } else {
    if (formOption.value.readonly) {
      return;
    } else {
      currentIndex.value = index;
      currentSonIndex.value = sonIndex;
      btnConfigCopy.listConfig[sonIndex].showPicker = true;
    }
  }
};
const onConfirmListPicker = (option, item) => {
  switch (item.itemType) {
    case "onePicker": {
      formData.value[btnConfigCopy.prop][currentIndex.value][
        item.prop + "Name"
      ] =
        option.selectedOptions[0][
          item.fieldNames.text ? item.fieldNames.text : onePickerFieldNames.text
        ];
      formData.value[btnConfigCopy.prop][currentIndex.value][item.prop] =
        option.selectedOptions[0][
          item.fieldNames.value
            ? item.fieldNames.value
            : onePickerFieldNames.value
        ];
      btnConfigCopy.listConfig[currentSonIndex.value].showPicker = false;
    }
    case "datePicker": {
      formData.value[btnConfigCopy.prop][currentIndex.value][item.prop] =
        option.selectedValues.join(item.split ? item.split : "-");
      btnConfigCopy.listConfig[currentSonIndex.value].showPicker = false;
    }
  }
};

// push事件
const handlePush = () => {
  if (btnConfigCopy.clickFn && typeof btnConfigCopy.clickFn == "function") {
    btnConfigCopy.clickFn();
  }
};
// remove
const handleRemove = (index, item) => {
  if (item.deleteFn) {
    item.deleteFn(index);
  } else {
    formData.value[btnConfigCopy.prop].splice(index, 1);
  }
};
// 拉去城市最近数据及处理
const getAreaInfo = (selectedOptions, item, index) => {
  showLoadingToast("加载中...");
  proxy
    .post("/customizeArea/list", { parentId: selectedOptions.value })
    .then((res) => {
      let countryIndex = selectedOptions.selectedOptions[0].index;
      let provinceIndex =
        selectedOptions.tabIndex === 1
          ? selectedOptions.selectedOptions[1].index
          : null;
      let cityIndex =
        selectedOptions.tabIndex === 2
          ? selectedOptions.selectedOptions[2].index
          : null;
      //已经没有下级数据
      if (res.data.length === 0) {
        if (selectedOptions.tabIndex === 1) {
          formData.value[item.prop + "Name"] = selectedOptions.selectedOptions
            .map((item) => item.text)
            .join(" ");
          formConfig.value[index].showPicker = false;
          formData.value.cityObj = selectedOptions;
          return;
        }
      }
      if (selectedOptions.tabIndex === 2) {
        formData.value[item.prop + "Name"] = selectedOptions.selectedOptions
          .map((item) => item.text)
          .join(" ");
        formConfig.value[index].showPicker = false;
        formData.value.cityObj = selectedOptions;
        return;
      }
      if (selectedOptions.tabIndex === 0) {
        cityOption.value[countryIndex].children = res.data.map(
          (item, index) => {
            return {
              ...item,
              index: index,
              text: item.name,
              value: item.id,
            };
          }
        );
      } else if (selectedOptions.tabIndex === 1) {
        cityOption.value[countryIndex].children[provinceIndex].children =
          res.data.map((item, index) => {
            return {
              ...item,
              index: index,
              text: item.name,
              value: item.id,
            };
          });
      } else if (selectedOptions.tabIndex === 2) {
        cityOption.value[countryIndex].children[provinceIndex].children[
          cityIndex
        ].children = res.data.map((item, index) => {
          return {
            ...item,
            index: index,
            text: item.name,
            value: item.id,
          };
        });
      }
      closeToast();
    });
};
// 城市变动事件
const cityOnChange = (options, item, index) => {
  getAreaInfo(options, item, index);
};

const commonOnChange = ({ selectedOptions }, item, index) => {
  const textAtt = item.fieldNames ? item.fieldNames.text : fieldNames.text;
  formData.value[item.prop + "Name"] =
    selectedOptions[selectedOptions.length - 1][textAtt];
};
const handleCommonFinish = (index) => {
  formConfig.value[index].showPicker = false;
};
// 文件上传
const onOversize = () => {
  showToast("文件大小不能超过 5MB");
};

const afterRead = (file) => {
  if (file && file.length > 0) {
    for (let i = 0; i < file.length; i++) {
      file[i].status = "uploading";
      file[i].message = "上传中...";
      proxy.post("/fileInfo/getSing", { fileName: file[i].file.name }).then(
        (res) => {
          let forms = new FormData();
          forms.append("file", file[i].file);
          proxy
            .post("https://winfaster.obs.cn-south-1.myhuaweicloud.com", {
              ...res.data.uploadBody,
              file: forms.get("file"),
            })
            .then(
              () => {
                file[i].id = res.data.id;
                file[i].url = res.data.fileUrl;
                file[i].fileName = res.data.fileName;
                delete file[i].status;
                delete file[i].message;
              },
              () => {
                file[i].status = "failed";
                file[i].message = "上传失败";
              }
            );
        },
        () => {
          file[i].status = "failed";
          file[i].message = "上传失败";
        }
      );
    }
  } else {
    file.status = "uploading";
    file.message = "上传中...";
    proxy.post("/fileInfo/getSing", { fileName: file.file.name }).then(
      (res) => {
        let forms = new FormData();
        forms.append("file", file.file);
        proxy
          .post("https://winfaster.obs.cn-south-1.myhuaweicloud.com", {
            ...res.data.uploadBody,
            file: forms.get("file"),
          })
          .then(
            () => {
              file.id = res.data.id;
              file.url = res.data.fileUrl;
              file.fileName = res.data.fileName;
              delete file.status;
              delete file.message;
            },
            () => {
              file.status = "failed";
              file.message = "上传失败";
            }
          );
      },
      () => {
        file.status = "failed";
        file.message = "上传失败";
      }
    );
  }
};
const testForm = ref(null); // 延迟使用，因为还没有返回跟挂载
watch(
  formData.value,
  (val) => {
    emit("update:modelValue", val);
  },
  {
    deep: true,
  }
);

watch(
  () => formData.value[btnConfigCopy.prop],
  (val) => {
    if (
      formOption.value.btnConfig !== undefined &&
      !formOption.value.btnConfig.isNeed &&
      val &&
      val.length > 0
    ) {
      formDataListShowLabel();
    }
  }
);
const changeCheckboxGroup = (form, label, data, fieldNames) => {
  let text = "";
  if (form[label] && form[label].length > 0) {
    form[label].map((item) => {
      let list = data.filter((itemData) => itemData[fieldNames.value] === item);
      if (list && list.length > 0) {
        if (text) {
          text = text + "," + list[0][fieldNames.text];
        } else {
          text = list[0][fieldNames.text];
        }
      }
    });
  }
  form[label + "Name"] = text;
};
const datePickerDateArr = ref([]);
const datePickerTimeArr = ref([]);
const datePickerTimeConfirm = (item, index) => {
  formData.value[item.prop] =
    datePickerDateArr.value.join("-") + " " + datePickerTimeArr.value.join(":");
  formConfig.value[index].showPicker = false;
};
defineExpose({
  formDataShowLabelOne,
  formDataListShowLabelOne,
  btnConfigCopy,
});
// onMounted(() => {});
</script>

<style lang="scss" scoped>
.btn-box {
  width: 100%;
  text-align: center;
  background: #f2f2f2;
  padding: 10px 0;
}
.row {
  color: #999999;
  background: #ecebeb;
  height: 32px;
  line-height: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
}
._title {
  font-size: 14px;
  font-weight: 700;
}
::v-deep {
  .multipleChoice {
    margin-bottom: 60px;
    .van-checkbox {
      justify-content: center;
      margin: 10px 40px;
    }
  }
  .van-form {
    margin-top: 0px !important;
  }
}
</style>
