<template>
  <!-- 添加/编辑 晨会精华 -->
  <div class="add-morning-meeting-wrap" v-loading="dataLoading">
    <div class="date-pick-wrap">
      <el-date-picker v-model="meettingDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择晨会日期"> </el-date-picker>
    </div>
    <div class="content-wrap">
      <div class="meeting-content-wrap">
        <div class="meeting-content" v-for="(item, index) in sectionData" :key="item.index">
          <div class="content">
            <div class="title">
              <h3>段落{{ index + 1 }}：</h3>
              <span class="dele" v-if="index !== 0" @click="deleteSection(index)"> <img src="~@/assets/img/icons/delete-Item.png" /></span>
            </div>
            <div>
              <el-checkbox v-model="item.isJumpNot">可跳转报告详情</el-checkbox>
              <template v-if="item.isJumpNot">
                <el-input style="margin: 20px 0" v-model="item.reportLink" placeholder="请输入报告链接"></el-input>
                <el-input v-model="item.headTitle" placeholder="请输入首行标题"></el-input>
              </template>
            </div>
            <div class="fr-wrapper">
              <froala :id="`froala-editor-${index}`" :ref="`froalaEditor${index}`" :tag="'textarea'" :config="froalaConfig" v-model="item.content"></froala>
            </div>
          </div>
          <div class="classify-box">
            <el-select placeholder="请选择行业" v-model="item.industry" value-key="ChartPermissionId" @change="handleSelectChange(item, index, 'industry')">
              <el-option
                v-for="industry in industryData"
                :key="industry.ChartPermissionId"
                :label="industry.PermissionName"
                :value="{ ChartPermissionId: industry.ChartPermissionId, PermissionName: industry.PermissionName }"
              />
            </el-select>
            <el-select placeholder="请选择产业" filterable v-model="item.property" value-key="ChartPermissionId" @change="handleSelectChange(item, index, 'property')">
              <el-option v-for="property in getPropertyData(item.industry)" :key="property.ChartPermissionId" :label="property.PermissionName" :value="property" />
            </el-select>
            <el-select multiple placeholder="请选择标的" v-model="item.subject" @focus="getSubjectData(item.property)">
              <el-option v-for="subject in subjectData" :key="subject.IndustrialSubjectId" :label="subject.SubjectName" :value="subject.IndustrialSubjectId" />
            </el-select>
          </div>
        </div>
        <div class="add-content-box" @click="addSection"><img src="~@/assets/img/set_m/add.png" /> 添加段落</div>
      </div>

      <div class="form-btn">
        <el-button type="primary" @click="comfirm('save')">保存</el-button>
        <el-button type="primary" @click="comfirm('pub')" v-if="isPublishShow">发布</el-button>
        <el-button @click="comfirm('cancel')">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { raiInterface } from "@/api/api.js";
