<script>
import { save, show, index } from "@/api/system/baseForm";
import { getparameter } from "@/api/system/dictionary";
import { domMap } from "@/const/inputType";
import { addPropsMap } from "@/const/addProps";
export default {
  props: {
    formInfo: {
      type: Array,
      default: () => [],
    },
    tableName: String,
  },
  render(h) {
    return h(
      "el-dialog",
      {
        props: {
          title: "新增",
          visible: this.dialogVisible,
          width: "600px",
        },
        on: {
          "update:visible": (val) => {
            this.dialogVisible = val;
          },
        },
      },
      [
        h(
          "el-form",
          {
            ref: "elForm",
            props: {
              model: this.form,
              labelWidth: "80px",
              rules: this.rules,
              labelPosition: "right",
              size: "small",
            },
          },
          (() => {
            let dom = [];
            this.formInfo.forEach((i, index) => {
              if (i.list_show) {
                dom.push(
                  h(
                    "el-form-item",
                    {
                      ref: `elFormItem${i.field}`,
                      style: {
                        width: "100%",
                      },
                      props: {
                        label: i.name,
                        prop: i.field,
                        required:
                          i.validation instanceof Array
                            ? !!i.validation.find((i) => i === "required")
                            : false,
                      },
                    },
                    [
                      h(
                        domMap.get(i.edit_input),
                        {
                          ref: `elEdit_${i.field}`,
                          style: {
                            width: "100%",
                          },
                          props: {
                            ...addPropsMap.get(i.edit_input),
                            ...this.extraProps(i),
                            // fileList:this.file[i.field],
                            placeholder: i.help,
                            value: this.form[i.field],
                          },
                          attrs: {
                            placeholder: i.help || `请填写${i.name}`,
                          },
                          on: {
                            [this.getEventType(i.edit_input)]: (e) => {
                              if (i.field) {
                                this.form[i.field] = e;
                                this.form = Object.assign({}, this.form);
                              }
                            },
                          },
                          scopedSlots:
                            i.edit_input === "file" || i.edit_input === "files"
                              ? {
                                  file: (scope) => {
                                    console.log("scope",scope)
                                    let { file } = scope;
                                    return [
                                      h("div", {}, [
                                        h("i", {
                                          class: {
                                            "el-icon-circle-check":
                                              file.status === "success",
                                            "el-icon-loading":
                                              file.status === "uploading",
                                          },
                                          style: {
                                            "color": file.status === "success" ? "green" : ""
                                          }
                                        }),
                                        h(
                                          "a",
                                          {
                                            attrs: {
                                              href: file.url,
                                              download: file.name,
                                              target:'_blank'
                                            },
                                            class: {
                                              "uploaded-a":
                                                file.status === "success",
                                            }
                                          },
                                          file.name
                                        )
                                      ]),
                                      h("i", {
                                        class: "el-icon-close",
                                        on: {
                                          ["click"]: () =>
                                            this.fileRemoveHandler(
                                              file,
                                              i.field
                                            ),
                                        },
                                      }),
                                    ];
                                  },
                                }
                              : "",
                        },
                        this.optionsRender(h, i)
                      ),
                    ]
                  )
                );
              }
            });
            return dom;
          })()
        ),
        h("template", { slot: "footer" }, [
          h(
            "el-button",
            {
              on: {
                click: () => (this.dialogVisible = false),
              },
            },
            "取 消"
          ),
          h(
            "el-button",
            {
              props: {
                type: "warning",
                plain: true,
              },
              on: {
                click: () => this.init(),
              },
            },
            "重 置"
          ),
          h(
            "el-button",
            {
              props: {
                type: "primary",
              },
              on: {
                click: this.submit,
              },
            },
            "确 定"
          ),
        ]),
      ]
    );
  },
  data() {
    return {
      id: "",
      type: "add",
      dialogVisible: false,
      form: {},
      rules: {},
      file: {},
    };
  },
  methods: {
    fileRemoveHandler(file, field) {
      console.log(file,field,this.file)
      this.file[field] = this.file[field].filter((item) => item !== file);
      this.file = Object.assign({}, this.file);
    },
    //on事件类别获取
    getEventType(info) {
      if (info.type === "checkbox") {
        return "change";
      }
      return "input";
    },

    //渲染一些组件内部需要选项等
    optionsRender(h, info) {
      if (info.edit_input === "checkbox" || info.edit_input === "radio") {
        return info._paramters && info._paramters instanceof Array
          ? info._paramters.map((i) =>
              h("el-option", {
                props: {
                  label: i.name || i.no || i.value || i.id,
                  value: i.id,
                },
              })
            )
          : [];
      }
      if (info.edit_input === "file" || info.edit_input === "files") {
        return [
          h(
            "el-button",
            {
              slot: "trigger",
              props: {
                size: "small",
                type: "primary",
              },
            },
            "选取文件"
          ),
          h(
            "el-button",
            {
              style: {
                "margin-left": "10px",
              },
              props: {
                size: "small",
                type: "success",
              },
              on: {
                ["click"]: (e) => {
                  this.$refs[`elEdit_${info.field}`].submit();
                },
              },
            },
            "上传到服务器"
          ),
          h(
            "div",
            {
              class: "el-upload__tip",
              slot: "tip",
            },
            "文件不超过500kb"
            // info.field
          ),
        ];
      }
    },

    extraProps(info) {
      let props = {};
      if (info.edit_input === "file" || info.edit_input === "files") {
        // props.fileList = this.file[info.field];
        this.$set(props,'fileList',this.file[info.field])
        // console.log("123",this.file[info.field],props.fileList)
        props.beforeUpload = (file) => {
          if (file.size / 1000 > 500) {
            this.$message({
              type: "warning",
              message: "上传图片大小超过500kb！",
            });
            return false;
          }
        };

        props.onSuccess = (response, file, fileList) => {
          this.file[info.field] = fileList;
        };

        props.onRemove = (file, fileList) => {
          this.file[info.field] = fileList;
        };

        props.onError = (err,file,fileList) => {
          this.file[info.field] = fileList;
          this.$message({
            type: "warning",
            message: err
          })
        }
      }
      console.log("props",info.field,props)
      return props;
    },

    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() {
      if(this.type === "editor"){
        this.getDetail()
      }else{
        this.dialogVisible = true;
      }

      // 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.file = {}
      this.formInfo.forEach((i) => {
        if (i && i.edit_input === "file") {
          if(res[i.field+'_uploads_id_relation']){
            this.file[i.field] = [
              {
                name: res[i.field+'_uploads_id_relation']?.original_name,
                url: res[i.field+'_uploads_id_relation']?.url,
                response: res[i.field+'_uploads_id_relation'],
              },
            ];
          }
        }
        if (i && i.edit_input === "files") {
          if(res[i.field+'_upload_details']){
            this.file[i.field] = []
            for(var k of res[i.field+'_upload_details']){
              this.file[i.field].push({
                name: k?.original_name,
                url: k?.url,
                response: k,
              })
            }
          }
        }
      });
      this.dialogVisible = true
      this.$forceUpdate()
    },

    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) {
          console.log("this.formInfo",this.formInfo)
          console.log("file",this.file)
          this.formInfo.forEach((info) => {

            if (info.edit_input === "files") {
              console.log("info",info)
              this.form[info.field] = this.file[info.field]?.map(
                (i) => i?.response?.id
              );
            }
            if (info.edit_input === "file") {
              this.form[info.field] = this.file[info.field][0]?.response?.id;
            }
          });
          console.log("file",this.file)
          console.log(this.form);
          // return
          save(Object.assign(this.form, { table_name: this.tableName })).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] = [];
            }
          }
        });
      },
      //immediate: true,
    },
    dialogVisible(val) {
      if (val) {
        if (this.type === "editor") {
          // this.getDetail()
          // this.$nextTick(() => this.getDetail());
        }
      } else {
        this.file = {};
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["elForm"].clearValidate();
        delete this.form.id;
      }
    },
  },
};
</script>

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

.uploaded-a:hover {
  color: red;
  text-decoration: underline;
}
</style>
