
<script>
import { CreateDialog } from "@/utils/createDialog";
import { deepCopy } from "@/utils";
import { destroy, save, show , index } from "@/api/system/baseForm";
export default {
  props: {
    formInfo: {
      type: Array,
      default: () => [],
    },
    tableName: String,
  },
  data() {
    return {
      columns: 1,
      id: "",
      type: "add",
      dialogVisible: false,
      form: {},
      originalForm: {},
      rules: {},
      file: {},

      pickedLinkField: {
        linkType: "",
        linkTableName: "",
        field: "",
        originalRows: [],
      },
      pumps: [],
    }
  },
  methods: {
    async getPumps () {
      this.pumps = (await index({ table_name: 'equipments' })).data
    },

    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this.form[key] = value;
      }
      if (!key) {
        this.init();
      }
    },
    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", "show"];
      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.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] = []);
        }

        this.form = Object.assign({}, this.form);
        this.originalForm = deepCopy(res);
      });
    },

    submit () {
      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 promiseAll = [];

          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 (
              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._relations.link_with_name]?.map(i => {
                  delete i.id;
                  return i;
                })
              }

              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
                  : "";
              }
            }
            if (!copyForm[info._relations?.link_with_name]) {
              delete copyForm[info._relations?.link_with_name];
            }
          });

          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: {
    title () {
      if (this.type === 'add') return '新增'
      if (this.type === 'editor') return '编辑'
      if (this.type === 'show') return '查看'
    }
  },
  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] = [];
            }
            if (i._relations) {
              this.form[i._relations?.link_with_name] = [];
            }
          }
        });

        this.columns = newVal.length > 11 ? '2' : '1'
      },
      //immediate: true,
    },
    dialogVisible(val) {
      if (val) {
        document.documentElement.style.setProperty(
          "--column-num",
          this.columns
        );
        if (this.type === "editor" || this.type === "show") {
          this.$nextTick(() => this.getDetail());
        }
      } else {
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["elForm"].clearValidate();
        delete this.form.id;
        for (let key in this.file) {
          this.file[key] = [];
        }
      }
    },
  },
  created() {
    this.getPumps();
  },
  render(h) {
    const dialog = new CreateDialog(this,[
      {
        key: 'equipment_id',
        label: '泵闸枢纽',
        render: h('el-transfer',{
          props: {
            value: this.form['equipment_id'],
            filterable: true,
            data: this.pumps,
            titles: ['源列表','目标列表'],
            props: {
              key: 'id',
              label: 'name'
            },
            'right-default-checked': this.form['equipment_id']
          },
          on: {
            'change':e => {
              this.form['equipment_id'] = e;
              this.form = Object.assign({},this.form);
            }
          }
        })
      }
    ])
    return dialog.render()
  },
}
</script>

<style scoped lang="scss">
</style>
