<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="40%"
    :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" size="mini">
          <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', 'webp']"
              ref="images"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button size="mini" @click="cancelForm">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleSubmit"
          >确定<i class="el-icon-circle-check" style="margin-left: 5px"></i
        ></el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { addCcProduct, updateCcProduct } from "@/api/product";
import { mapGetters } from "vuex";
import { uploadV1 } from "@/utils/file";
import { deleteFiles } from "@/api/file";
export default {
  name: "InfoEditDialog",
  components: {},
  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);
            }
          });
        }

        if (deleteFileArr.length > 0) {
          await deleteFiles(deleteFileArr);
        }

        let res = await updateCcProduct(params);
        if (res.code == 0) {
          this.$message.success("修改成功！");
          this.reload();
          this.submitLoading = false;
        }
      } else {
        let res = await addCcProduct(params);
        if (res.code == 0) {
          this.$message.success("添加成功！");
          this.reload();
          this.submitLoading = false;
        }
      }
    },
    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;
  }
}

.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;
}
.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;
  }
}
</style>
