<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="80%"
    style="height: 98%"
    :before-close="handleClose"
    top="5vh"
    lock-scroll
  >
    <div class="title" slot="title">
      <div class="divider"></div>
      <div class="label">{{ title }}</div>
    </div>
    <div class="dialog-content">
      <el-form :model="dialogForm" class="basic-info">
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="文物名称" :label-width="formLabelWidth">
              <el-input
                v-model="dialogForm.name"
                autocomplete="off"
                placeholder="请输入文物名称"
              ></el-input>
            </el-form-item>

            <el-form-item label="文物类别" :label-width="formLabelWidth">
              <el-select
                v-model="dialogForm.type"
                placeholder="请选择文物类别"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(value, key) in dicts.culturalRelicType"
                  :key="key"
                  :label="value"
                  :value="key"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文物级别" :label-width="formLabelWidth">
              <el-select
                v-model="dialogForm.level"
                placeholder="请选择文物级别"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(value, key) in dicts.culturalRelicLevel"
                  :key="key"
                  :label="value"
                  :value="key"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文物质地" :label-width="formLabelWidth">
              <el-cascader
                style="width: 100%"
                v-model="dialogForm.textureType"
                :options="culturalRelicTextureType"
                :props="culturalRelicTextureProps"
                placeholder="请选择文物质地"
                filterable
              >
              </el-cascader>
              <!-- <el-select
                v-model="dialogForm.textureType"
                placeholder="请选择文物质地"
                style="width: 100%"
              >
                <el-option
                  v-for="(value, key) in culturalRelicTexture"
                  :key="key"
                  :label="value"
                  :value="key"
                >
                </el-option>
              </el-select> -->
            </el-form-item>
            <el-form-item label="具体尺寸" :label-width="formLabelWidth">
              <el-input
                v-model="dialogForm.detailSize"
                autocomplete="off"
                placeholder="请输入具体尺寸"
              ></el-input>
            </el-form-item>
            <el-form-item label="文物年代" :label-width="formLabelWidth">
              <el-cascader
                style="width: 100%"
                v-model="dialogForm.years"
                :options="culturalRelicYears"
                :props="culturalRelicYearsProps"
                placeholder="请选择文物年代"
                filterable
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="文物数量" :label-width="formLabelWidth">
              <!-- <el-input
                v-model="dialogForm.num"
                autocomplete="off"
                placeholder="请输入文物数量"
              ></el-input> -->
              <el-input-number
                v-model="dialogForm.num"
                :min="1"
                :max="1000"
                label="请输入文物数量"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="馆藏单位" :label-width="formLabelWidth">
              <el-cascader
                style="width: 100%"
                v-model="dialogForm.deptId"
                :options="orgTreeData"
                :props="optionProps"
                placeholder="请选择馆藏单位"
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="馆藏介绍" :label-width="formLabelWidth">
              <!-- <el-input
                type="textarea"
                placeholder="请输入馆藏介绍"
                v-model="dialogForm.intro"
                maxlength="300"
                show-word-limit
              >
              </el-input> -->
              <quill-editor
                ref="myQuillEditor"
                v-model="dialogForm.intro"
                :options="editorOption"
                class=".editor"
              />
            </el-form-item>
            <el-form-item label="关联文献" :label-width="formLabelWidth">
              <el-select
                v-model="literatureValues"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索文献"
                :remote-method="searchLiterature"
                :loading="loading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in literatureList"
                  :key="item.literatureId"
                  :label="item.name"
                  :value="item.literatureId"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="来源方式" :label-width="formLabelWidth">
              <el-input
                v-model="dialogForm.sourceWay"
                autocomplete="off"
                placeholder="请输入来源方式"
              ></el-input>
            </el-form-item>

            <el-form-item label="是否上架" :label-width="formLabelWidth">
              <el-switch v-model="dialogForm.status"> </el-switch>
            </el-form-item>

            <el-form-item label="主题词" :label-width="formLabelWidth">
              <el-input
                v-model="dialogForm.themeWord"
                autocomplete="off"
                placeholder="请输入主题词"
              ></el-input>
            </el-form-item>

            <el-form-item label="3durl链接" :label-width="formLabelWidth">
              <el-input
                v-model="dialogForm.url3d"
                autocomplete="off"
                placeholder="请输入3durl链接"
              ></el-input>
            </el-form-item>

            <el-form-item label="备注" :label-width="formLabelWidth">
              <el-input
                type="textarea"
                placeholder="请输入备注"
                v-model="dialogForm.remark"
                maxlength="100"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="文物封面" :label-width="formLabelWidth">
              <ManualUploader
                :files="faceImage"
                :fileLimit="1"
                :fileSize="50"
                listType="picture-card"
                :fileType="['png', 'jpeg', 'jpg']"
                ref="faceImage"
              />
            </el-form-item>
            <el-form-item label="文物图片" :label-width="formLabelWidth">
              <ManualUploader
                :files="images"
                :fileLimit="20"
                :fileSize="50"
                listType="picture-card"
                :fileType="['png', 'jpeg', 'jpg']"
                ref="images"
              />
            </el-form-item>

            <el-form-item label="文物视频" :label-width="formLabelWidth">
              <ManualUploader
                :files="videos"
                :fileLimit="6"
                :fileSize="50"
                :fileType="['mp4', 'wav']"
                listType="text"
                ref="videos"
              />
            </el-form-item>
            <!-- <el-form-item label="讲解词文件" :label-width="formLabelWidth">
              <ManualUploader
                :files="sayExplain"
                :fileLimit="6"
                listType="text"
                :fileType="['doc', 'tet', 'docx']"
                ref="sayExplain"
              />
            </el-form-item> -->
            <el-form-item label="文物音频" :label-width="formLabelWidth">
              <ManualUploader
                :files="audios"
                :fileLimit="1"
                :fileSize="50"
                :fileType="['mp3']"
                listType="text"
                ref="audios"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="dialog-footer">
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定<i class="el-icon-s-promotion" style="margin-left: 5px"></i
        ></el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { getLiteratureList } from "@/api/literature";
