<template>
  <el-dialog
    v-loading="submitLoading"
    element-loading-background="rgba(0, 0, 0, 0.5)"
    :element-loading-text="loadingText"
    :visible.sync="visible"
    width="80%"
    :before-close="handleClose"
    top="2vh"
    lock-scroll
  >
    <div class="title" slot="title">
      <div class="divider"></div>
      <div class="label">
        {{ title }}
        <!-- <span
          v-if="dialogForm.exhibitionId"
          style="font-size: 12px; margin-left: 10px; font-weight: 500"
        >
          <i class="el-icon-warning-outline"></i
          >点击左右切换按钮可切换展览。<span style="color: #f56c6c">
            注意：切换前请注意保存当前展览信息
          </span>
        </span> -->
      </div>
    </div>
    <div class="el-dialog-div">
      <div class="dialog-content" v-if="visible" id="dialog-content">
        <el-form
          size="mini"
          :model="dialogForm"
          class="basic-info"
          :rules="rules"
          ref="form"
        >
          <el-row :gutter="50">
            <el-col :span="12">
              <el-form-item
                label="展览标题"
                :label-width="formLabelWidth"
                prop="title"
              >
                <el-input
                  v-model="dialogForm.title"
                  autocomplete="off"
                  placeholder="请输入展览标题"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item
                label="展览单位"
                :label-width="formLabelWidth"
                prop="deptId"
              >
                <el-cascader
                  style="width: 100%"
                  v-model="dialogForm.deptId"
                  :options="orgTreeData"
                  :props="optionProps"
                  placeholder="请选择展览单位"
                  clearable
                >
                </el-cascader>
              </el-form-item>
              <el-form-item label="展览地区" :label-width="formLabelWidth">
                <el-cascader
                  class="years item"
                  style="width: 100%"
                  v-model="dialogForm.regionCode"
                  :options="regionTree"
                  :props="culturalRegionProps"
                  placeholder="请选择所属地区"
                  filterable
                  clearable
                >
                </el-cascader>
              </el-form-item>
              <el-form-item label="展览类型" :label-width="formLabelWidth">
                <el-select
                  v-model="dialogForm.type"
                  placeholder="请选择展览类型"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="(value, key) in dicts.displayType"
                    :key="key"
                    :label="value"
                    :value="key"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item
                label="展览性质"
                :label-width="formLabelWidth"
                style="display: none"
              >
                <el-select
                  v-model="dialogForm.displayCharacter"
                  placeholder="请选择展览性质"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="(value, key) in dicts.displayCharacter"
                    :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%"
                  clearable
                >
                  <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">
                <VueQuillEditor
                  v-model="dialogForm.intro"
                  placeholder="请输入展览介绍"
                />
              </el-form-item>
              <el-form-item label="关键词" :label-width="formLabelWidth">
                <el-input
                  v-model="dialogForm.keyword"
                  autocomplete="off"
                  placeholder="请输入关键词"
                  clearable
                ></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%"
                  clearable
                >
                  <el-option
                    v-for="item in crList"
                    :key="item.crId"
                    :label="item.name"
                    :value="item.crId"
                  >
                  </el-option>
                </el-select>
                <!-- <PageSelect
                ref="PageSelect"
                label="name"
                value="crId"
                :select.sync="value"
                :url="pageSelectUrl"
                filter-key="name"
              /> -->
              </el-form-item>

              <el-form-item label="关联文献" :label-width="formLabelWidth">
                <el-select
                  v-model="literatureIdArr"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词搜索文献"
                  :remote-method="searchLiterature"
                  :loading="loading"
                  style="width: 100%"
                  ref="literatureSelect"
                  clearable
                >
                  <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-select
                  v-model="vrIds"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词搜索虚拟展厅"
                  :remote-method="searchVirtual"
                  :loading="loading"
                  style="width: 100%"
                  ref="virtualSelect"
                  clearable
                >
                  <el-option
                    v-for="item in vrList"
                    :key="item.bvId"
                    :label="item.name"
                    :value="item.bvId"
                  >
                  </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">
                <el-input
                  type="textarea"
                  placeholder="请输入备注"
                  v-model="dialogForm.remark"
                  maxlength="100"
                  show-word-limit
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="展览封面" :label-width="formLabelWidth">
                <ManualUploader
                  :fileLimit="1"
                  listType="picture-card"
                  :fileType="['png', 'jpeg', 'jpg']"
                  :files="faceImage"
                  ref="faceImage"
                  @getRemovedIds="getRemovedIds"
                />
              </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"
                  :advice="imagesAdvice"
                  @getRemovedIds="getRemovedIds"
                />
              </el-form-item>
              <el-form-item label="展览音频" :label-width="formLabelWidth">
                <ManualUploader
                  :files="audios"
                  :fileLimit="1"
                  :fileSize="50"
                  :fileType="['mp3']"
                  listType="card"
                  ref="audios"
                  @getRemovedIds="getRemovedIds"
                />
              </el-form-item>
              <el-form-item label="展览视频" :label-width="formLabelWidth">
                <ManualUploader
                  :files="videos"
                  :fileLimit="6"
                  :fileSize="500"
                  :fileType="['mp4']"
                  listType="card"
                  ref="videos"
                  @getRemovedIds="getRemovedIds"
                />
              </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
          size="mini"
          icon="el-icon-top"
          @click.native="handleToTop"
        ></el-button>
        <el-button
          size="mini"
          @click="handleClose"
          icon="el-icon-circle-close"
          type="warning"
          >取 消</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="handleSubmit(0)"
          :disabled="loading"
          icon="el-icon-document-checked"
        >
          只保存
        </el-button>
        <!-- <el-button @click="handlePreview">预 览</el-button> -->
        <el-button
          size="mini"
          type="primary"
          @click="handleSubmit(1)"
          icon="el-icon-circle-check"
          :disabled="loading"
          >保存并提交审核
        </el-button>
        <!-- <el-button
          size="mini"
          type="primary"
          @click="handleSubmit"
          icon="el-icon-circle-check"
          :disabled="loading"
          >提交
        </el-button> -->
      </div>
    </div>
    <!-- <el-tooltip
      class="item"
      effect="dark"
      content="下一展览"
      placement="top-start"
    >
      <div
        class="next btn"
        v-if="dialogForm.exhibitionId"
        @click="handleChangeDisplay('next')"
      >
        <i class="el-icon-arrow-right"></i>
      </div>
    </el-tooltip>
    <el-tooltip
      class="item"
      effect="dark"
      content="上一展览"
      placement="top-start"
    >
      <div
        class="prev btn"
        v-if="dialogForm.exhibitionId"
        @click="handleChangeDisplay('prev')"
      >
        <i class="el-icon-arrow-left"></i>
      </div>
    </el-tooltip> -->
  </el-dialog>
