<template>
  <div class="container-summary">
    <el-form :model="addOfEditForm" :rules="rulesOption" ref="addOfEditForm">
      <el-card class="card-top">
        <el-form-item prop="industry" v-if="isSource === 'HZ'">
          <el-select placeholder="请选择行业" clearable v-model="addOfEditForm.industry" style="width: 360px; margin-right: 20px">
            <el-option v-for="item in chartPermissionList" :label="item.PermissionName" :key="item.ChartPermissionId" :value="item.ChartPermissionId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="regions" v-else>
          <el-select placeholder="请选择报告类型" clearable @change="regionsChange" v-model="addOfEditForm.regions" style="width: 360px; margin-right: 20px">
            <el-option v-for="item in chartPermissionList" :label="item.ArticleTypeName" :key="item.ArticleTypeId" :value="item.ArticleTypeId"></el-option>
            <div class="add-report-type" @click="addRepotrTypeHandel">
              <img src="~@/assets/img/set_m/add.png" alt="" />
              添加报告类型
            </div>
          </el-select>
        </el-form-item>
        <el-form-item prop="property">
          <el-cascader
            v-model="addOfEditForm.property"
            placeholder="请选择产业名称"
            :show-all-levels="false"
            :options="industryArr"
            clearable
            @visible-change="industrySelectFocus"
            @change="propertyChange"
            :props="{ ...defaultProps, multiple: true }"
            filterable
          >
          </el-cascader>
        </el-form-item>
        <img v-if="!isSource" src="~@/assets/img/set_m/add_ico.png" style="margin: 0 20px 0 0" @click="addIndustryDlgIsShow" />
        <el-select v-model="markValue" @focus="markSelectFocus" multiple placeholder="请选择关联标的">
          <el-option v-for="item in markOptions" :key="item.IndustrialSubjectId" :value="item.IndustrialSubjectId" :label="item.SubjectName"> </el-option>
        </el-select>
        <img v-if="!isSource" src="~@/assets/img/set_m/add_ico.png" style="margin: 0 0 0 10px" @click="isAddMarketDlg" />
        <el-form-item prop="publishTime">
          <el-date-picker style="margin-left: 30px" v-model="addOfEditForm.publishTime" type="date" placeholder="请选择发布时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd"> </el-date-picker>
        </el-form-item>
      </el-card>

      <el-card style="margin-top: 30px">
        <div class="box">
          <div>
            <el-form-item prop="title" style="display: inline-block">
              <el-input style="width: 360px; margin-right: 30px" v-model="addOfEditForm.title" placeholder="请输入报告标题"></el-input>
            </el-form-item>
            <el-form-item prop="synopsis" style="display: inline-block; margin-right: 30px">
              <el-input style="width: 360px" v-model="addOfEditForm.synopsis" placeholder="请输入摘要"></el-input>
            </el-form-item>
            <el-form-item prop="mobile" style="display: inline-block">
              <el-input v-if="isSource === 'HZ'" style="width: 360px" v-model="addOfEditForm.mobile" placeholder="请输入作者"></el-input>

              <el-autocomplete
                v-else
                style="width: 380px"
                class="inline-input"
                v-model="addOfEditForm.mobile"
                :fetch-suggestions="authorCallbackHandle"
                placeholder="请输入作者（昵称+“-”+备注，例：阿银-xxxxxxxxxx）"
                :trigger-on-focus="false"
                @select="authorSelectHandle"
                clearable
              >
              </el-autocomplete>
            </el-form-item>
          </div>
          <div style="display: inline-block; margin-bottom: 20px" v-if="addOfEditForm.regions == 1">
            <el-button type="primary" @click="dialogVisible = true">纪要内容输入模板</el-button>
          </div>
        </div>
        <el-form-item prop="content">
          <froala id="froala-editor" ref="froalaEditor" :tag="'textarea'" :config="froalaConfig" v-model="addOfEditForm.content"></froala>
        </el-form-item>
        <el-form-item>
          <div class="report-link" v-if="articleTypeName === '路演精华'">
            <span class="report-word">报告链接：</span>
            <el-input placeholder="请输入报告链接" v-model="addOfEditForm.reportLink"></el-input>
          </div>
        </el-form-item>
        <el-form-item class="form-item-bootm">
          <div style="color: #f00; font-size: 16px" v-if="isSource !== 'HZ'">*报告发布前，请在核心观点/核心结论下加分割线</div>
          <el-button type="primary" @click="submitForm('预览')">预览</el-button>
          <el-button type="primary" @click="submitForm('保存')">保存</el-button>
          <el-button type="primary" @click="submitForm('发布')" v-if="isShowStatus">发布</el-button>
          <el-button @click="cancelBtn">取消</el-button>
        </el-form-item>
      </el-card>
    </el-form>

    <el-dialog v-dialogDrag :close-on-click-modal="false" :modal-append-to-body="false" center title="纪要内容模板" :visible.sync="dialogVisible" width="35%" :before-close="handleClose">
      <div id="dialog" v-html="copyText"></div>
      <div style="margin-bottom: 60px">
        <p class="no-cv" style="color: #f00">注：多场调研访谈时，请插入水平线分隔</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button id="copy_text" type="primary" :data-clipboard-text="copyTxt" @click="handleCopyFun">复制模版</el-button>
      </span>
    </el-dialog>
    <add-industry-mark
      optionFormregion="研选"
      :source="2"
      :addIndustryDlg.sync="addIndustryDlg"
      :addMarkDlg.sync="addMarkDlg"
      @commitIndustryDlg="commitIndustryDlg"
      @commitMarkDlg="commitMarkDlg"
      :addMarkUpVal="addMarkUpVal"
    />
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      center
      title="添加报告类型"
      :visible.sync="addReportDialogVisible"
      width="500px"
      :before-close="reportHandleClose"
      append-to-body
    >
      <div>
        <el-input style="width: 100%; margin-bottom: 20px" placeholder="请输入类型名称" clear v-model.trim="reportTypeVal"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reportHandleClose">取消</el-button>
        <el-button type="primary" @click="addReportConfirm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { raiInterface } from "@/api/api.js";