import { addCulturalRelic, editCulturalRelic } from "@/api/culturalRelic";
import ManualUploader from "@/components/Uploader/ManualUploader.vue";
import { mapGetters } from "vuex";
import { uploadV1 } from "@/utils/file";
import { deleteFiles } from "@/api/file";
import { quillEditor } from "vue-quill-editor";
export default {
  name: "InfoEditDialog",
  components: {
    ManualUploader,
    quillEditor,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    ...mapGetters(["userInfo", "dicts"]),
    title() {
      if (this.dialogForm.crId) {
        return "修改信息";
      } else {
        return "新增发布";
      }
    },
  },
  watch: {
    visible: {
      handler: function (value) {
        this.dialogVisible = value;
      },
      immediate: true,
      deep: true,
    },
    form: {
      handler(value) {
        this.dialogForm = JSON.parse(JSON.stringify(value));
        // 回填状态
        this.dialogForm.status = Boolean(Number(this.dialogForm.status));
        // debugger
        // 回填媒体
        if (this.dialogForm.faceImageUrl) {
          this.faceImage = [
            {
              name: "",
              url: this.dialogForm.faceImageUrl,
              fileId: this.dialogForm.faceImage,
            },
          ];
        }

        this.images = this.dialogForm.imagesVo || [];
        this.videos = this.dialogForm.videosVo || [];
        this.audios = this.dialogForm.audiosVo || [];

        // 回填文献
        if (
          this.dialogForm.literatureVo &&
          this.dialogForm.literatureVo.length > 0
        ) {
          this.literatureList = this.dialogForm.literatureVo;
          this.literatureValues = [];
          this.dialogForm.literatureVo.forEach((lt) => {
            if (this.literatureValues) {
              this.literatureValues.push(lt.literatureId);
            }
          });
        }

        // 回填馆藏单位
        if (this.dialogForm.deptId) {
          this.dialogForm.deptId = [this.dialogForm.deptId];
        } else {
          // 设置默认值为当前用户的信息
          const { deptId, regionCode } = this.userInfo;
          this.dialogForm.deptId = deptId;
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    // 工具栏配置
    const toolbarOptions = [
      ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
      ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
      [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
      [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
      [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
      [{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
      [{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
      [{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
      [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
      [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
      [{ font: [] }], // 字体种类-----[{ font: [] }]
      [{ align: [] }], // 对齐方式-----[{ align: [] }]
      ["clean"], // 清除文本格式-----['clean']
      // ["image", "video"], // 链接、图片、视频-----['link', 'image', 'video']
    ];

    return {
      dialogForm: {
        ...this.form,
      },
      formLabelWidth: "100px",
      loading: false,
      literatureList: [],
      literatureValues: [], //文献绑定的数组，编辑回显时需要将后台传的值转成[id1,id2,]并赋值给它,新增时记得清空，提交时改成id 的str
      faceImage: [],
      images: [],
      videos: [],
      audios: [],
      culturalRelicTextureType: "",
      culturalRelicYears: "",
      culturalRelicYearsProps: {
        value: "value",
        label: "label",
        children: "children",
        checkStrictly: true, //单选选择任意一级选项
      },
      culturalRelicTextureProps: {
        value: "value",
        label: "label",
        children: "children",
        checkStrictly: true, //单选选择任意一级选项
      },
      dialogVisible: false,
      orgTreeData: [],
      optionProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true, //单选选择任意一级选项
      },
      //富文本编辑器配置
      editorOption: {
        //  富文本编辑器配置
        modules: {
          //工具栏定义的
          toolbar: toolbarOptions,
        },
        //主题
        theme: "snow",
        placeholder: "请输入馆藏介绍",
      },
    };
  },
  async created() {
    await this.$store.dispatch("dict/getDictList", [
      "culturalRelicLevel",
      "culturalRelicType",
    ]);
    let res = await this.$store.dispatch("dict/getDictTree", [
      "culturalRelicTextureType",
      "culturalRelicYears",
    ]);
    this.culturalRelicTextureType = res.culturalRelicTextureType;
    this.culturalRelicYears = res.culturalRelicYears;

    this.$store.dispatch("org/getMuseumTreeData", false).then((res) => {
      this.orgTreeData = res[0].children; //去掉根节点的文旅厅
    });
  },
  methods: {
    // 关联文献查询
    searchLiterature(queryString) {
      if (!queryString.trim()) {
        this.literatureList = [];
        return;
      }
      this.loading = true;
      const params = {
        name: queryString,
        page: "1",
        limit: "100",
      };
      setTimeout(async () => {
        this.loading = false;
        const res = await getLiteratureList(params);
        if (res.code == 0) {
          this.literatureList = res.data.records;
        } else {
          this.literatureList = [];
          this.$message.error(res.msg);
        }
      }, 500);
    },

    handlePreview({ type, file }) {
      console.log(type, file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 取消编辑
    cancelForm() {
      this.$emit("handleClose");
      this.reset();
    },
    async handleSubmit() {
      var that = this;
      let formData = new FormData();
      this.loading = true;
      // 已存在的文件的对象
      let successFilesObj = [];
      // 需要被删除的文件Id
      let deleteFileArr = [];
      // 添加布展本身的媒体文件至formData
      const mediaArr = ["faceImage", "images", "videos", "audios"];
      let newFiles = {};
      mediaArr.map((media) => {
        let files = [...this.$refs[media].getFiles()];
        let fileIds = [];
        files.map((f) => {
          switch (f.status) {
            case "ready":
              formData.append(media, f.raw);
              break;
            case "success":
              if (successFilesObj[media]) {
                successFilesObj[media].push(f);
              } else {
                successFilesObj[media] = [f];
              }
              fileIds.push(f.fileId);
              break;
          }
        });
        newFiles[media] = fileIds;
      });

      mediaArr.map((media) => {
        if (this.dialogForm[media]) {
          let oldFileIdArr = this.dialogForm[media].split(",");
          oldFileIdArr.map((oldId) => {
            if (newFiles[media].indexOf(oldId) == -1) {
              console.log(oldId + "已被删除");
              deleteFileArr.push(oldId);
            }
          });
        }
      });
      // 上传所有媒体文件
      let filesObj = {};

      var formDataArr = Array.from(formData.entries(), ([key, prop]) => ({
        [key]: {
          ContentLength: typeof prop === "string" ? prop.length : prop.size,
        },
      }));
      // formData有长度时再进行上传
      if (formDataArr.length > 0) {
        let upLoadRes = await uploadV1(formData);
        if (upLoadRes.code == 0) {
          upLoadRes.data.map((resFile) => {
            if (filesObj[resFile.fileKey]) {
              filesObj[resFile.fileKey].push(resFile.fileId);
            } else {
              filesObj[resFile.fileKey] = [resFile.fileId];
            }
          });
        }
      }
      // 1、回填之前先获取已存在的文件
      for (const key in successFilesObj) {
        // 如果文件id中含有已上传成功的某个key，如images，则将已上传成功的images推入文件id集合
        if (filesObj[key]) {
          successFilesObj[key].map((sf) => {
            filesObj[key].push(sf.fileId);
          });
        } else {
          let ids = [];
          successFilesObj[key].map((sf) => {
            ids.push(sf.fileId);
          });
          filesObj[key] = ids;
        }
      }
      // return;
      // 2、回填布展自带的媒体文件
      mediaArr.forEach((media) => {
        if (filesObj[media]) {
          this.dialogForm[media] = filesObj[media].join(",");
        } else {
          this.dialogForm[media] = "";
        }
      });
      if (!that.dialogForm.crId) {
        // const { deptId, regionCode } = this.userInfo;
        const params = { ...this.dialogForm };
        params.literature = this.literatureValues.join(",");
        params.status = this.dialogForm.status ? 1 : 0;
        // 处理年份
        params.years = params.years[params.years.length - 1];
        // 处理质地TODO:
        params.textureType = params.textureType[params.textureType.length - 1];
        let res = await addCulturalRelic(params);
        if (res.code == 0) {
          this.$message.success("提交成功！");
          this.loading = false;
          this.$emit("handleClose");
          this.$emit("refresh");
          this.reset();
        }
      } else {
        console.log("this.dialogForm", this.dialogForm);
        const params = { ...this.dialogForm };
        // debugger
        // return
        params.literature = this.literatureValues.join(",");
        params.status = this.dialogForm.status ? 1 : 0;
        // return;
        // 处理年份
        if (params.years instanceof Array) {
          params.years = params.years[params.years.length - 1];
        }
        // 处理质地
        if (params.textureType instanceof Array) {
          params.textureType =
            params.textureType[params.textureType.length - 1].trim();
        }

        // 处理馆藏单位
        if (params.deptId instanceof Array) {
          params.deptId = params.deptId[params.deptId.length - 1];
        }
        let res = await editCulturalRelic(params);
        let deleteRes = await deleteFiles(deleteFileArr);
        if (res.code == 0 && deleteRes.code == 0) {
          this.$message.success("修改成功！");
          this.loading = false;
          this.$emit("handleClose");
          this.$emit("refresh");
          this.reset();
        }
      }
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.$emit("handleClose");
          this.reset();
        })
        .catch((_) => {});
    },
    // 清空编辑组件中的所有值
    reset() {
      //父组件将清空form绑定的值
      // 清空文献
      this.literatureValues = [];
      this.images = [];
      this.videos = [];
      this.audios = [];
      this.faceImage = [];
    },

    refresh() {
      this.$emit("refresh");
    },

    // // 下载已上传的图片文件
    // handleDownload({ type, file }) {
    //   console.log("handleDownload", type, file);
    // },
  },
};
</script>

<style lang='scss' scoped>
.title {
  display: flex;
  margin-bottom: 16px;
  .divider {
    width: 8px;
    border-left: 4px solid #409eff;
    margin-right: 8px;
  }
  .label {
    font-weight: bold;
  }
}
.dialog-content {
  padding: 0 32px;
  display: flex;
  .basic-info {
    flex: 1;
    margin-right: 48px;
  }
  .relate {
    flex: 1;
  }
  .dialog-footer {
    display: flex;
    align-items: flex-end;
  }
}

.upload-box {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  line-height: 146px;
  vertical-align: top;
  text-align: center;
  margin: 0 8px 8px 0;
  i {
    font-size: 28px;
    color: #8c939d;
  }
}

.video-lists {
  display: flex;
}
</style>