<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    :before-close="optFun"
  >
    <el-form :model="form" class="topicOpt">
      <el-form-item label="主题" :label-width="formLabelWidth" required>
        <el-input
          v-model="objInfo.topic.subject"
          auto-complete="off"
          clearable
          :maxLength="max"
          placeholder="请输入主题(最长60个字符)"
        ></el-input>
      </el-form-item>
      <!--- 关联学科--->
      <div class="course-sort">
        <el-form-item label="关联学科" :label-width="formLabelWidth" required>
          <div class="child-sort">
            <div class="child-first" v-for="(_item,_index) in courseOneLeveArray" :key="_index">
              <!-- <span>一级:</span> -->
              <el-select
                v-model="_item.id"
                placeholder="请选择一级分类"
                @focus="getOneLevelIndex(_index)"
                @change="changeCourseOneLevel"
              >
                <el-option
                  v-for="(item,index) in courseOneLevelList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="child-sort">
            <div class="child" v-for="(_item,_index) in courseSortArray" :key="_index">
              <!-- <span>二级:</span> -->
              <el-select
                v-model="_item.id"
                @focus="getTowLevelIndex(_index)"
                @change="changeCourseTwoLevel"
                placeholder="请选择二级分类"
              >
                <el-option
                  v-for="(item,index) in _item.list"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <i class="el-icon-circle-plus-outline" v-if="_index == 0" @click="addTwoLevelCourse"></i>
              <i
                class="el-icon-remove-outline"
                v-if="_index > 0"
                @click="reduceTwoLevelCourse(_index)"
              ></i>
            </div>
          </div>
        </el-form-item>
      </div>
      <el-form-item label="列表内容" :label-width="formLabelWidth">
        <el-input
          type="textarea"
          v-model="objInfo.topic.content"
          auto-complete="off"
          clearable
          size="mini"
          :maxLength="maxL"
          placeholder="请输入主题(最长1000个字符)"
          rows="5"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="列表配图"
        :label-width="formLabelWidth"
        class="teste1"
      >
        <!-- 	<el-upload
				  action="#"
				  list-type="picture-card"
				  :file-list="fileList"
				  :on-change="selectImg"
				  :on-preview="handlePictureCardPreview"
				  :on-remove="handleRemove">
				  <i class="el-icon-plus"></i> -->
        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog
          :visible.sync="dialogVisible"
          size="tiny"
          :modal="false"
          :close-on-click-modal="false"
        >
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
	  <el-form-item label="详情页内容" required :label-width="formLabelWidth">
        <editor-component
          :message="richContent"
          @setEditorMsge="setEditorMsge"
          id="1"
          ref="editorWraper"
        ></editor-component>
	  </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="optFun('1')" size="mini">取 消</el-button>
      <el-button
        type="primary"
        @click="optFun('2')"
        size="mini"
        :disabled="isRequestBack"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import { doUpload, getFilePath } from "../../utils/qiniu-util";