export default {
  data() {
    var that = this;
    return {
      meettingDate: "",
      meetingId: 0,
      froalaConfig: {
        toolbarButtons: ["bold", "italic", "underline", "strikeThrough", "insertHR", "fontSize", "align", "undo", "redo"],
        height: 260,
        fontSizeDefaultSelection: "16",
        quickInsertEnabled: false,
        theme: "dark", //主题
        placeholderText: "请输入晨会内容",
        language: "zh_cn",
        events: {
          initialized: function () {
            that.editor = this;
            that.editor.toolbar.hide();
          },
        },
      },
      sectionData: [
        {
          isJumpNot: false, //是否跳转
          reportLink: "", //报告链接
          headTitle: "", //报告标题
          content: "", //晨会内容
          industry: "", //行业
          property: "", //行业
          subject: "", //标的
        },
      ],
      industryData: [],
      allPropertyData: [], //总的产业数据
      PropertyData: [], //单个行业下的产业数据
      subjectData: [],
      isGoBack: true, //点击底部按钮时,是否进行页面跳转
      isPublishShow: false, //是否显示发布按钮
      dataLoading: false,
    };
  },
  methods: {
    //添加段落
    addSection() {
      const section = {
        content: "",
        industry: "",
        property: "",
        subject: "",
        isJumpNot: false, //是否跳转
        reportLink: "", //报告链接
        headTitle: "", //报告标题
      };
      this.sectionData.push(section);
    },
    //删除段落
    deleteSection(index) {
      this.sectionData.splice(index, 1);
    },
    //获取行业数据
    async getIndustryData() {
      const res = await raiInterface.chartPermissionFirstHaveIco();
      if (res.Ret !== 200) return;
      this.industryData = res.Data.List || [];
    },
    //根据行业获取产业数据
    getPropertyData(industry) {
      const industryId = industry.ChartPermissionId;
      if (!industryId) return [];
      let propertyData = [];
      this.allPropertyData.forEach((item) => {
        if (item.ChartPermissionId === industryId) {
          propertyData = item.List || [];
        }
      });
      return propertyData;
    },
    //根据产业获取标的数据
    async getSubjectData(property) {
      const propertyId = property.ChartPermissionId;
      if (!propertyId) {
        this.subjectData = [];
        return;
      }
      const res = await raiInterface.getindustrialSubjectlistIds({ IndustrialManagementIdStr: propertyId });
      if (res.Ret !== 200) return;
      this.subjectData = res.Data.List || [];
    },
    //获取全部产业数据
    async getAllPropertyData() {
      const res = await raiInterface.getListIndustrial();
      if (res.Ret !== 200) return;
      this.allPropertyData = res.Data.List || [];
    },
    //行业 产业 选择框改变时触发
    handleSelectChange(data, index, prop) {
      if (prop === "industry") {
        data.property = "";
        data.subject = [];
      }
      if (prop === "property") {
        data.subject = [];
      }
      this.sectionData.splice(index, 1, data);
    },
    //晨会详情
    async getMeetingDetail(id) {
      //获取晨会详情
      const res = await raiInterface.getMorningMeetingDetail({
        MeetingId: this.meetingId || id,
      });
      if (res.Ret !== 200) return;
      //处理数据
      const data = res.Data.List || [];
      this.meettingDate = res.Data.MeetingTime;
      this.isPublishShow = res.Data.Status === 1 ? false : true;
      this.sectionData = data.map((item) => {
        let temp = {
          id: item.Id,
          content: item.content,
          industry: { ChartPermissionId: item.chartPermissionId, PermissionName: item.chartPermissionName },
          property: { ChartPermissionId: item.industryId, PermissionName: item.industryName },
          reportLink: item.reportLink,
          headTitle: item.title,
          isJumpNot: item.reportLink ? true : false,
        };
        let subject = [];
        let industrialSubjectList = item.industrialSubjectList || [];
        industrialSubjectList.map((i) => {
          subject.push(i.IndustrialSubjectId);
        });
        temp.subject = subject;
        this.getSubjectData(temp.property);
        return temp;
      });
      this.dataLoading = false;
    },
    //保存 发布 取消 操作
    comfirm: _.debounce(async function (type) {
      if (type === "cancel") {
        this.$router.back();
        return;
      }
      if (!this.checkContent()) return;
      if (type === "pub") {
        this.pubMeeting();
      }
      if (type === "save") {
        this.meetingId && this.editMeeting();
        !this.meetingId && this.addMeeting();
      }
      /* if(type==="cancel"){} */

      this.isGoBack && this.$router.back();
    }, 500),
    async pubMeeting() {
      const list = this.getSectionData();
      const res = await raiInterface.publishMorningMeeting({
        MeetingId: Number(this.meetingId),
        MeetingTime: this.meettingDate,
        List: list,
      });
      if (res.Ret !== 200) {
        this.isGoBack = false;
        return;
      }
      this.$message.success("发布成功");
    },
    async addMeeting() {
      const list = this.getSectionData();
      const res = await raiInterface.editMorningMeeting({
        MeetingId: 0,
        MeetingTime: this.meettingDate,
        List: list,
      });
      if (res.Ret !== 200) {
        this.isGoBack = false;
        return;
      }
      await this.getMeetingDetail(res.Data);
      this.meetingId = res.Data;
      this.$message.success("添加成功");
    },
    async editMeeting() {
      const list = this.getSectionData();
      const res = await raiInterface.editMorningMeeting({
        MeetingId: Number(this.meetingId),
        MeetingTime: this.meettingDate,
        List: list,
      });
      if (res.Ret !== 200) {
        this.isGoBack = false;
        return;
      }
      this.$message.success("保存成功");
    },
    //转换页面段落的内容为接口的格式
    getSectionData() {
      //item.content做处理，把<p data-f-id=\"pbf\"....></p>替换成''
      this.sectionData = this.sectionData.map((item) => {
        item.content = item.content.replace(/<p data-f-id=\"pbf\".*?<\/p>/g, "");
        return item;
      });
      let list = [];
      this.sectionData.forEach((item) => {
        let temp = {
          ChapterId: item.id || 0,
          Content: item.content,
          ChartPermissionId: item.industry.ChartPermissionId,
          ChartPermissionName: item.industry.PermissionName,
          IndustryId: item.property.ChartPermissionId,
          IndustryName: item.property.PermissionName,
          IndustrialSubjectIds: item.subject.join(),
          ReportLink: item.reportLink,
          Title: item.headTitle,
        };
        list.push(temp);
      });
      return list;
    },
    //检查晨会内容
    checkContent() {
      for (let i = 0; i < this.sectionData.length; i++) {
        if (this.sectionData[i].isJumpNot && this.sectionData[i].reportLink.length === 0) {
          this.$message.warning(`请输入段落${i + 1}报告链接`);
          return false;
        }
        if (this.sectionData[i].isJumpNot && this.sectionData[i].headTitle.length === 0) {
          this.$message.warning(`请输入段落${i + 1}报告标题`);
          return false;
        }
        //所有的段落有值
        if (this.sectionData[i].content.length === 0) {
          this.$message.warning(`请输入段落${i + 1}的内容`);
          return false;
        }
        //所有的段落 有产业,行业
        if (!(this.sectionData[i].industry instanceof Object)) {
          this.$message.warning(`请选择段落${i + 1}的行业`);
          return false;
        }
        if (!(this.sectionData[i].property instanceof Object)) {
          this.$message.warning(`请选择段落${i + 1}的产业`);
          return false;
        }
      }
      return true;
    },
  },
  mounted() {
    this.getIndustryData();
    this.getAllPropertyData();
    if (this.$route.query.id) {
      this.meetingId = this.$route.query.id;
      this.dataLoading = true;
      this.getMeetingDetail();
    } else {
      this.meettingDate = this.$moment().format("yyyy-MM-DD");
      this.isPublishShow = true;
    }
    //console.log('meetingId',this.meetingId,!this.meetingId)
  },
};
</script>

<style scoped lang="scss">
.add-morning-meeting-wrap {
  .date-pick-wrap {
    background-color: #fff;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    padding: 20px;
    box-sizing: border-box;
  }
  .content-wrap {
    margin-top: 20px;
    background-color: #fff;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    padding: 20px;
    box-sizing: border-box;
    /* height: calc(100vh - 120px - 120px); */
    display: flex;
    flex-direction: column;
    .meeting-content-wrap {
      flex: 1;
      .meeting-content {
        margin-bottom: 20px;
        .content {
          .title {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            h3 {
              margin-left: 2px;
              margin-right: 10px;
            }
            .dele {
              display: flex;
              cursor: pointer;
              img {
                width: 24px;
                height: 24px;
              }
            }
          }
        }
      }
      .classify-box {
        margin-top: 10px;
      }
      .add-content-box {
        cursor: pointer;
        color: #3385ff;
        display: flex;
        align-items: center;
        font-size: 16px;
        width: 100px;
        img {
          width: 15px;
          height: 15px;
          border: 1px solid #3385ff;
          padding: 2px;
          box-sizing: border-box;
          margin-right: 10px;
        }
      }
    }
    .form-btn {
      display: flex;
      justify-content: center;
      /*  height:50px; */
    }
  }
  .fr-wrapper {
    margin-top: 20px;
    border-top: 1px solid #cccccc !important;
    border-bottom: 1px solid #cccccc !important;
  }
}
</style>
