<template>
  <div>
    <Modal v-model="isShow" title="附件" footer-hide :width="64">
      <Button type="primary" shape="circle" icon="ios-add" @click="add"
        >新增</Button
      >

      <Table
        style="margin-top: 10px"
        :height="320"
        :data="detail.attachment"
        :columns="columns"
      >
      </Table>
    </Modal>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { show, save } from "@/api/propertyPlan";
export default {
  props: {},
  data() {
    return {
      fileList: [],
      action: process.env.VUE_APP_UPLOAD,
      key: 1,
      isShowModal: false,
      isShow: false,
      id: "",
      type: "",

      detail: {},
      columns: [
        {
          key: "file",
          title: "文件",
          width: 200,
          render: (h, { row }) => {
            return h(
              "a",
              {
                attrs: { download: row.file.original_name, href: row.file.url },
              },
              row.file.original_name
            );
          },
        },
        {
          key: "content",
          title: "内容",
          minWidth: 220,
          align: "left",
        },
        {
          key: "date",
          title: "日期",
          width: 160,
        },
        {
          key: "operate",
          title: "操作",
          width: 100,
          align: "left",
          render: (h, { row }) => {
            return h("Poptip", {
              props: {
                transfer: true,
                confirm: true,
                title: "确认要删除吗",
              },
              scopedSlots: {
                default: () => {
                  return h(
                    "Button",
                    {
                      props: {
                        ghost: true,
                        size: "small",
                        type: "error",
                      },
                    },
                    "删除"
                  );
                },
              },
              on: {
                ["on-ok"]: (_) => {
                  let attachments = this.detail.attachment
                    .filter((i) => i.id !== row.id)
                    .map((i) => {
                      return {
                        file: i.file.id,
                        date: i.date,
                        content: i.content,
                      };
                    });
                  save({
                    ...this.detail,
                    attachment_list: attachments,
                    content_list: this.detail.content.map((i) => {
                      return {
                        title: i.title,
                        content: i.content,
                        date: i.date,
                      };
                    }),
                  }).then((_) => {
                    this.$message({
                      type: "success",
                      message: "删除成功",
                    });
                    this.getDetail();
                  });
                },
              },
            });
          },
        },
      ],
    };
  },
  methods: {
    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["dialog"].clearValidate();
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },
    getId() {
      return this.id;
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    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();
      }
    },

    async getDetail() {
      const res = await show({ id: this.getId() });
      this.detail = res;
      console.log(res);
    },

    async add() {
      let form = {
        date: this.$moment(new Date()).format("YYYY-MM-DD"),
        file: "",
        content: "",
      };
      const h = this.$createElement;
      this.$msgbox({
        title: "新增附件",
        message: h(
          "el-form",
          { key: ++this.key, props: { model: form, "label-width": "80px" } },
          [
            h("el-form-item", {
              props: { label: "文件" },
              scopedSlots: {
                default: () =>
                  h(
                    "el-upload",
                    {
                      props: {
                        action: this.action,
                        "file-list": this.fileList,
                        limit: 1,
                        headers: {
                          Authorization: "Bearer " + getToken(),
                        },
                        accept:
                          ".rar,.zip,.doc,.docx,.pdf,.jpg,.png,.gif,.mp4,.xls,.xlsx",
                        "on-success": (response, file, fileList) => {
                          this.fileList = fileList;
                          form.file = response?.id;
                        },
                        "before-upload": (file) => {
                          if (file.size / 1000 > 5 * 1024) {
                            this.$message({
                              type: "warning",
                              message: "上传文件大小超过5M！",
                            });
                            return false;
                          }
                        },
                        "on-remove": (file, fileList) => {
                          this.fileList = fileList;
                        },
                      },
                    },
                    [
                      h(
                        "el-button",
                        {
                          props: {
                            type: "primary",
                            size: "small",
                          },
                          slot: "trigger",
                        },
                        "选取文件"
                      ),
                      h(
                        "div",
                        {
                          class: "el-upload__tip",
                          slot: "tip",
                        },
                        "只能上传jpg/png文件，且不超过5Mb"
                      ),
                    ]
                  ),
              },
            }),
            h("el-form-item", {
              props: { label: "内容" },
              scopedSlots: {
                default: () =>
                  h("textarea", {
                    class: "el-textarea__inner",
                    props: { value: form.content },
                    on: {
                      ["input"]: (e) => {
                        form.content = e.target.value;
                      },
                    },
                  }),
              },
            }),
          ]
        ),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "保存中...";
            this.detail.attachment_list = [
              ...this.detail.attachment?.map((i) => {
                return { file: i.file.id, content: i.content, date: i.date };
              }),
              form,
            ];
            save(this.detail)
              .then((_) => {
                this.$message({
                  type: "success",
                  message: "保存成功",
                });
                instance.confirmButtonLoading = false;
                done();
                this.getDetail();
                this.fileList = [];
              })
              .catch((_) => {
                instance.confirmButtonLoading = false;
              });
          } else {
            done();
          }
        },
      });
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        this.getDetail();
      } else {
        this.id = "";
        this.fileList = [];
      }
    },
  },
  created() {},
};
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}
</style>
