<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="80%"
    style="height: 98%"
    :before-close="handleClose"
    top="2vh"
    lock-scroll
  >
    <div class="title" slot="title">
      <div class="divider"></div>
      <div class="label">{{ title }}</div>
    </div>
    <div class="dialog-content" v-if="dialogVisible">
      <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.title"
                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%"
              >
                <el-option
                  v-for="(value, key) in dicts.display_type"
                  :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.displayCharacter"
                placeholder="请选择展览性质"
                style="width: 100%"
              >
                <el-option
                  v-for="(value, key) in dicts.display_character"
                  :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.themeType"
                placeholder="请选择模板主题"
                style="width: 100%"
              >
                <el-option
                  v-for="item in themeTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </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-form-item label="展览介绍" :label-width="formLabelWidth">
              <el-input
                type="textarea"
                placeholder="请输入展览介绍"
                v-model="dialogForm.intro"
                maxlength="1000"
                show-word-limit
                rows="6"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="展览封面" :label-width="formLabelWidth">
              <ManualUploader
                :fileLimit="1"
                listType="picture-card"
                :fileType="['png', 'jpeg', 'jpg']"
                :files="faceImage"
                ref="faceImage"
              />
            </el-form-item>
            <el-form-item label="展览视频" :label-width="formLabelWidth">
              <ManualUploader
                :files="videos"
                :fileLimit="6"
                :fileSize="50"
                :fileType="['mp4', 'wav']"
                listType="picture"
                ref="videos"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关键词" :label-width="formLabelWidth">
              <el-input
                v-model="dialogForm.keyword"
                autocomplete="off"
                placeholder="请输入关键词"
              ></el-input>
            </el-form-item>

            <el-form-item label="展览文物" :label-width="formLabelWidth">
              <el-select
                v-model="crIds"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索文物"
                :remote-method="searchCR"
                :loading="loading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in crList"
                  :key="item.crId"
                  :label="item.name"
                  :value="item.crId"
                >
                </el-option>
              </el-select>
            </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%"
                ref="literatureSelect"
              >
                <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-switch v-model="dialogForm.status"> </el-switch>
            </el-form-item>
            <el-form-item label="展览图片" :label-width="formLabelWidth">
              <ManualUploader
                :files="images"
                :fileLimit="20"
                :fileSize="50"
                listType="picture-card"
                :fileType="['png', 'jpeg', 'jpg']"
                @handleFileReady="handleImagesReady"
                ref="images"
              />
            </el-form-item>
            <el-form-item label="展览音频" :label-width="formLabelWidth">
              <ManualUploader
                :files="audios"
                :fileLimit="1"
                :fileSize="50"
                :fileType="['mp3']"
                listType="picture"
                @handleFileReady="handleAudiosReady"
                ref="audios"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="展览单元" :label-width="formLabelWidth">
            <ExhibitionUnit
              :exhibitionUnits="dialogForm.exhibitionUnits"
              ref="exhibitionUnits"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="dialog-footer">
      <el-button @click="cancelForm">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :disabled="loading"
        >确定<i class="el-icon-right" style="margin-left: 5px"></i
      ></el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addDisplay, editDisplay } from "@/api/display";
