<template>
  <div class="container-summary">
    <el-form :model="addOfEditForm" :rules="rulesOption" ref="addOfEditForm">
      <el-card class="card-top">
        <el-form-item prop="regions">
          <el-input placeholder="标题栏名称（限10字以内)" :maxlength="10" clearable v-model="addOfEditForm.regions" style="width: 360px"> </el-input>
        </el-form-item>
        <el-form-item prop="title">
          <el-input style="width: 360px" clearable v-model="addOfEditForm.title" placeholder="请输入报告标题"></el-input>
        </el-form-item>
        <el-form-item prop="publishTime">
          <el-date-picker style="width: 360px" v-model="addOfEditForm.publishTime" type="date" placeholder="请选择发布时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd"> </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input style="width: 360px" clearable v-model="addOfEditForm.department" placeholder="请输入作者(选填)"></el-input>
        </el-form-item>
        <el-form-item prop="industry">
          <el-select placeholder="请选择行业" style="width: 360px" clearable v-model="addOfEditForm.industry" @change="industryChangeHandler">
            <el-option v-for="item in chartPermissionList" :label="item.PermissionName" :key="item.ChartPermissionId" :value="item.ChartPermissionId" />
          </el-select>
        </el-form-item>
        <el-form-item prop="property">
          <el-select v-model="addOfEditForm.property" multiple placeholder="请选择关联产业（选填）" @change="propertyChangeHandler" clearable filterable style="width: 360px">
            <el-option :label="item.IndustryName" :value="item.IndustrialManagementId" v-for="item in selectedIndustryArr" :key="item.IndustrialManagementId" />
          </el-select>
        </el-form-item>
        <el-form-item prop="subject">
          <el-select v-model="addOfEditForm.subject" multiple placeholder="请选择关联标的（选填）" clearable filterable style="width: 360px">
            <el-option v-for="item in subjectData" :key="item.IndustrialSubjectId" :label="item.SubjectName" :value="item.IndustrialSubjectId" />
          </el-select>
        </el-form-item>
        <el-form-item prop="matchTypeName">
          <el-select v-model="addOfEditForm.matchTypeName" placeholder="请选择报告类型" clearable filterable style="width: 360px">
            <el-option v-for="item in matchTypeNameList" :label="item.MatchTypeName" :key="item.Id" :value="item.Id" />
          </el-select>
          <img src="~@/assets/img/set_m/add_ico.png" style="margin: 5px 0px 0 10px" @click="addMatchTypeDlgIsShow" />
        </el-form-item>
        <el-form-item>
          <el-input style="width: 755px" clearable v-model="addOfEditForm.synopsis" placeholder="请输入摘要(选填)"></el-input>
        </el-form-item>
        <froala id="froala-editor" ref="froalaEditor" :tag="'textarea'" :config="froalaConfig" v-model="addOfEditForm.content"></froala>
        <div class="form-item-bootm">
          <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>
        </div>
      </el-card>
    </el-form>
    <el-dialog v-dialogDrag :close-on-click-modal="false" :modal-append-to-body="false" center title="新建报告类型" :visible.sync="addMatchTypeDlg" :before-close="confirmMatchType" width="500px">
      <p style="margin-bottom: 10px">所属行业：{{ dlgTextRender }}</p>
      <el-form :model="addMatchTypeData" :rules="matchTypeRules" ref="addMatchTypeData">
        <el-form-item prop="type">
          <el-radio-group v-model="addMatchTypeData.type">
            <el-radio :label="2">产业报告</el-radio>
            <el-radio :label="1">行业综述报告</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="name">
          <el-input style="width: 100%" clearable v-model="addMatchTypeData.name" placeholder="输入类型名称"></el-input>
        </el-form-item>
      </el-form>
      <div class="form-item-bootm" style="margin-bottom: 30px">
        <el-button type="primary" @click="addMatchSubmitForm">确定</el-button>
        <el-button @click="confirmMatchType">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { raiInterface } from "@/api/api.js";
