<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="40%"
    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-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-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">
          <el-input
            type="textarea"
            placeholder="请输入展厅简介"
            v-model="dialogForm.intro"
            maxlength="600"
            show-word-limit
          >
          </el-input>
        </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">
          <!-- <el-switch v-model="dialogForm.url"> </el-switch> -->
          <el-input
            v-model="dialogForm.url"
            autocomplete="off"
            placeholder="请输入链接"
          ></el-input>
        </el-form-item>

        <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>
    </div>
    <div class="dialog-footer">
      <el-button @click="cancelForm">取 消</el-button>
      <el-button type="primary" @click="handleSubmit"
        >确定<i class="el-icon-right" style="margin-left: 5px"></i
      ></el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addVirtual, editVirtual } from "@/api/vitual";
import ManualUploader from "@/components/Uploader/ManualUploader.vue";
import { mapGetters } from "vuex";
import { uploadV1 } from "@/utils/file";
export default {
  name: "InfoEditDialog",
  components: {
    ManualUploader,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => ({}),
    },
    orgTreeData: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    ...mapGetters(["userInfo"]),
    dialogVisible: {
      get: function () {
        return this.visible;
      },
      set: function () {},
    },
    title() {
      if (this.dialogForm.bvId) {
        return "修改虚拟展厅信息";
      } else {
        return "添加虚拟展厅";
      }
    },
  },
  watch: {
    dialogVisible(value) {
      if (value) {
        // 判断是否本地
        this.loadRegionTree();
      }
    },
    form: {
      handler: function (value) {
        let that = this;
        that.dialogForm = JSON.parse(JSON.stringify(value));
        // 编辑状态
        if (that.dialogForm.bvId) {
          console.log("that.dialogForm.", that.dialogForm);
          that.status = Boolean(Number(that.dialogForm.status));
          // 回填封面
          if (this.dialogForm.faceImage) {
            that.faceImage = [
              {
                name: this.dialogForm.name + "封面.png",
                url: this.dialogForm.faceImageUrl,
                fileId: this.dialogForm.faceImage,
              },
            ];
          }
        }
      },
      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);
            }
          });
        }
      }
    },
    status(value) {
      console.log(value);
    },
  },
  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: false,
      pidModalKey: 0,
      regionCodeModalKey: 0,
      faceImage: [],
    };
  },
  methods: {
    handlePreview({ type, file }) {
      console.log(type, file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 取消编辑
    cancelForm() {
      this.$emit("handleClose");
      this.faceImage = [];
    },

    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() {
      let params = { ...this.dialogForm };
      // // 回填图片
      // if (this.faceImage.length > 0) {
      //   params.faceImage = this.faceImage[0].fileId;
      // }
      // return;
      let deleteFileArr = [];
      let file = this.$refs.faceImage.getFiles();
      if (file.length > 0) {
        let formData = new FormData();
        switch (file[0].status) {
          case "ready":
            formData.append("faceImage", file[0].raw);
            let upLoadRes = await uploadV1(formData);
            if (upLoadRes.code == 0) {
              params.faceImage = upLoadRes.data[0].fileId;
            } else {
              this.$message.error("上传失败！:" + upLoadRes.data.msg);
            }
            deleteFileArr.push(this.dialogForm.faceImage);
            break;
          case "success":
            params.faceImage = file[0].fileId;
            break;
        }
      } else {
        params.faceImage = "";
      }

      // 处理行政区划
      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.bvId) {
        let res = await editVirtual(params);
        if (res.code == 0) {
          this.$message.success("修改成功！");
          this.reload();
        }
      } else {
        // let params = { ...this.dialogForm };
        // // // 回填图片
        // // if (this.faceImage.length > 0) {
        // //   params.faceImage = this.faceImage[0].fileId;
        // // }
        // // 处理行政区划
        // params.regionCode = params.regionCode[params.regionCode.length - 1];
        // // 处理所属部门
        // params.deptId = params.deptId[params.deptId.length - 1];
        // // 处理状态
        // params.status = this.status ? 1 : 0;
        // return
        let res = await addVirtual(params);
        if (res.code == 0) {
          this.$message.success("添加成功！");
          this.reload();
        }
      }
    },
    reload() {
      this.$emit("refresh", true); //需要重新获取orgTree
      this.$emit("handleClose");
      this.faceImage = [];
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.$emit("handleClose");
          this.faceImage = [];
        })
        .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>