<script>
import venuePick from "./venuePick.vue";
import { save, show, index, destroy } from "@/api/system/baseForm";
import { deepCopy } from "@/utils";
import { CreateDialog } from "@/utils/createDialog"
export default {
  components: {
    venuePick,
  },
  props: {
    formInfo: {
      type: Array,
      default: () => [],
    },
    tableName: String,
  },
  render(h) {
    let addOrder = new CreateDialog(this,[
      {
        key: 'venue_detail_id',
        label: '场馆选择',
        render:() => {
          return h(
            "el-input",
            {
              props: {
                readonly: true,
                value: this.pickVenueDetail.name || this.originalForm?.venue_detail_id_venue_details_id_relation?.name || ''
              },
              on: {
                ['focus']:e => {
                  this.$refs['venuePick'].show();
                }
              },
            }
          )
        }
      }
    ])

    return h('div',[
      addOrder.render(),
      h('venuePick',{
        ref: 'venuePick',
        on: {
          venueDetailPick:node => {
            console.log(node)
            this.pickVenueDetail = node;
            this.form.venue_detail_id = node.id;
          }
        }
      })
    ])
  },
  data() {
    return {
      columns: 1,
      id: "",
      type: "add",
      dialogVisible: false,
      form: {},
      originalForm: {},
      rules: {},
      file: {},

      pickedLinkField: {
        linkType: "",
        linkTableName: "",
        field: "",
        originalRows: [],
      },
      pickVenueDetail: {}
    };
  },
  methods: {
    fileRemoveHandler(file, field) {
      this.file[field] = this.file[field].filter((item) => item !== file);
      this.file = Object.assign({}, this.file);
    },
    //on事件类别获取
    getEventType(info) {
      if (info === "checkbox") {
        return "change";
      }
      return "input";
    },

    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["elForm"].clearValidate();
    },
    show() {
      this.dialogVisible = true;
    },
    hidden() {
      this.dialogVisible = false;
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },

    async getDetail() {
      const res = await show({ id: this.id, table_name: this.tableName });
      this.$integrateData(this.form, res);
      this.form = Object.assign({}, this.form);

      this.formInfo.forEach((i) => {
        if (i && (i.edit_input === "file" || i.edit_input === "files")) {
          res[i._relations.link_with_name]
            ? (this.file[i.field] =
              res[i._relations.link_with_name] instanceof Array
                ? res[i._relations.link_with_name].map((i) => {
                  return {
                    name: i?.original_name,
                    url: i?.url,
                    response: i,
                  };
                })
                : [
                  {
                    name: res[i._relations.link_with_name]?.original_name,
                    url: res[i._relations.link_with_name]?.url,
                    response: res[i._relations.link_with_name],
                  },
                ])
            : (this.file[i.field] = []);

          return;
        }
        if (
          i &&
          (i._relations?.link_relation === "newHasMany" ||
            i._relations?.link_relation === "hasMany")
        ) {
          this.form[i.field] = res[i._relations.link_with_name].map(
            (j) => j[i._relations.custom_form_field]
          );
        }
      });

      this.originalForm = deepCopy(res);
    },

    submit() {
      let promiseAll = [];
      if (this.type === "add") {
        if (this.form.hasOwnProperty("id")) {
          delete this.form.id;
        }
      }
      if (this.type === "editor") {
        Object.defineProperty(this.form, "id", {
          value: this.id,
          enumerable: true,
          configurable: true,
          writable: true,
        });
      }
      this.$refs["elForm"].validate((validate) => {
        if (validate) {
          let copyForm = deepCopy(this.form);
          this.formInfo.forEach((info) => {
            if (
              info._relations?.link_relation === "newHasMany" ||
              info._relations?.link_relation === "hasMany"
            ) {
              if (this.originalForm[info._relations.link_with_name]) {
                this.originalForm[info._relations.link_with_name].map((i) => {
                  promiseAll.push(
                    destroy({
                      id: i.id,
                      table_name: info._relations.link_table_name,
                    })
                  );
                });
              }
            }

            // if (copyForm[info._relations?.link_with_name]?.length > 0) {
            //   delete copyForm[info.field];
            // }
            if (
              info._relations?.link_relation === "newHasMany" ||
              info._relations?.link_relation === "hasMany"
            ) {
              if (info.edit_input === "files") {
                copyForm[info._relations.link_with_name] = this.file[
                  info.field
                  ]?.map((i) => {
                  return {
                    upload_id: i?.response?.id,
                    original_name: i?.response?.original_name,
                  };
                });
              } else {
                copyForm[info._relations.link_with_name] =
                  copyForm[info.field] instanceof Array
                    ? copyForm[info.field]?.map((i) => {
                      return {
                        [info._relations.custom_form_field]: i,
                        //...copyRelation,
                      };
                    })
                    : "";
              }

              delete copyForm[info.field];
            }
            if (
              info._relations?.link_relation === "newHasOne" ||
              info._relations?.link_relation === "hasOne"
            ) {
              if (info.edit_input === "file") {
                copyForm[info.field] = this.file[info.field]
                  ? this.file[info.field][0]?.response?.id
                  : "";
              } else {
                // let copyRelation = deepCopy(
                //   info._params.find(
                //     (param) => param.id == this.form[info.field]
                //   )
                // );
                // if (copyRelation) {
                //   delete copyRelation.id;
                //   copyForm[info._relations.link_with_name] = [
                //     {
                //       id: this.form[info._relations?.link_with_name]?.id,
                //       [info.field === "shenhebumen"
                //         ? "dept_id"
                //         : info._relations.foreign_key]: this.form[info.field],
                //       ...copyRelation,
                //     },
                //   ];
                // }
              }

              //delete copyForm[info.field];
            }
            if (!copyForm[info._relations?.link_with_name]) {
              delete copyForm[info._relations?.link_with_name];
            }
            // if (info._relations?.link_with_name) {
            //   if (info.edit_input === "files" || info.edit_input === "file") {
            //     this.form[info._relations.link_with_name] = this.file[info.field].map(i => i?.response);
            //     delete this.form[info.field]
            //   } else {
            //     this.form[info._relations.link_with_name] = this.form[info.field] instanceof Array ? this.form[info.field].map(i => {
            //       return info._params.find(param => i === param[info._relations.foreign_key])
            //     }) : [info._params.find(param => this.form[info.field] === param[info._relations.foreign_key])]
            //     delete this.form[info.field]
            //   }
            // }
          });

          promiseAll.push(
            save(Object.assign(copyForm, { table_name: this.tableName }))
          );
          Promise.all(promiseAll).then((res) => {
            this.$Message.success({
              content: `${this.type === "add" ? "新增" : "编辑"}成功`,
            });
            this.$emit("refresh");
            this.hidden();
          });
        }
      });
    },
  },
  computed: {},
  watch: {
    formInfo: {
      handler: function (newVal) {
        this.form = {};
        this.rules = {};
        this.file = {};
        newVal.forEach((i) => {
          if (i.field) {
            this.form[i.field] = "";
            if (
              i.validation instanceof Array &&
              i.validation.length > 0 &&
              !!i.validation.find((i) => i === "required")
            ) {
              this.rules[i.field] = [
                { required: true, message: `请填写${i.name}` },
              ];
            }
            if (i.edit_input === "files") {
              this.form[i.field] = [];
            }
            if (i.edit_input === "files" || i.edit_input === "file") {
              this.file[i.field] = [];
            }
            if (i.edit_input === "checkbox") {
              this.form[i.field] = [];
            }
          }
        });

        document.documentElement.style.setProperty('--column-num', Math.round(newVal.length / 8).toString())
      },
      //immediate: true,
    },
    dialogVisible(val) {
      if (val) {
        if (this.type === "editor") {
          this.$nextTick(() => this.getDetail());
        }
      } else {
        this.pickVenueDetail = {};
        this.originalForm = {};
        this.file = {};
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["elForm"].clearValidate();
        delete this.form.id;
      }
    },
  },
};
</script>

<style scoped lang="scss">
:root {
  --column-num: 2;
}
.uploaded-a {
  color: red;
  text-decoration: none;
  transition: all 0.2s;
}

.uploaded-a:hover {
  color: red;
  text-decoration: underline;
}
.form-body {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(var(--column-num), 1fr);
}
</style>