import RichTextMixins from "../../components/reportComponents/RichTextMixins";
export default {
  name: "",
  data() {
    return {
      addOfEditForm: {
        content: "",
        title: "",
        synopsis: "",
        department: "", // 作者
        regions: "",
        publishTime: "",
        industry: "", //行业
        property: [], //产业
        subject: [], // 标的
        matchTypeName: "", //报告类型
      },
      rulesOption: {
        regions: [{ required: true, message: "请输入标题栏名称（限10字以内）", trigger: "blur" }],
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        publishTime: [{ required: true, message: "请选择发布时间", trigger: "change" }],
        industry: [{ required: true, message: "请选择行业", trigger: "change" }],
        matchTypeName: [{ required: true, message: "请选择报告类型", trigger: "change" }],
      },
      chartPermissionList: [], //行业的数组
      selectedIndustryArr: [], //产业的数组
      subjectData: [], //标的的数组
      matchTypeNameList: [], //报告类型的数组
      isShowStatus: true,
      addMatchTypeDlg: false,
      addMatchTypeData: {
        name: "",
        type: "",
      },
      matchTypeRules: {
        name: [{ required: true, message: "输入类型名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型归属", trigger: "change" }],
      },
      dlgTextRender: "",
      timeInterval: null,
    };
  },
  mixins: [RichTextMixins],
  computed: {},
  created() {},
  mounted() {
    if (this.$route.query.id) {
      // 编辑进来的
      this.getDetail();
    } else {
      this.dataInit();
    }
    this.chartPermission();
  },
  methods: {
    // 报告的缓存处理数据
    dataInit() {
      if (sessionStorage.getItem("addHaveReportQY")) {
        let data = JSON.parse(sessionStorage.getItem("addHaveReportQY"));
        setTimeout(async () => {
          this.addOfEditForm = {
            regions: data.Detail.ColumnName,
            content: data.Detail.Body,
            title: data.Detail.Title,
            synopsis: data.Detail.Abstract,
            department: data.Detail.Department,
            publishTime: data.Detail.PublishTime,
            property: data.Detail.ListIndustrial,
            subject: data.Detail.ListSubject,
            industry: data.Detail.ChartPermissionId,
            matchTypeName: data.Detail.MatchTypeId,
          };
          this.isShowStatus = data.Detail.Status == 0;
          await this.industryChangeHandler();
          await this.propertyChangeHandler();
        }, 200);
      }
      this.timeInterval = setInterval(() => {
        let params = {
          PublishTime: this.addOfEditForm.publishTime,
          ColumnName: this.addOfEditForm.regions,
          Title: this.addOfEditForm.title,
          Abstract: this.addOfEditForm.synopsis,
          Department: this.addOfEditForm.department,
          Body: this.addOfEditForm.content,
          IndustrialManagementIds: this.addOfEditForm.property,
          IndustrialSubjectIds: this.addOfEditForm.subject,
          ChartPermissionId: this.addOfEditForm.industry,
          MatchTypeId: this.addOfEditForm.matchTypeName,
        };
        sessionStorage.setItem("addHaveReportQY", JSON.stringify(params));
      }, 120000);
    },
    // 产业的change事件
    propertyChangeHandler(val) {
      if (this.addOfEditForm.property && this.addOfEditForm.property.length) {
        if (val) {
          this.subjectData = [];
          this.addOfEditForm.subject = [];
        }
        this.getSubjectList();
      } else {
        this.subjectData = [];
        this.addOfEditForm.subject = [];
      }
    },
    // 行业的change事件
    industryChangeHandler(value) {
      if (this.addOfEditForm.industry) {
        if (value) {
          this.industryDataInit();
        }
        this.getIndustryList();
        this.getMatchTypeNameList();
        this.chartPermissionList.forEach((item) => item.ChartPermissionId === this.addOfEditForm.industry && (this.dlgTextRender = item.PermissionName));
      } else {
        this.industryDataInit();
      }
    },
    // 行业的筛选框发生change事件后 清理联动的数据
    industryDataInit() {
      this.selectedIndustryArr = [];
      this.addOfEditForm.property = "";
      //关联报告
      this.matchTypeNameList = [];
      this.addOfEditForm.matchTypeName = "";
      this.dlgTextRender = "";
      this.subjectData = [];
      this.addOfEditForm.subject = [];
    },
    //添加报告类型
    addMatchTypeDlgIsShow() {
      if (!this.addOfEditForm.industry) return this.$message.error("请先选择行业");
      this.addMatchTypeDlg = true;
    },
    //获取报告类型
    async getMatchTypeNameList() {
      const res = await raiInterface.reportMappingMatchTypeRep({
        ChartPermissionId: this.addOfEditForm.industry,
      });
      if (res.Ret !== 200) return;
      this.matchTypeNameList = res.Data.List || [];
    },
    // 获取标的
    async getSubjectList() {
      const res = await raiInterface.getindustrialSubjectlistIds({
        IndustrialManagementIdStr: this.addOfEditForm.property.join(","),
      });
      if (res.Ret === 200) {
        this.subjectData = res.Data.List || [];
      }
    },
    // 获取产业
    async getIndustryList() {
      const res = await raiInterface.getIndustrialManagement({
        ChartPermissionId: this.addOfEditForm.industry,
      });
      if (res.Ret === 200) {
        this.selectedIndustryArr = res.Data.List || [];
      }
    },
    //获取行业
    async chartPermission() {
      const res = await raiInterface.reportChartPermissionFirstProduct();
      if (res.Ret === 200) {
        this.chartPermissionList = res.Data.List || [];
      }
    },
    //进来编辑的 获取内容的事件
    async getDetail() {
      const res = await raiInterface.internalProductInteriorDetail({
        ProductInteriorId: Number(this.$route.query.id),
      });
      if (res.Ret !== 200) return;
      this.addOfEditForm = {
        regions: res.Data.Detail.ColumnName,
        content: res.Data.Detail.Body,
        title: res.Data.Detail.Title,
        synopsis: res.Data.Detail.Abstract,
        department: res.Data.Detail.Department,
        publishTime: res.Data.Detail.PublishTime,
        property: res.Data.Detail.ListIndustrial ? res.Data.Detail.ListIndustrial.map((item) => item.IndustrialManagementId) : [],
        subject: res.Data.Detail.ListSubject ? res.Data.Detail.ListSubject.map((item) => item.IndustrialSubjectId) : [],
        industry: res.Data.Detail.ChartPermissionId,
        matchTypeName: res.Data.Detail.MatchTypeId,
      };
      this.isShowStatus = res.Data.Detail.Status == 0;
      await this.industryChangeHandler();
      await this.propertyChangeHandler();
    },
    //表单保存发布事件
    submitForm: _.debounce(async function (type) {
      this.$refs.addOfEditForm.validate(async (valid) => {
        if (valid) {
          let params = {
            ProductInteriorId: this.$route.query.id ? Number(this.$route.query.id) : 0,
            DoType: type == "保存" ? 0 : 1,
            PublishTime: this.addOfEditForm.publishTime,
            ColumnName: this.addOfEditForm.regions,
            Title: this.addOfEditForm.title,
            Abstract: this.addOfEditForm.synopsis,
            Department: this.addOfEditForm.department,
            Body: this.addOfEditForm.content.replace(/<p data-f-id=\"pbf\".*?<\/p>/g, ""),
            IndustrialManagementIds: this.addOfEditForm.property ? this.addOfEditForm.property.join(",") : "",
            IndustrialSubjectIds: this.addOfEditForm.subject ? this.addOfEditForm.subject.join(",") : "",
            ChartPermissionId: this.addOfEditForm.industry,
            MatchTypeId: this.addOfEditForm.matchTypeName,
          };
          const res = await raiInterface.internalPreserveAndPublish(params);
          if (res.Ret === 200) {
            this.$message.success("操作成功！");
            clearInterval(this.timeInterval);
            sessionStorage.removeItem("addHaveReportQY");
            this.$refs.addOfEditForm.resetFields();
            this.$router.push("/internalTesting");
          }
        }
      });
    }, 500),
    //表单取消事件
    cancelBtn() {
      clearInterval(this.timeInterval);
      sessionStorage.removeItem("addHaveReportQY");
      this.$refs.addOfEditForm.resetFields();
      this.$router.push("/internalTesting");
    },
    // 新增报告类型的确定事件
    addMatchSubmitForm() {
      this.$refs.addMatchTypeData.validate(async (valid) => {
        if (valid) {
          console.log("ok");
          const res = await raiInterface.reportMappingAdd({
            ReportType: this.addMatchTypeData.type,
            MatchTypeName: this.addMatchTypeData.name,
            ChartPermissionId: this.addOfEditForm.industry,
            ChartPermissionName: this.dlgTextRender,
          });
          if (res.Ret === 200) {
            await this.getMatchTypeNameList();
            this.$message.success("添加成功");
            this.addOfEditForm.matchTypeName = res.Data.Id;
            this.confirmMatchType();
          }
        }
      });
    },
    //关闭弹框事件
    confirmMatchType() {
      this.addMatchTypeDlg = false;
      this.$refs.addMatchTypeData.resetFields();
      this.addMatchTypeData = {
        name: "",
        type: "",
      };
    },
  },
  // 路由离开了 清除定时器
  beforeRouteLeave(to, from, next) {
    clearInterval(this.timeInterval);
    next();
  },
};
</script>
<style scoped lang="scss">
.container-summary {
  .card-top {
    .el-card__body {
      padding-bottom: 0 !important;
    }
    .el-form-item {
      display: inline-block;
      margin-right: 30px;
    }
    .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;
    }
  }
  .form-item-bootm {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 50px;
    .el-button {
      margin-right: 20px;
    }
  }
}
</style>
