<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="60%"
    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.pid"
            :options="orgTreeData"
            :props="optionProps"
            placeholder="请选择所属部门"
            :key="pidModalKey"
            disabled
          >
          </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"
          >
          </el-cascader>
        </el-form-item>

        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="经度" :label-width="formLabelWidth">
              <el-input
                style="width: 100%"
                v-model="dialogForm.longitude"
                autocomplete="off"
                placeholder="请输入经度"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"
            ><el-form-item label="纬度" :label-width="formLabelWidth">
              <el-input
                v-model="dialogForm.latitude"
                autocomplete="off"
                placeholder="请输入纬度"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>
        <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="faceImage"
            :fileLimit="1"
            :fileSize="50"
            listType="picture-card"
            :fileType="['png', 'jpeg', 'jpg']"
            ref="museumFaceImage"
          />
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <VueQuillEditor v-model="dialogForm.intro" />
        </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-s-promotion" style="margin-left: 5px"></i
      ></el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addMuseum, editMuseum } from "@/api/org";
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: () => ({}),
    },
    orgTreeData: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    ...mapGetters(["userInfo"]),
    dialogVisible: {
      get: function () {
        return this.visible;
      },
      set: function () {},
    },
    title() {
      if (this.dialogForm.id) {
        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.id) {
          that.status = Boolean(Number(that.dialogForm.status));
          // 回填封面
          if (this.dialogForm.faceImage) {
            that.faceImage = [
              {
                name: this.dialogForm.name + "封面.png",
                url:
                  this.dialogForm.faceImagePressUrl ||
                  this.dialogForm.faceImageUrl,
                fileId: this.dialogForm.faceImage,
              },
            ];
          }
          // 编辑状态下禁用当前所属地之下的节点
        }
      },
      immediate: true,
      deep: true,
    },
    orgTreeData: {
      handler: function (value) {
        if (value && value.length > 0) {
          if (value.length > 0 && !this.dialogForm.id) {
            this.dialogForm.pid = value[0].id; //新增状态下，将所属部门默认填写为树结构根节点
          }
        }
      },
      immediate: true,
      deep: true,
    },
    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: true,
      pidModalKey: 0,
      regionCodeModalKey: 0,
      faceImage: [],
      parentPid: null, //博物馆根节点id
    };
  },
  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 };
      let deleteFileArr = [];
      // 回填图片
      let file = this.$refs.museumFaceImage.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];
      }
      // 处理所属部门
      params.pid = this.regionTree[0].regionId;
      // 处理状态
      params.status = this.status ? 1 : 0;
      if (this.dialogForm.id) {
        let res = await editMuseum(params);
        deleteFiles(deleteFileArr);
        if (res.code == 0) {
          this.$message.success("修改成功！");
          this.reload();
        }
      } else {
        let res = await addMuseum(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>