import { mapGetters } from "vuex";
import { openLoading, closeLoading } from "../../utils/utils";
import  EditorComponent from '../../components/editorComponent'
let vm = null;
export default {
  components: {
	  EditorComponent
  },
  data() {
    return {
      formLabelWidth: "82px",
      form: {},
      id: null,
      dialogImageUrl: "",
      max: 60,
      maxL: 1000,
      dialogVisible: false,
      dialogFormVisible: false,
      fileList: [],
      title: "编辑话题",
      reType: ["PUT", "POST"],
      isEdit: false,
      objInfo: {
        topic: {
          subject: "",
          content: "",
        },
        images: [],
      },
      isRequestBack: false,
	  oneLevelIndex: '', //一级分类index
      courseOneLevelId: "", //一级分类id
      courseOneLevelList: [], //一级分类数据
	  towLevelIndex: '',//二级分类index
      courseSortArray: [], //二级分类
      courseOneLeveArray: [], //一级分类
	  richContent: '',
    };
  },
  props: {
    isShow: {
      default: false,
      type: Boolean,
    },
    editInfo: {
      default: () => {},
      type: Object,
    },
    discussId: {
      default: 0,
      type: Number,
    },
  },
  computed: {
    ...mapGetters(["_token", "idType"]),
  },
  created() {
    this.dialogFormVisible = this.isShow;
	
    if (this.editInfo.topic) {
      this.isEdit = true;
      this.objInfo = this.editInfo;
      this.objInfo.topic.content = this.objInfo.topic.content.replace(
        /&nbsp;/g,
        " "
      );
    } else {
      this.title = "新增话题";
      this.isEdit = false;
	  this.courseInt()
    }
	this.getCourseOneLevel()
    if (this.objInfo.images.length > 0) {
      for (let i = 0; i < this.objInfo.images.length; i++) {
        this.fileList.push({
          url: this.objInfo.images[i].imageurl,
          imageurl: this.objInfo.images[i].imageurl,
          id: this.objInfo.images[i].id,
        });
      }
    }
  },
  // 挂载到Dom完成时
  mounted: function () {},
  methods: {
	// 新建时增加初始化学科
	courseInt() {
		this.courseOneLeveArray.push({ id: "" });
    	this.courseSortArray.push({ id: "", list: [] });
	},
	// 获取一级疾病分类数据
    getCourseOneLevel() {
      	this.GET("/contents/admin/label/getFirstLevelLable/1")
        .then(res => {
          if (res.code == "000000") {
            this.courseOneLevelList = res.data;
          }
        });
    },
	getOneLevelIndex(val) {
      this.oneLevelIndex = val;
    },
	// 选择一级分类
    changeCourseOneLevel(value) {
      this.courseOneLevelList.forEach(item => {
        if (value == item.id) {
          if (item.isAppHide) {
            this.$message.info("选择的标签为前端不展示标签");
          }
        }
      });
      this.courseOneLevelId = value;
      this.courseSortArray[this.oneLevelIndex].id = "";
      this.getCourseTwoLevel();
    },
	 // // 获取二级疾病分类
    async getCourseTwoLevel(index) {
      console.log("1级索引" + this.oneLevelIndex);
      let req = {
		parentId: this.courseOneLevelId,
		publish: 1
      };
      await this.GET("/contents/admin/label/childLabelList", req)
        .then(res => {
          if (res.code == "000000") {
            if (this.editInfo.topic) {
              //edit
              this.courseSortArray[index].list = res.data;
            } else {
              //add
              this.courseSortArray[this.oneLevelIndex].list = res.data;
            }
            this.$forceUpdate();
          }
        });
    },
	// 增加二级分类
    addTwoLevelCourse() {
		this.courseInt()
    },
    // 减少二级分类
    reduceTwoLevelCourse(index) {
      this.courseOneLeveArray.splice(index, 1);
      this.courseSortArray.splice(index, 1);
      console.log(this.courseSortArray);
    },
	getTowLevelIndex(val) {
      this.towLevelIndex = val;
    },
	 // 选择二级分类--重复校验
    changeCourseTwoLevel(value) {
      for (let i = 0; i < this.courseSortArray.length; i++) {
        if (i != this.towLevelIndex) {
          if (value == this.courseSortArray[i].id) {
            this.$message.info("疾病分类存在重复的二级分类，请修改");
            this.courseSortArray[this.towLevelIndex].id = "";
            return;
          }
        }
      }
      this.courseSortArray.forEach((item, index) => {
        if (value == item.id) {
          if (item.isAppHide) {
            this.$message.info("选择的标签为前端不展示标签");
            this.courseSortArray[this.towLevelIndex].id = "";
          }
        }
      });
    },
	// 学科回显
	labelEcho(labelList){
		if (labelList && labelList.lenght) {
			for (let i = 0; i < labelList.length; i++) {
			if (
				labelList[i].type == 1 &&
				labelList[i].level == 1
			) {
				this.courseOneLevelId = labelList[i].id;
				this.courseOneLeveArray.push({
				id: labelList[i].id
				});
				this.getCourseTwoLevel(i);
			} else if (
				labelList[i].type == 1 &&
				labelList[i].level == 2
			) {
				for (let a = 0; a < this.courseOneLeveArray.length; a++) {
				if (
					this.courseOneLeveArray[a].id == labelList[i].parentId
				) {
					this.courseSortArray.push({
					id: labelList[i].id
					});
					break;
				}
				}
			} else if ( labelList[i].type == 2 && labelList[i].level == 2) { }
			}
		} else {
			this.courseSortArray.push({
				id: "",
				list: []
			});
			this.courseOneLeveArray.push({
				id: ""
			});
		}
	},
	// 设置保存时的学科
	setLabelIdList() {
		this.labelIdList = [];
		this.courseOneLeveArray.forEach(item => {
			this.labelIdList.push(item.id);
		});
		this.courseSortArray.forEach(item => {
			this.labelIdList.push(item.id);
		});
	},
	// 保存富文本数据
    setEditorMsge(msg) {
      if (!msg) {
        this.$message.error("请将富文本填写完整!");
        return;
      }
      vm.richContent = msg;
      openLoading(vm);
      let req = {
        richContent: this.richContent,
        id: this.id
      };
      this.POST(
          "v2/qualityContent/updateRichContent",
          req
        )
        .then(function(res) {
          closeLoading(vm);
          if (res.code == "000000") {
            this.$message.success("保存富文本成功");
          } else {
            this.$message.error(res.message);
          }
        })
        .catch(function(error) {
          closeLoading(vm);
          this.$message.error(error);
        });
    },
    handlePictureCardPreview(file) {
      //console.log(file)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    selectImg(file) {
      //console.log(file)
      this.fileList.push({
        url: file.url,
        imageurl: file.url,
      });
    },
    beforeAvatarUpload(file) {
      //console.log(file)
      let imgTypes = ["jpg", "png", "gif", "jpeg"];
      if (file.type) {
        let fileType = file.type.split("/")[1];
        if (imgTypes.indexOf(fileType) == -1) {
          this.showError("上传图片格式仅支持png、jpg、jpeg、gif ");
          return false;
        }
      } else {
        this.showError("上传图片格式仅支持png,jpg,jpeg,gif!");
        return false;
      }
      // 			console.log(this.fileList)
      if (this.fileList.length > 5) {
        // /、this.$message.info('图片个数不能超过6个')
        this.showError("上传图片个数不能超过6个");
        return false;
      }
      this.imgDoUpload(file, 4, 2048, 400, 400);
    },
    imgDoUpload(file, urlType, size, w, h) {
      let vm = this;
      const isSize = file.size / 1024 < size;
      if (!isSize) {
        //vm.$message.info('上传图片要小于' + size + 'k')
        //vm.$message.info('上传图片要小于2M')
        vm.showError("上传图片要小于2M");
        return;
      }
      var _img = new FileReader();
      _img.readAsDataURL(file);
      _img.onload = function (theFile) {
        let image = new Image();
        image.src = theFile.target.result;
        image.onload = function () {
          vm.$message.info("开始上传");
          doUpload(
            vm,
            file,
            getFilePath(file, null),
            "preview4",
            "progress1",
            1
          )
            .then(function (path) {
              //console.log(path)
              vm.fileList.push({
                url: path.fullPath,
                imageurl: path.fullPath,
              });
              vm.$message.success("上传成功");
            })
            .catch((res) => {
              console.log(res);
            });
        };
      };
    },
    handleRemove(file, fileList) {
      let index = null;
      if (this.fileList.length > 0) {
        for (let i = 0; i < this.fileList.length; i++) {
          if (file.url == this.fileList[i].url) {
            index = i;
            break;
          }
        }
        if (index != null) {
          this.fileList.splice(index, 1);
        }
        //console.log(file)
        //console.log(this.fileList)
      }
    },
    optFun(index) {
      if (index == 2) {
        this.subFun();
      } else {
		this.$confirm('确定取消么?', '提示', {
			confirmButtonText: '确定取消',
			cancelButtonText: '关闭',
			type: 'warning'
		}).then(() => {
			this.dialogFormVisible = false;
			this.$emit("setFun", false);
		}).catch(() => {     
		});
	  }
    },
    //返回
    goBack() {
      this.$router.back(-1);
    },
    showError(str) {
      //console.log(str)
      this.$message({
        message: str,
        type: "warning",
      });
    },
    //保存修改讨论组件详细
    subFun() {
      let A = this.isEdit ? this.reType[0] : this.reType[1];

      if (this.objInfo.topic.subject.length == 0) {
        this.showError("请输入主题！");
        return;
      }
      // 加入话题内容识别宫格
      let placeContent = this.objInfo.topic.content.replace(/ /gi, "&nbsp;");
      let parm = {
        topic: {
          subject: this.objInfo.topic.subject,
          // content:this.objInfo.topic.content,
          content: placeContent,
          discussid: this.objInfo.topic.discussid || this.discussId,
          id: this.objInfo.topic.id || null,
          official: true,
        },
        images: this.fileList,
      };
      this.isRequestBack = true;

      let url = "/interaction/topic/admin/";
      if (this.isEdit) {
        url = "/interaction/topic/";
      }

      this[A](url, parm)
        .then((res) => {
          if (res.code == "000000") {
            this.$message({
              message: "操作成功！",
              type: "success",
            });

            setTimeout(() => {
              this.isRequestBack = false;
              this.$emit("setFun", true);
            }, 2000);
          } else {
            this.isRequestBack = false;
            this.$message({
              message: res.message,
              type: "error",
            });
          }
        })
        .catch(function (error) {
          ///console.log()
          //this.$message.error('接口异常请联系管理员');
        });
    },
  },
};
</script>
<style lang="scss">
.topicOpt {
  	.el-form-item__content {
    	width: 80%;
	}
	.el-upload--picture-card {
		height: 80px;
		width: 80px;
		line-height: 80px;
	}
	.el-upload-list--picture-card .el-upload-list__item {
		width: 80px;
		height: 80px;
	}
	.el-form-item__label {
		// line-height: 26px;
	}
	.course-sort {
		position: relative;
		span {
			font-size: 12px;
		}
		span.course-sort-icon {
			position: absolute;
			left: 69px;
			top: 6px;
			color: red;
		}
		.child-sort {
			float: left;
			&.ml {
				margin-left: 52px;
			}
			.child {
				margin: 0 10px 10px;
			}
			.child-first {
				margin-bottom:  10px;
			}
			.label {
				margin-bottom: 10px;
				.lb {
					margin: 0 10px;
				}
			}
			.child {
				margin: 0 10px 10px;
			}
		}
	}
	.course-add-edit .el-dialog {
		width: 850px;
	}
}
</style>