<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="40%"
    style="height: 98%"
    :before-close="handleClose"
    top="5vh"
    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="dialog-content">
      <el-form :model="dialogForm" class="basic-info">
        <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-cascader
            style="width: 100%"
            v-model="dialogForm.deptId"
            :options="orgTreeData"
            :props="optionProps"
            placeholder="请选择所属博物馆"
            :key="pidModalKey"
            filterable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="所属地" :label-width="formLabelWidth">
          <el-cascader
            style="width: 100%"
            v-model="dialogForm.regionCode"
            :options="regionTree"
            :props="regionOptionProps"
            placeholder="请选择所属地"
            :key="regionCodeModalKey"
            filterable
          >
          </el-cascader>
        </el-form-item>

        <el-form-item label="展览介绍" :label-width="formLabelWidth">
          <VueQuillEditor
            ref="VueQuillEditor"
            v-model="dialogForm.intro"
            :placeholder="'请输入产品介绍'"
          />
        </el-form-item>

        <el-form-item label="上架" :label-width="formLabelWidth">
          <el-switch v-model="status"> </el-switch>
        </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>
    </div>
    <div class="dialog-footer">
      <el-button @click="cancelForm">取 消</el-button>
      <el-button type="primary" @click="handleSubmit"
        >确定<i class="el-icon-circle-check" style="margin-left: 5px"></i
      ></el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addCcProduct, updateCcProduct } from "@/api/literature";
import ManualUploader from "@/components/Uploader/ManualUploader.vue";
import { mapGetters } from "vuex";
import { uploadV1 } from "@/utils/file";
import VueQuillEditor from "@/components/VueQuillEditor";
import { deleteFiles } from "@/api/file";
export default {
  name: "InfoEditDialog",
  components: {
    ManualUploader,
    VueQuillEditor,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => ({}),
    },
    orgTreeData: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    ...mapGetters(["userInfo"]),
    title() {
      if (this.dialogForm.bccpId) {
        return "修改信息";
      } else {
        return "添加文创产品";
      }
    },
  },
  watch: {
    visible: {
      handler: function (value) {
        this.dialogVisible = value;
        this.loadRegionTree();
      },
      deep: true,
      immediate: true,
    },
    form: {
      handler: function (value) {
        let that = this;
        that.dialogForm = JSON.parse(JSON.stringify(value));

        if (that.dialogForm.bccpId) {
          // 回填状态
          that.status = Boolean(Number(that.dialogForm.status));
          // 回填图片

          if (that.dialogForm.imagesVo.length > 0) {
            let tempList = [];
            that.dialogForm.imagesVo.map((item) => {
              item.pressUrl = "/files" + item.pressUrl;
              item.url = "/files" + item.url;
              tempList.push(item);
              that.images = tempList;
            });
          } else {
            that.images = [];
          }
        }
      },
      immediate: true,
      deep: true,
    },
    orgTreeData(value) {
      // 遍历，如果children为空，则直接去掉children，以免选择器中显示无结果
      if (value) {
        let tree = [...value];
        loopTree(tree);
        function loopTree(arr) {
          arr.forEach((item) => {
            if (item.children && item.children.length == 0) {
              delete item.children;
            } else {
              loopTree(item.children);
            }
          });
        }
      }
    },
  },
  data() {
    return {
      dialogForm: {},
      formLabelWidth: "100px",
      optionProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true, //单选选择任意一级选项
      },
      regionOptionProps: {
        value: "code",
        label: "name",
        children: "children",
        checkStrictly: true, //单选选择任意一级选项
      },
      regionTree: [],
      status: true,
      pidModalKey: 0,
      regionCodeModalKey: 0,
      images: [],
      dialogVisible: false,
      submitLoading: false,
      loadingText: "",
    };
  },
  methods: {
    handlePreview({ type, file }) {
      console.log(type, file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 取消编辑
    cancelForm() {
      this.$emit("handleClose");
      this.images = [];
      if (this.submitLoading) {
        this.submitLoading = false;
      }
    },

    loadRegionTree() {
      let parentId = "";
      this.$store.dispatch("org/getSysRegionTreeData", parentId).then((res) => {
        this.regionTree = res;
        loopTree(this.regionTree);
        function loopTree(arr) {
          if (arr && arr.length > 0) {
            arr.forEach((item) => {
              if (item.children && item.children.length == 0) {
                delete item.children;
              } else {
                loopTree(item.children);
              }
            });
          }
        }
      });
    },
    async handleSubmit() {
      // this.submitLoading = true;
      let params = { ...this.dialogForm };
      let deleteFileArr = [];
      let oldImageIds = [];
      let newImageIds = [];
      let files = this.$refs.images.getFiles();

      let imgFileIds = [];
      if (files.length > 0) {
        let formData = new FormData();
        files.map((f) => {
          switch (f.status) {
            case "ready":
              formData.append("images", f.raw);
              break;
            case "success":
              imgFileIds.push(f.fileId);
              break;
          }
        });
        var formDataArr = Array.from(formData.entries(), ([key, prop]) => ({
          [key]: {
            ContentLength: typeof prop === "string" ? prop.length : prop.size,
          },
        }));
        // return;
        // formData有长度时再进行上传
        if (formDataArr.length > 0) {
          this.loadingText = "正在上传文件...请耐心等待";
          let upLoadRes = await uploadV1(formData);
          if (upLoadRes.code == 0) {
            upLoadRes.data.map((resFile) => {
              imgFileIds.push(resFile.fileId);
            });
          }
        }

        params.images = imgFileIds.join(",");
      } else {
        params.images = "";
      }
      // return;
      // 处理行政区划
      if (params.regionCode instanceof Array) {
        params.regionCode = params.regionCode[params.regionCode.length - 1];
      }

      // 处理所属部门
      if (params.deptId instanceof Array) {
        params.deptId = params.deptId[params.deptId.length - 1];
      }

      // 处理状态
      params.status = this.status ? 1 : 0;
      if (this.dialogForm.bccpId) {
        if (this.dialogForm.images) {
          oldImageIds = this.dialogForm.images.split(",");
          newImageIds = imgFileIds;
          oldImageIds.map((id) => {
            if (newImageIds.indexOf(id) == -1) {
              deleteFileArr.push(id);
            }
          });
        }
        // console.log("deleteFileArr", deleteFileArr);
        // return;
        let res = await updateCcProduct(params);
        if (res.code == 0) {
          this.$message.success("修改成功！");
          this.reload();
        }
        if (deleteFileArr.length > 0) {
          await deleteFiles(deleteFileArr);
        }
      } else {
        let res = await addCcProduct(params);
        if (res.code == 0) {
          this.$message.success("添加成功！");
          this.reload();
        }
      }
    },
    reload() {
      this.$emit("refresh", true); //需要重新获取orgTree
      this.$emit("handleClose");
      this.images = [];
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.$emit("handleClose");
          this.images = [];
        })
        .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;
  }
}
.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;
}

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