import VueFroala from "vue-froala-wysiwyg";
import Clipboard from "clipboard";
import AddIndustryMark from "../components/addIndustryMark.vue";
import RichTextMixins from "./reportComponents/RichTextMixins";
export default {
  name: "",
  components: { AddIndustryMark },
  mixins: [RichTextMixins],
  data() {
    var that = this;
    return {
      copyText:
        " <div><p>#核心观点：</p> <p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</p></div><div><p>#访谈时间：</p><p>2021.01.01</p></div><div><p>#纪要详情：</p><p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</p></div><div><p>#专家评价：</p><p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</p></div>",
      copyTxt: `#核心观点：
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#访谈时间：
2021.01.01

#纪要详情：
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#专家评价：
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`,
      defaultProps: {
        label: "PermissionName",
        children: "List",
        value: "ChartPermissionId",
      },
      industryArr: [], //
      markValue: "",
      markOptions: [],
      addOfEditFormregion: "", //行业选择
      addIndustryDlg: false, //
      addMarkDlg: false,
      addMarkUpVal: {
        industrialName: "",
        industrialId: "",
      }, //弹框里的
      articleId: 0,
      addOfEditForm: {
        content: "",
        title: "",
        synopsis: "",
        mobile: "", // 预览的作者 用的 mobile 。。。。
        // 头像
        ImgUrl: "",
        // 昵称
        nickName: "",
        reportLink: "",
        regions: "",
        property: "",
        indication: "",
        publishTime: "",
        industry: "", //行业
      },
      rulesOption: {
        regions: [{ required: true, message: "请选择报告类型", trigger: "change" }],
        property: [{ required: true, message: "请选择产业", trigger: "change" }],
        publishTime: [{ required: true, message: "请选择发布时间", trigger: "change" }],
        title: [{ required: true, message: "请输入报告标题", trigger: "blur" }],
        synopsis: [{ required: true, message: "请输入摘要", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入作者", trigger: "blur" }],
        industry: [{ required: true, message: "请选择行业", trigger: "change" }],
      },
      chartPermissionList: [], //行业的数组
      dialogVisible: false,
      isShowStatus: true,
      ummary: 0,
      indicationPostOptins: [], //标的数组v-model
      indicationOption: [], //行业数组
      propertyOption: [], //产业数组
      addReportDialogVisible: false, //添加报告类型
      reportTypeVal: "", //添加报告类型的输入框
      synopsisText: [], //
      articleTypeName: "", //报告类型的名称
      isSource: "",
      numNum: 0,
      timeInterval: null,
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.isSource = this.$route.query.type;
    this.addOfEditForm.mobile = this.isSource === "HZ" ? "弘则内容组" : "";
    this.chartPermission(); //获取基础的报告类型数据
    this.getIndustry();
    if (this.$route.query.id) {
      // 编辑进来的
      this.getsummaryManagedetail();
    } else {
      this.dataInit();
    }
  },
  methods: {
    // 报告的缓存处理数据
    dataInit() {
      if (sessionStorage.getItem(this.isSource == "HZ" ? "addSummaryParamsHZ" : "addSummaryParamsQY")) {
        let data = JSON.parse(sessionStorage.getItem(this.isSource == "HZ" ? "addSummaryParamsHZ" : "addSummaryParamsQY"));
        setTimeout(() => {
          this.addOfEditForm = {
            industry: data.ChartPermissionId, //HZ  行业
            regions: data.ArticleTypeId,
            title: data.Title,
            content: data.Body,
            synopsis: data.Abstract,
            mobile: data.SellerAndMobile,
            ImgUrl: data.ImgUrl,
            nickName: data.NickName,
            reportLink: data.ReportLink,
            publishTime: data.PublishDate,
            property: data.IndustrialManagementIds,
          };
          this.articleTypeName = data.ArticleTypeName;
          this.markValue = data.IndustrialSubjectIds;
          data.IndustrialManagementIds && this.markSelectFocus();
        }, 200);
      }
      this.timeInterval = setInterval(() => {
        let params = {
          Abstract: this.addOfEditForm.synopsis,
          Body: this.addOfEditForm.content,
          SellerAndMobile: this.addOfEditForm.mobile,
          NickName: this.addOfEditForm.nickName,
          ImgUrl: this.addOfEditForm.ImgUrl,
          Title: this.addOfEditForm.title,
          ArticleTypeId: this.addOfEditForm.regions,
          IndustrialSubjectIds: this.markValue,
          IndustrialManagementIds: this.addOfEditForm.property, //产业
          PublishDate: this.addOfEditForm.publishTime,
          ReportLink: this.addOfEditForm.reportLink,
          ChartPermissionId: this.addOfEditForm.industry,
        };
        sessionStorage.setItem(this.isSource == "HZ" ? "addSummaryParamsHZ" : "addSummaryParamsQY", JSON.stringify(params));
        this.numNum++;
      }, 120000);
    },
    //点击了添加产业
    addIndustryDlgIsShow() {
      if (this.addOfEditForm.regions) {
        this.addIndustryDlg = true;
      } else {
        this.addIndustryDlg = false;
        this.$message.error("请选选择报告类型");
      }
    },
    //报告类型的选择事件
    regionsChange(e) {
      this.articleTypeName = this.chartPermissionList.find((item) => item.ArticleTypeId == e).ArticleTypeName;
      let str = this.synopsisText.find((item) => item.ArticleTypeId == e);
    },
    //进来编辑的 获取内容的事件
    async getsummaryManagedetail() {
      const res =
        this.isSource === "HZ"
          ? await raiInterface.reportArticleDetail({ ArticleId: this.$route.query.id })
          : await raiInterface.getsummaryManagedetail({
              ArticleId: this.$route.query.id,
            });
      if (res.Ret !== 200) return;
      this.addOfEditForm = {
        industry: res.Data.ChartPermissionId, //HZ  行业
        regions: res.Data.ArticleTypeId,
        content: res.Data.Body,
        title: res.Data.Title,
        synopsis: res.Data.Abstract,
        mobile: res.Data.SellerAndMobile,
        ImgUrl: res.Data.ImgUrl,
        nickName: res.Data.NickName,
        reportLink: res.Data.ReportLink,
        publishTime: res.Data.PublishDate,
        property: res.Data.ListIndustrial ? res.Data.ListIndustrial.map((item) => [item.ChartPermissionId, item.IndustrialManagementId]) : "",
      };
      this.articleId = res.Data.ArticleId;
      this.articleTypeName = res.Data.ArticleTypeName;
      this.markValue = res.Data.ListSubject ? res.Data.ListSubject.map((item) => item.IndustrialSubjectId) : [];
      this.isShowStatus = res.Data.PublishStatus == 0;
      this.markSelectFocus();
    },
    //表单保存发布事件
    submitForm: _.debounce(async function (type) {
      let validateFieldList = [];
      this.$refs.addOfEditForm.validateField([this.isSource === "HZ" ? "industry" : "regions", "property", "publishTime", "title", "synopsis", "mobile"], (valid) => {
        validateFieldList.push(valid);
      });
      let industrialManagementIds = this.addOfEditForm.property && this.addOfEditForm.property.map((item) => item[1]);
      if (validateFieldList.every((item) => item === "")) {
        let params = {
          Abstract: this.addOfEditForm.synopsis,
          Body: this.addOfEditForm.content,
          SellerAndMobile: this.addOfEditForm.mobile,
          NickName: this.addOfEditForm.nickName,
          ImgUrl: this.addOfEditForm.ImgUrl,
          DoType: type == "保存" ? 0 : 1,
          Title: this.addOfEditForm.title,
          ArticleTypeId: this.addOfEditForm.regions,
          ArticleId: this.$route.query.id ? Number(this.$route.query.id) : 0,
          IndustrialSubjectIds: this.markValue.length ? this.markValue.join(",") : "",
          IndustrialManagementIds: industrialManagementIds.join(","), //产业
          PublishDate: this.addOfEditForm.publishTime,
          ReportLink: this.addOfEditForm.reportLink,
          ChartPermissionId: this.addOfEditForm.industry,
        };
        if (type == "预览") {
          if (!this.isShowStatus) {
            let href = `${process.env.CYGX_WEB}/material/info/${this.$route.query.id}`;
            window.open(href, "_blank");
          } else {
            sessionStorage.setItem("summaryPre", JSON.stringify(params));
            let { href } = this.$router.resolve({ name: "预览研选报告" });
            window.open(href, "_blank");
          }
          return;
        } else {
          const res = this.isSource === "HZ" ? await raiInterface.reportPreserveAndPublish(params) : await raiInterface.preserveAndPublish(params);
          if (res.Ret === 200) {
            clearInterval(this.timeInterval);
            this.$message.success("操作成功！");
            sessionStorage.removeItem(this.isSource == "HZ" ? "addSummaryParamsHZ" : "addSummaryParamsQY");
            this.$refs.addOfEditForm.resetFields();
            this.$router.back();
          }
        }
      }
    }, 500),
    //表单取消事件
    cancelBtn() {
      clearInterval(this.timeInterval);
      this.$refs.addOfEditForm.resetFields();
      sessionStorage.removeItem(this.isSource == "HZ" ? "addSummaryParamsHZ" : "addSummaryParamsQY");
      this.$router.back();
    },
    //获取行业
    async chartPermission() {
      const res = this.isSource === "HZ" ? await raiInterface.getNoTacticsfirst() : await raiInterface.summaryManageArticleType();
      if (res.Ret === 200) {
        this.chartPermissionList = res.Data.List || [];
        this.synopsisText = res.Data.AbstractList || [];
      }
    },
    // 操作：点击了复制按钮
    handleCopyFun() {
      let clipboard = new Clipboard("#copy_text");
      clipboard.on("success", (e) => {
        this.$message({
          type: "success",
          message: "复制成功!",
        });
        this.dialogVisible = false;
        clipboard.destroy(); // 释放内存
      });
      clipboard.on("error", (e) => {
        // 不支持复制
        this.$Message.info("该浏览器不支持自动复制");
        clipboard.destroy(); // 释放内存
      });
    },
    //作者的联想事件，单个 回调
    async authorCallbackHandle(data, cb) {
      const res = await raiInterface.departmentList({ KeyWord: data });
      this.addOfEditForm.ImgUrl = "";
      this.addOfEditForm.nickName = "";
      if (res.Ret === 200) {
        let arr = res.Data.List
          ? res.Data.List.map((item) => {
              return { ...item, value: item.Content };
            })
          : [];
        cb(arr);
      } else {
        cb([]);
      }
    },
    // 作者选择事件
    authorSelectHandle(e) {
      // 同步头像
      this.addOfEditForm.ImgUrl = e.ImgUrl;
      this.addOfEditForm.nickName = e.NickName;
      // console.log(e);
    },
    //添加报告类型的事件
    addRepotrTypeHandel() {
      this.reportTypeVal = "";
      this.addReportDialogVisible = true;
    },
    //添加报告类型弹框的取消事件
    reportHandleClose() {
      this.reportTypeVal = "";
      this.addReportDialogVisible = false;
    },
    //添加报告类型弹框的确定事件
    async addReportConfirm() {
      if (!this.reportTypeVal) return this.$message.error("输入内容不能为空");
      const res = await raiInterface.addSummaryManageArticleType({ ArticleTypeName: this.reportTypeVal });
      if (res.Ret === 200) {
        this.reportTypeVal = "";
        this.addReportDialogVisible = false;
        this.$message.success("添加成功");
        this.chartPermission();
      }
    },
    propertyChange() {
      this.markOptions = [];
      this.markValue = "";
    },
    // 选择报告类型
    industrySelectFocus(value) {
      if (!value) return;
      if (this.addOfEditForm.industry || this.addOfEditForm.regions) {
        this.getIndustry();
      } else {
        this.industryArr = [];
        this.$message.error(this.isSource === "HZ" ? "请先选择行业" : "请先选择报告类型");
      }
    },
    //添加标的的点击事件
    isAddMarketDlg() {
      if (this.addOfEditForm.property.length) {
        let arr = this.addOfEditForm.property.flat(Infinity);
        this.addMarkUpVal.industrialId = arr[1];
        this.industryArr.forEach((item) => {
          if (item.ChartPermissionId == arr[0]) {
            item.List.forEach((key) => {
              if (key.ChartPermissionId == arr[1]) {
                this.addMarkUpVal.industrialName = key.PermissionName;
              }
            });
          }
        });
        if (this.addOfEditForm.property.length > 1) {
          this.$message.error("已选多个产业，无法添加标的");
        } else {
          this.addMarkDlg = true;
        }
      } else {
        this.$message.error("未选择产业，无法添加标的");
      }
    },
    //点击添加标的的下拉选择框
    markSelectFocus() {
      if (!this.addOfEditForm.property.length) {
        this.$message.error("请先选择产业");
      } else {
        let arr = this.addOfEditForm.property.map((item) => item[1]);
        raiInterface
          .getindustrialSubjectlistIds({
            IndustrialManagementIdStr: arr.join(","),
            ArticleId: this.articleId,
          })
          .then((res) => {
            if (res.Ret === 200) {
              this.markOptions = res.Data.List || [];
            }
          });
      }
    },
    // 子组件来的事件 产业
    commitIndustryDlg(data) {
      this.getIndustry();
      this.addOfEditForm.property.push([Number(data.ChartPermissionId), Number(data.NewId)]);
      this.$refs["addOfEditForm"].clearValidate();
    },
    // 子组件来的事件 标的
    commitMarkDlg(data) {
      raiInterface
        .getindustrialSubjectlistIds({
          IndustrialManagementIdStr: this.addMarkUpVal.industrialId,
        })
        .then((res) => {
          if (res.Ret === 200) {
            this.markOptions = res.Data.List || [];
          }
        });
      this.markValue = data.split(",").map((item) => Number(item));
    },
    /* 获取全部的行业 */
    getIndustry() {
      raiInterface.getListIndustrial().then((res) => {
        if (res.Ret === 200) {
          this.industryArr = res.Data.List || [];
        }
      });
    },
  },
  // 路由离开了 清除定时器
  beforeRouteLeave(to, from, next) {
    clearInterval(this.timeInterval);
    next();
  },
};
</script>
<style lang="scss">
.add-report-type {
  padding-left: 20px;
  display: flex;
  align-items: center;
  height: 34px;
  color: #409eff;
  cursor: pointer;
  img {
    margin-right: 5px;
  }
}
.container-summary {
  .card-top {
    .el-card__body {
      padding-bottom: 0 !important;
    }
    .el-form-item {
      display: inline-block;
      margin-right: 10px;
    }
    .inline-input {
      margin-right: 10px;
    }
    .el-input {
      width: 360px;
    }
  }
  .fr-second-toolbar {
    display: none;
  }
  .report-link {
    display: flex;
    align-items: center;
    .report-word {
      flex-shrink: 0;
    }
    .el-input {
      display: inline-block;
    }
  }
  #dialog {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    color: #333;
    font-size: 14px;
    div {
      margin-bottom: 40px;
    }
  }
  .box {
    display: flex;
    justify-content: space-between;
  }
  .form-item-bootm {
    margin-top: 50px;
    text-align: center;
    .el-button {
      margin-right: 20px;
    }
  }
  .no-cv {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
}
.fr-visible {
  display: none !important;
}
</style>