import { mapGetters } from "vuex";
import ManualUploader from "@/components/Uploader/ManualUploader.vue";
import ExhibitionUnit from "./ExhibitionUnit.vue";
import { upload, uploadV1 } from "@/utils/file";
import { themeTypeOptions } from "../contants";
import { deleteFiles } from "@/api/file";
export default {
  name: "InfoEditDialog",
  components: {
    ManualUploader,
    ExhibitionUnit,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    ...mapGetters(["userInfo", "dicts"]),
    dialogVisible: {
      get: function () {
        return this.visible;
      },
      set: function () {},
    },
    title() {
      if (this.dialogForm.exhibitionId) {
        return "修改信息";
      } else {
        return "新增发布";
      }
    },
    themeTypeOptions() {
      return themeTypeOptions;
    },
  },
  watch: {
    form: {
      handler: function (value) {
        if (value) {
          this.dialogForm = JSON.parse(JSON.stringify(value));
          if (
            this.dialogForm.exhibitionUnits &&
            this.dialogForm.exhibitionUnits.length > 0
          ) {
            loopUnit(this.dialogForm.exhibitionUnits);
            function loopUnit(arr) {
              arr.forEach((unit) => {
                if (unit.length > 0) {
                  // this.$set(unit, "showMediaUploader", true); //设置展示图片单元的为展开
                  // 如果有文物，回填文物
                  if (unit.culturalRelics && uni.culturalRelics.length > 0) {
                    this.$set(unit, "crIds", unit.culturalRelics);
                  }
                  if (unit.children) {
                    loopUnit(unit.children);
                  }
                }
              });
            }
          }
          // 回填媒体资源
          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 || [];

          // 编辑
          // 回填状态
          this.dialogForm.status = Boolean(Number(this.dialogForm.status));
          // 回填文献
          this.literatureValues = [];

          if (
            this.dialogForm.literatureVo &&
            this.dialogForm.literatureVo.length > 0
          ) {
            this.literatureList = this.dialogForm.literatureVo;
            this.dialogForm.literatureVo.forEach((lt) => {
              if (this.literatureValues) {
                this.literatureValues.push(lt.literatureId);
              }
            });
          }
          // 回填文物
          this.crIds = [];
          if (
            this.dialogForm.culturalRelicVo &&
            this.dialogForm.culturalRelicVo.length > 0
          ) {
            this.crList = this.dialogForm.culturalRelicVo;
            this.dialogForm.culturalRelicVo.forEach((cr) => {
              if (this.crIds) {
                this.crIds.push(cr.crId);
              }
            });
          }
        }
      },
      immediate: true,
    },
  },
  async created() {
    await this.$store.dispatch("dict/getDictList", [
      "display_type",
      "display_character",
    ]);
  },
  data() {
    return {
      dialogForm: {
        ...this.form,
      },
      formLabelWidth: "100px",
      loading: false,
      upLoadAddress: process.env.VUE_APP_BASE_API + "/sysFiles/upload",
      typeOptions: [{ label: "展览类型", value: 1 }], //后期从vuex中取
      disabled: false,
      exhibitionUnits: [],
      literatureList: [], //文献列表
      literatureValues: [], //选中的文献列表
      crList: [], //文物列表
      crIds: [], //选中的文物列表
      // showUnit: false,
      faceImage: [],
      images: [],
      videos: [],
      audios: [],
    };
  },
  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 this.$store.dispatch("dict/getLtList", {
          hasPer: false,
          params,
        });
        if (res.code == 0) {
          this.literatureList = res.data.records;
        } else {
          this.literatureList = [];
          this.$message.error(res.msg);
        }
      }, 500);
    },
    // 关联文物查询
    searchCR(queryString) {
      let that = this;
      if (!queryString.trim()) {
        that.crList = [];
        return;
      }
      that.loading = true;
      const params = {
        name: queryString,
        page: "1",
        limit: "100",
      };

      setTimeout(async () => {
        // debugger
        that.loading = false;
        const res = await that.$store.dispatch("dict/getCrList", {
          params,
          isReload: true,
        });
        if (res.code == 0) {
          that.crList = res.data.records;
        } else {
          that.crList = [];
          that.$message.error(res.msg);
        }
      }, 500);
    },
    handlePreview({ type, file }) {
      console.log(type, file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 取消编辑
    cancelForm() {
      this.reload();
    },

    async handleSubmit() {
      this.loading = true;
      var that = this;
      let formData = new FormData();
      // 已存在的文件的对象
      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);
            }
          });
        }
      });
      // return
      let unitIds = [];
      let unitData = [...this.$refs["exhibitionUnits"].getUnitData()];
      // debugger
      // return
      addUnitIds(unitData); //添加unit的id作为上传文件的key
      function addUnitIds(arr) {
        if (arr.length > 0) {
          arr.map((item) => {
            unitIds.push(item.euId);
            if (item.children) {
              addUnitIds(item.children);
            }
          });
        }
      }
      unitIds.map(async (euId) => {
        let exhibitionUnitsDom = this.$refs.exhibitionUnits;
        let imageFiles = [];
        let videoFiles = [];
        if (exhibitionUnitsDom.$refs[`unit-images-${euId}`]) {
          imageFiles = [
            ...exhibitionUnitsDom.$refs[`unit-images-${euId}`].getFiles(),
          ];
        }

        if (exhibitionUnitsDom.$refs[`unit-videos-${euId}`]) {
          videoFiles = [
            ...exhibitionUnitsDom.$refs[`unit-videos-${euId}`].getFiles(),
          ];
        }

        if (imageFiles.length > 0) {
          imageFiles.forEach((imgFile) => {
            if (imgFile.status === "ready") {
              formData.append(`unit-images-${euId}`, imgFile.raw);
            } else {
              //
              if (successFilesObj[`unit-images-${euId}`]) {
                successFilesObj[`unit-images-${euId}`].push(imgFile);
              } else {
                successFilesObj[`unit-images-${euId}`] = [imgFile];
              }
            }
          });
        }
        if (videoFiles.length > 0) {
          videoFiles.forEach((videoFile) => {
            if (videoFile.status === "ready") {
              formData.append(`unit-videos-${euId}`, videoFile.raw);
            } else {
              if (successFilesObj[`unit-videos-${euId}`]) {
                successFilesObj[`unit-videos-${euId}`].push(videoFiles);
              } else {
                successFilesObj[`unit-videos-${euId}`] = [videoFiles];
              }
            }
          });
        }
      });
      // 上传所有媒体文件
      let filesObj = {};

      var formDataArr = Array.from(formData.entries(), ([key, prop]) => ({
        [key]: {
          ContentLength: typeof prop === "string" ? prop.length : prop.size,
        },
      }));
      // console.log("formDataArr,length", formDataArr.length);
      // 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);
          });
          // filesObj[key].push(successFilesObj[key].fileId);
        } else {
          let ids = [];
          successFilesObj[key].map((sf) => {
            ids.push(sf.fileId);
          });
          filesObj[key] = ids;
        }
      }
      // 2、回填布展自带的媒体文件
      mediaArr.forEach((media) => {
        if (filesObj[media]) {
          this.dialogForm[media] = filesObj[media].join(",");
        } else {
          this.dialogForm[media] = "";
        }
      });
      // 3、回填布展单元媒体文件,修改关联文物为Str，和显示隐藏控制器
      backFillUnit(unitData);
      function backFillUnit(arr) {
        if (arr.length > 0) {
          arr.map((unit) => {
            // 如果进行了文件上传
            if (Object.keys(filesObj).length > 0) {
              for (const key in filesObj) {
                let type = key.split("-")[1];
                let euId = key.split("-")[2];
                if (euId == unit.euId) {
                  switch (type) {
                    case "images":
                      unit.images = filesObj[key].join(",");
                      console.log("unit", unit);
                      break;
                    case "videos":
                      unit.videos = filesObj[key].join(",");
                      break;
                  }
                }
              }
            }
            // 不管是否进行文件上传，都需要修改文物为Str和显示隐藏控制器,去除euid
            // 编辑时关联文物id为字符串，新增时为数组，需要重新组成
            // 新增时
            if (!that.dialogForm.exhibitionId) {
              let crIdArr = unit.crIds;
              unit.crIds = crIdArr.join(",");
              var deleteArr = ["euId", "showMediaUploader"];
              deleteArr.forEach((i) => {
                if (unit[i]) {
                  delete unit[i];
                }
              });
            } else {
              // 编辑时
              // console.log("修改时---unit.crIds ", unit.crIds);
              let crIdArr = unit.crIds;
              unit.crIds = crIdArr.join(",");
              var deleteArr = ["euId", "showMediaUploader"];
              deleteArr.forEach((i) => {
                if (unit[i]) {
                  delete unit[i];
                }
              });
            }
            if (unit.children) {
              backFillUnit(unit.children);
            }
          });
        }
      }

      if (!that.dialogForm.exhibitionId) {
        const { deptId, regionCode } = this.userInfo;
        const params = {
          ...this.dialogForm,
          exhibitionUnits: unitData,
          deptId,
          regionCode,
        };
        params.literature = this.literatureValues.join(",");
        params.status = this.dialogForm.status ? 1 : 0;
        params.crIds = this.crIds.join(",");
        params.displayCharacter = 1; //传布展
        let res = await addDisplay(params);

        if (res.code == 0) {
          this.$message.success("提交成功！");
          this.loading = false;
          this.$emit("refresh");
          this.reload();
        }
      } else {
        const {
          exhibitionId,
          title,
          type,
          keyword,
          intro,
          themeType,
          remark,
          faceImage,
          faceImageUrl,
          images,
          audios,
          videos,
          regionCode,
          deptId,
          displayCharacter,
        } = this.dialogForm;

        let literature = this.literatureValues.join(",");
        let crIds = this.crIds.join(",");
        let status = this.dialogForm.status ? 1 : 0;
        // return;
        const params = {
          exhibitionId,
          title,
          type,
          keyword,
          intro,
          themeType,
          remark,
          audios,
          deptId,
          faceImage,
          faceImageUrl,
          images,
          regionCode,
          videos,
          status,
          literature,
          crIds,
          displayCharacter,
          exhibitionUnits: unitData,
        };
        console.log("修改参数-----------", params);
        // return;
        let res = await editDisplay(params);
        let deleteRes = await deleteFiles(deleteFileArr);
        if (res.code == 0 && deleteRes.code == 0) {
          this.$message.success("提交成功！");
          this.loading = false;
          this.$emit("refresh");
          this.reload();
        }
      }

      // }
    },
    // 清空编辑组件中的所有值
    reload() {
      //父组件将清空form绑定的值
      this.$emit("handleClose");
      // 清空文献
      this.literatureValues = [];
      // 清空文物
      this.crIds = [];
      // this.literatureNames = [];
      // 清空布展单元
      this.exhibitionUnits = [
        {
          euId: 1, //后期去掉
          // unit: "", //单元名称,如前言、第一单元，暂时忽略
          title: "", //单元标题，类似主题名称
          intro: "", //单元介绍
          images: "", //图片id集合
          videos: "", //视频id集合
          crIds: [], //关联文物集合
          showMediaUploader: false,
          // showImageUploader: false, //后期去掉
          // showVideoUploader: false, //后期去掉
        },
      ];

      this.images = [];
      this.videos = [];
      this.audios = [];
      this.faceImage = [];
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.reload();
        })
        .catch((_) => {});
    },
    // 处理将文件的url拼接成字符串
    handleJoinArrToStr(file) {
      var str = "";
      var urlArr = file.map((item) => {
        return item.url;
      });
      str = urlArr.join(",");
      return str;
    },
    // 封面上传
    handleFaceImageReady(file) {
      var str = this.handleJoinArrToStr(file);
      this.dialogForm.faceImage = str;
    },

    // 展览图片上传
    handleImagesReady(file) {
      var str = this.handleJoinArrToStr(file);
      this.dialogForm.images = str;
    },

    // 展览图片上传
    handleVideosReady(file) {
      var str = this.handleJoinArrToStr(file);
      this.dialogForm.videos = str;
    },

    // 展览图片上传
    handleAudiosReady(file) {
      var str = this.handleJoinArrToStr(file);
      this.dialogForm.auidos = str;
    },

    refresh() {
      this.$emit("refresh");
    },
  },
};
</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;
  justify-content: flex-end;
}

.video-lists {
  display: flex;
}

//展览单元
</style>