<template>
  <div class="ydFormDetail">
    <a-form
      ref="formRef"
      :model="formInfo"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-row>
        <a-col
          v-for="item in formArr"
          :key="item.attr"
          :span="item.span || span"
        >
          <template v-if="!item.label && item.slot">
            <slot :name="item.attr"></slot>
          </template>
          <a-form-item v-else :label="item.label" :name="item.attr">
            <slot :name="item.attr" :data="item" v-if="item.slot"></slot>
            <template v-else>
              <a-input
                :disabled="item.disabled"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'input'"
                @change="(val) => propChange(val, item)"
              />
              <a-range-picker
                :disabled="item.disabled"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'timeRange'"
                valueFormat="YYYY-MM-DD"
                @change="(val) => propChange(val, item)"
              />
              <a-radio-group
                @change="(val) => propChange(val, item)"
                :disabled="item.disabled"
                v-if="item.type == 'radio'"
                name="radioGroup"
                v-model:value="formInfo[item.attr]"
              >
                <a-radio
                  v-for="item in item.options"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.name }}</a-radio
                >
              </a-radio-group>

              <a-date-picker
                :disabled="item.disabled"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'time'"
                valueFormat="YYYY-MM-DD"
                @change="(val) => propChange(val, item)"
              />
              <a-textarea
                :disabled="item.disabled"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'textarea'"
                @change="(val) => propChange(val, item)"
              />
              <a-input
                type="number"
                :disabled="item.disabled"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'number'"
                @change="(val) => propChange(val, item)"
              />
              <a-select
                :disabled="item.disabled"
                mode="multiple"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'select' && item.mode === 'multiple'"
                @change="(val) => propChange(val, item)"
              >
                <template v-if="item.options && item.options.length > 0">
                  <a-select-option
                    :title="oitem.name"
                    :value="oitem.value"
                    v-for="oitem in item.options"
                    :key="oitem.value"
                    >{{ oitem.name }}</a-select-option
                  >
                </template>
              </a-select>
              <a-select
                :disabled="item.disabled"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'select' && item.mode !== 'multiple'"
                @change="(val) => propChange(val, item)"
              >
                <template v-if="item.options && item.options.length > 0">
                  <a-select-option
                    :title="oitem.name"
                    :value="oitem.value"
                    v-for="oitem in item.options"
                    :key="oitem.value"
                    >{{ oitem.name }}</a-select-option
                  >
                </template>
              </a-select>
              <a-cascader
                :disabled="item.disabled"
                :fieldNames="item.props"
                :options="item.options"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'cascader'"
                @change="(val) => propChange(val, item)"
              />
              <a-cascader
                :disabled="item.disabled"
                :fieldNames="
                  item.props
                    ? item.props
                    : {
                        label: 'name',
                        value: 'code',
                      }
                "
                :options="adressOption"
                placeholder="请选择地址"
                v-model:value="formInfo[item.attr]"
                v-if="item.type == 'adress'"
                @change="(val) => propChange(val, item)"
              />
              <template v-if="item.type == 'image'">
                <UploadImg
                  :action="actionUrl"
                  :initChildMethod="initChildMethod"
                  :initList="formInfo[item.attr] || []"
                  :isDetail="item.disabled ? true : false"
                  :limit="item.limit || 5"
                  @imgChange="(val) => imgChange(val, item)"
                ></UploadImg>
              </template>
            </template>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted, onBeforeMount, ref } from "vue";