</template>

<script>
import { addOrUpdateDisplayTemp } from "@/api/display";
import { mapGetters, mapActions } from "vuex";
import ExhibitionUnit from "./ExhibitionUnit.vue";
import { uploadV1 } from "@/utils/file";
import { themeTypeOptions } from "../contants";
import { deleteFiles } from "@/api/file";
import { getVirtualListPer } from "@/api/vitual";
import { rules } from "../configs/validateRules";
import { pageSelectUrl, upLoadAddress } from "../configs/urls";
import bizTransform from "@/utils/bizTransform";

import submit from "./submit";
const {
  faceImageToClient,
  literatureListToIds,
  statusStrToBool,
  getDeptIdArr,
} = bizTransform;

export default {
  name: "InfoEditDialog",
  components: {
    ExhibitionUnit,
  },
  props: {
    form: {
      type: Object,
      default: () => ({}),
    },
    currentPageIds: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    ...mapGetters(["userInfo", "dicts"]),
    title() {
      return this.dialogForm.exhibitionId ? "修改信息" : "发布展览";
    },
    themeTypeOptions() {
      return themeTypeOptions;
    },
  },
  watch: {
    form: {
      handler: function (value) {
        if (!value) {
          return;
        }
        this.coverServerData(value);
      },
      immediate: true,
    },
    "dialogForm.themeType": {
      handler: function (value) {
        if (!value) {
          return;
        }
        if (value == "2") {
          this.imagesAdvice = "中国风主题建议上传10张以上的展览图片，效果更好";
        } else {
          this.imagesAdvice = "";
        }
      },
    },
    // currentId(value) {
    //   this.$emit("changeDisplay", value);
    // },
  },
  data() {
    return {
      dialogForm: {
        ...this.form,
      },
      formLabelWidth: "100px",
      loading: false,
      submitLoading: false,
      loadingText: "",
      typeOptions: [{ label: "展览类型", value: 1 }], //后期从vuex中取
      disabled: false,
      exhibitionUnits: [],
      literatureList: [], //文献列表
      literatureIdArr: [], //选中的文献列表
      crList: [], //文物列表
      crIds: [], //选中的文物列表
      vrList: [], //虚拟展厅列表
      vrIds: [],
      faceImage: [],
      images: [],
      videos: [],
      audios: [],
      orgTreeData: [],
      optionProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
      culturalRegionProps: {
        value: "code",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
      regionTree: [],
      imagesAdvice: "",
      visible: false,
      nextDiaplayId: null,
      prevDiaplayId: null,
      currentId: null,
      pageSelectUrl,
      upLoadAddress,
      rules,
      mediaKeys: ["faceImage", "images", "videos", "audios"],
      removedIds: [],
    };
  },
  async created() {
    await this.getDictList(["displayType", "displayCharacter"]);
    this.orgTreeData = await this.getMuseumTreeData(false);
    this.loadRegionTree();
  },

  methods: {
    ...mapActions("dict", ["getDictList", "getLtList", "getCrList"]),
    ...mapActions("org", ["getMuseumTreeData", "getSysRegionTreeData"]),
    coverServerData(value) {
      if (value) {
        this.dialogForm = JSON.parse(JSON.stringify(value));
        if (!this.dialogForm.exhibitionId) {
          const { deptId, regionCode } = this.userInfo;
          this.dialogForm.deptId = deptId;
          this.dialogForm.regionCode = regionCode;
        } else {
          this.currentId = this.dialogForm.exhibitionId;
        }
        const {
          faceImage,
          faceImageUrl,
          faceImagePressUrl,
          imagesVo,
          videosVo,
          audiosVo,
          status,
          literature,
          literatureVo,
          deptId,
          exhibitionUnits,
          culturalRelicVo,
          crIds,
          virtualVo,
        } = this.dialogForm;
        this.faceImage = faceImageToClient(
          faceImage,
          faceImageUrl,
          faceImagePressUrl
        );
        this.images = imagesVo || [];
        this.videos = videosVo || [];
        this.audios = audiosVo || [];
        this.crList = this.getClientCrList(culturalRelicVo);
        this.crIds = this.getClientCrIds(crIds);
        this.vrList = this.getClientVrList(virtualVo);
        this.vrIds = this.getClientVrIds(virtualVo);
        this.dialogForm.status = this.getClientStatus(status);
        this.literatureIdArr = this.getClientLiteratureIds(literature);
        this.literatureList = literatureVo;
        this.dialogForm.deptId = getDeptIdArr(deptId, this.userInfo);
        this.dialogForm.exhibitionUnits = this.getClientUnit(exhibitionUnits);
      }
    },
    getClientStatus(status) {
      if (status == undefined) {
        return false;
      }
      return Boolean(Number(status));
    },
    // 获取前端需要的文物list
    getClientCrList(culturalRelicVo) {
      if (!culturalRelicVo || culturalRelicVo.length == 0) {
        return;
      }
      return culturalRelicVo;
    },
    // 获取前端需要的文物id合集
    getClientCrIds(crIds) {
      if (!crIds) {
        return;
      }
      if (crIds.includes(",")) {
        return crIds.split(",");
      } else {
        return [crIds];
      }
    },
    // 获取前端需要的虚拟展list
    getClientVrList(virtualVo) {
      if (!virtualVo || virtualVo.length == 0) {
        return;
      }
      return virtualVo;
    },
    // 获取前端需要的虚拟展id合集
    getClientVrIds(virtualVo) {
      if (!virtualVo || virtualVo.length == 0) {
        return;
      }
      const vrIds = virtualVo.map((item) => {
        return item.bvId;
      });
      return vrIds;
    },
    getClientLiteratureIds(literature) {
      if (!literature) {
        return;
      }
      if (literature.includes(",")) {
        return literature.split(",");
      } else {
        return [literature];
      }
    },

    // 获取前端需要的布展单元
    getClientUnit(exhibitionUnits) {
      function loopUnit(arr) {
        arr.forEach((unit) => {
          if (unit.length > 0) {
            // 如果有文物，回填文物
            if (unit.culturalRelics && uni.culturalRelics.length > 0) {
              this.$set(unit, "crIds", unit.culturalRelics);
            }
            if (unit.children) {
              loopUnit(unit.children);
            }
          }
        });
        return arr;
      }
      if (!exhibitionUnits || exhibitionUnits.length == 0) {
        return;
      }
      const newUnits = loopUnit(exhibitionUnits);
      return newUnits;
    },
    // 关联文献查询
    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.getLtList(params);
        if (res.code == 0) {
          this.literatureList = res.data.records;
        } else {
          this.literatureList = [];
          this.$message.error(res.msg);
        }
      }, 500);
    },

    // 关联虚拟展厅查询
    searchVirtual(queryString) {
      let that = this;
      if (!queryString.trim()) {
        that.vrList = [];
        return;
      }
      that.loading = true;
      const params = {
        name: queryString,
        page: "1",
        limit: "100",
      };

      setTimeout(async () => {
        that.loading = false;
        let res = await getVirtualListPer(params);
        if (res.code == 0) {
          that.vrList = res.data.records;
        } else {
          that.vrList = [];
          that.$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 () => {
        that.loading = false;
        const res = await this.getCrList({
          params,
          isReload: true,
        });
        if (res.code == 0) {
          that.crList = res.data.records;
        } else {
          that.crList = [];
          that.$message.error(res.msg);
        }
      }, 500);
    },

    // 取消编辑
    cancelForm() {
      if (this.loading) {
        this.loading = false;
      }
      if (this.submitLoading) {
        this.submitLoading = false;
      }
      this.resetData();
    },

    handleToTop() {
      let el = document.getElementById("dialog-content");
      el.scrollIntoView({ block: "start", behavior: "smooth" });
    },

    loadRegionTree() {
      function loopTree(arr) {
        if (!arr || arr.length == 0) {
          return;
        }
        arr.forEach((item) => {
          if (item.children && item.children.length == 0) {
            delete item.children;
          } else {
            loopTree(item.children);
          }
        });
      }
      let parentId = "";
      this.getSysRegionTreeData(parentId).then((res) => {
        this.regionTree = res;
        loopTree(res);
      });
    },

    handleChangeDisplay(dir) {
      let index = this.currentPageIds.indexOf(this.currentId);
      switch (dir) {
        case "next":
          if (this.currentPageIds[index + 1]) {
            this.currentId = this.currentPageIds[index + 1];
          } else {
            this.$message.info("已经是此页最后一个！");
          }
          break;
        case "prev":
          if (this.currentPageIds[index - 1]) {
            this.currentId = this.currentPageIds[index - 1];
          } else {
            this.$message.info("已经是此页第一个！");
          }
          break;
      }
    },
    getRemovedIds(removedIds) {
      if (removedIds) {
        this.removedIds = [...new Set([...this.removedIds, ...removedIds])];
      }
    },

    handleSubmit(submitFlag) {
      submit(submitFlag, this);
    },

    // 清空编辑组件中的所有值
    resetData() {
      // 清空文献
      this.literatureIdArr = [];
      // 清空文物
      this.crIds = [];
      // this.literatureNames = [];
      // 清空布展单元
      this.exhibitionUnits = [
        {
          euId: 1, //后期去掉
          // unit: "", //单元名称,如前言、第一单元，暂时忽略
          title: "", //单元标题，类似主题名称
          intro: "", //单元介绍
          images: "", //图片id集合
          videos: "", //视频id集合
          crIds: [], //关联文物集合
        },
      ];
      this.images = [];
      this.videos = [];
      this.audios = [];
      this.faceImage = [];
      this.removedIds = [];
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.visible = false;
          this.resetData();
          this.submitLoading = false;
          this.$emit("handleClose");
          done();
        })
        .catch((_) => {});
    },
  },
};
</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;
  }
}

.el-dialog-div {
  height: 80vh;
  overflow-x: hidden;
}

.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;
  margin: 20px 50px;
  position: sticky;
  bottom: 0;
}

.video-lists {
  display: flex;
}

::v-deep .el-dialog__body {
  position: relative;
}

.btn {
  width: 60px;
  height: 60px;
  border: 2px solid #fff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 40%;
  cursor: pointer;

  i {
    font-size: 40px;
    color: #fff;
  }
}

.prev {
  left: -8%;
}

.next {
  right: -8%;
}
</style>
@/utils/bizTransform@/utils/bizUploadFunctions
