<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="80%"
    :before-close="handleClose"
    top="2vh"
    lock-scroll
    v-loading="submitLoading"
    element-loading-background="rgba(0, 0, 0, 0.5)"
    :element-loading-text="loadingText"
  >
    <div class="title" slot="title">
      <div class="divider"></div>
      <div class="label">{{ title }}</div>
    </div>
    <div class="el-dialog-div">
      <div class="dialog-content">
        <el-form
          :model="dialogForm"
          class="basic-info"
          :rules="rules"
          ref="form"
          status-icon
        >
          <el-row :gutter="50">
            <el-col :span="12">
              <el-form-item
                label="文物名称"
                :label-width="formLabelWidth"
                prop="name"
              >
                <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"
                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"
                prop="intro"
              >
                <VueQuillEditor v-model="dialogForm.intro" />
              </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="200"
                  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="200"
                  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="500"
                  :fileType="['mp4']"
                  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>
    </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 VueQuillEditor from "@/components/VueQuillEditor";
export default {
  name: "InfoEditDialog",
  components: {
    ManualUploader,
    VueQuillEditor,
  },
  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() {
    let that = this;
    var checkFaceImage = (rule, value, callback) => {
      if (that.faceImage.length == 0) {
        // this.$message.info('请上传封面')
        return callback(new Error("请上传封面"));
      } else {
        callback();
      }
    };

    var checkIntro = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请填写馆藏介绍"));
      } else {
        callback();
      }
    };
    return {
      dialogForm: {
        ...this.form,
      },
      formLabelWidth: "100px",
      loading: false,
      submitLoading: false,
      loadingText: "",
      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, //单选选择任意一级选项
      },
      rules: {
        name: [{ required: true, message: "请输入文物名称", trigger: "blur" }],
        // faceImage: [
        //   { required: true, message: "请上传封面", trigger: "change" },
        // ],
        // faceImage: [
        //   { required: true, validator: checkFaceImage, trigger: "change" },
        // ],
        deptId: [
          { required: true, message: "请填写馆藏单位", trigger: "change" },
        ],
        // intro: [{ required: true, message: "请输入馆藏介绍", trigger: "blur" }],

        intro: [{ required: true, validator: checkIntro, trigger: "blur" }],
      },
    };
  },
  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);
    },
    // 取消编辑
    cancelForm() {
      this.$emit("handleClose");
      //TODO:如果正在编辑需要处理正在编辑
      if (this.loading) {
        this.loading = false;
      }
      if (this.submitLoading) {
        this.submitLoading = false;
      }
      this.reset();
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid,err) => {
        if (valid) {
          var that = this;
          this.submitLoading = true;
          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);
                }
              });
            }
          });
          // 上传所有媒体文件
          let filesObj = {};

          var formDataArr = Array.from(formData.entries(), ([key, prop]) => ({
            [key]: {
              ContentLength: typeof prop === "string" ? prop.length : prop.size,
            },
          }));
          // formData有长度时再进行上传
          if (formDataArr.length > 0) {
            this.loadingText = "正在上传文件...请耐心等待";
            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) {
            this.loadingText = "正在处理文物数据...请耐心等待";
            // const { deptId, regionCode } = this.userInfo;
            const params = { ...this.dialogForm };
            params.literature = this.literatureValues.join(",");
            params.status = this.dialogForm.status ? 1 : 0;
            // 处理年份
            if (params.years && 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();
            }

            addCulturalRelic(params)
              .then((res) => {
                if (res.code == 0) {
                  setTimeout(() => {
                    this.submitLoading = false;
                    this.$emit("handleClose");
                    this.$emit("refresh");
                    this.reset();
                    this.$message.success("提交成功！");
                  }, 1000);
                }
              })
              .then((err) => {
                this.submitLoading = false;
              });
          } else {
            this.loadingText = "正在处理文物数据...请耐心等待";
            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];
            }
            if (deleteFileArr.length > 0) {
              await deleteFiles(deleteFileArr);
            }
            editCulturalRelic(params)
              .then((res) => {
                if (res.code == 0) {
                  setTimeout(() => {
                    this.submitLoading = false;
                    this.$emit("handleClose");
                    this.$emit("refresh");
                    this.reset();
                    this.$message.success("修改成功！");
                  }, 1000);
                }
              })
              .catch((err) => {
                this.submitLoading = false;
              });
          }
        }else{
          console.warn(err);
        }
      });
    },

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

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

    editorInput(e) {
      console.log(e);
    },
  },
};
</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;
    align-items: flex-end;
    margin: 20px 0;
  }
}

.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>