import { fetchAddress } from "./util";
import UploadImg from "../uploadImg/index";
import moment from "moment";
export default {
  name: "YdCreateForm",
  components: {
    UploadImg,
  },
  props: {
    formField: {
      type: Array,
      default: () => [],
    },
    actionUrl: {
      type: String,
      default: "",
    },
    initData: {
      type: Object,
      default: () => ({}),
    },
    rules: {
      type: Object,
      default: () => ({}),
    },
    span: {
      type: Number,
      default: 8,
    },
    labelCol: {
      type: Object,
      default: () => ({
        span: 4,
      }),
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    wrapperCol: {
      type: Object,
      default: () => ({
        span: 20,
      }),
    },
  },
  //https://cdn.youdi.net/F/a/5/f/b/9/bd9af00688bb67e9e7b6bde134f.png
  emits: ["dataChange"],
  setup(prop, context) {
    const formRef = ref();
    const state = reactive({
      formArr: prop.formField,
      formInfo: prop.initData,
      adressOption: [],
    });
    let childM = {};
    const initChildMethod = (method) => {
      childM = method;
    };
    const getAddressName = (code, list, options) => {
      list.forEach((it) => {
        if (code.includes(it.code)) {
          options.push(it.name);
          if (it.children && it.children.length > 0) {
            getAddressName(code, it.children, options);
          }
        }
      });
    };
    const checkField = () => {
      return new Promise((reslove) => {
        formRef.value
          .validate()
          .then(() => reslove(true))
          .catch((err) => reslove(false));
      });
    };
    const getForm = () => {
      return JSON.parse(JSON.stringify(state.formInfo));
    };
    const propChange = (val, item) => {
      let options = [];
      if (item.type == "select") {
        const temp = item.options.filter((it) => it.value === val);
        if (temp.length > 0) {
          options = temp;
        }
      }
      if (item.type === "adress") {
        getAddressName(state.formInfo[item.attr], state.adressOption, options);
      }
      context.emit("dataChange", {
        options,
        type: item.attr,
        data: JSON.parse(JSON.stringify(state.formInfo)),
      });
    };
    const setFormVal = (form) => {
      state.formInfo = form;
      state.formArr.forEach((it) => {
        if (it.type === "image") {
          childM.setImgList(form[it.attr] || []);
        }
      });
    };
    const imgChange = (val, item) => {
      let imageList = [];
      if (val.length > 0) {
        imageList = val.map((vitem) => {
          return vitem.url;
        });
      }
      state.formInfo[item.attr] = imageList;
      propChange(val, item);
    };
    const setVal = (attr, val) => {
      state.formInfo[attr] = val;
    };

    // watchEffect(() => {
    //   console.log(prop.initData);
    // });
    const setInitData = () => {
      state.formArr.forEach(async (it) => {
        if (prop.disabled) {
          it.disabled = true;
        }
        if (it.type === "adress") {
          fetchAddress().then((res) => {
            state.adressOption = res;
          });
        }
        if ((it.type === "select" || it.type === "radio") && it.fun) {
          it.options = await it.fun();
        }

        if (it.type === "time" && prop.initData[it.attr]) {
          state.formInfo[it.attr] = moment(prop.initData[it.attr]);
        }
        if (it.type === "timeRange" && prop.initData[it.attr]) {
          state.formInfo[it.attr] = [
            moment(prop.initData[it.attr][0]),
            moment(prop.initData[it.attr][1]),
          ];
        }
      });
    };

    onBeforeMount(() => {
      setInitData();
    });
    const resetValue = () => {
      for (const k in state.formInfo) {
        state.formInfo[k] = undefined;
      }
    };
    onMounted(() => {
      // setTimeout(() => {
      //   childM.setImgList(['https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c23da837e149482899fc28f3791c3df0~tplv-k3u1fbpfcp-zoom-mark-crop-v2:0:0:360:360.awebp'])
      // },3000)
    });
    return {
      imgChange,
      propChange,
      setVal,
      getForm,
      checkField,
      formRef,
      setFormVal,
      resetValue,
      initChildMethod,
      ...toRefs(state),
    };
  },
};
</script>

<style lang="scss">
.ydFormDetail {
  text-align: left;
  .ant-select,
  .ant-form-explain {
    text-align: left;
  }
  .ant-calendar-picker,
  .ant-select {
    width: 100%;
  }
  .ant-upload-list {
    display: inline;
  }
}
</style>
