<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-input
                type="textarea"
                placeholder="请输入馆藏介绍"
                v-model="dialogForm.intro"
                maxlength="300"
                show-word-limit
              >
              </el-input>
            </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="6"
                :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";
export default {
  name: "InfoEditDialog",
  components: {
    ManualUploader,
  },
  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);
            }
          });
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    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,
    };
  },
  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;
  },
  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, deptId, regionCode };
        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 {
        const params = { ...this.dialogForm };
        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();
        }
        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>