<script setup>
import { ref, onMounted, reactive, toRefs, watch } from "vue";

import RichText from "./richText.vue";
import _ from "lodash";
import { raiInterface } from "@/api/api.js";
import { Calendar, Search, InfoFilled } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { onBeforeRouteLeave, useRouter, useRoute } from "vue-router";

const $route = useRoute();
const $router = useRouter();

const pageState = reactive({
  listForm: {
    title: "", //标题
    author: "", //作者
    time: "", //时间
    industry: "", //行业
    property: [], //产业
    target: [], //标的
    abstract: "",
    reportLink: "",
  },
  property: [],
  rules: {
    title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    author: [{ required: true, message: "请输入作者", trigger: "blur" }],
    time: [{ required: true, message: "请输入标题", trigger: "change" }],
    industry: [{ required: true, message: "请选择行业", trigger: "change" }],
    property: [{ required: true, message: "请选择所属产业", trigger: "change" }],
    target: [{ required: true, message: "请选择关联标的", trigger: "change" }],
  },
  optionsIndustry: [],
  optionsProperty: [],
  optionsTarget: [],
  contentValue: "请输入内容",
  propertyDetai: [],
  isShowStatus: true,
  timeInterval: null,
  richTetxValue: "", //
});

// 报告的缓存处理数据
function dataInit() {
  if (sessionStorage.getItem("addRoadshowReportQY")) {
    let data = JSON.parse(sessionStorage.getItem("addRoadshowReportQY"));
    setTimeout(async () => {
      pageState.listForm = {
        title: data.Title, //标题
        author: data.SellerAndMobile, //作者
        time: data.PublishDate, //时间
        industry: data.ChartPermissionId, //行业
        abstract: data.Abstract,
        reportLink: data.ReportLink,
        property: data.IndustrialManagementId,
        target: data.IndustrialSubjectIdStr,
      };
      pageState.richTetxValue = data.Body;
      if (pageState.listForm.industry) {
        await getPropertyList();
        await getTargetList();
      }
    }, 200);
  }
  pageState.timeInterval = setInterval(() => {
    let params = {
      Abstract: pageState.listForm.abstract,
      Body: pageState.richTetxValue,
      ChartPermissionId: pageState.listForm.industry,
      IndustrialManagementId: pageState.listForm.property,
      IndustrialSubjectIdStr: pageState.listForm.target,
      ReportLink: pageState.listForm.reportLink,
      PublishDate: pageState.listForm.time,
      SellerAndMobile: pageState.listForm.author,
      Title: pageState.listForm.title,
    };
    sessionStorage.setItem("addRoadshowReportQY", JSON.stringify(params));
  }, 120000);
}
// 获取数据
async function getDetail() {
  const res = await raiInterface.roadshowEssenceDetail({ ArticleId: Number($route.query.id) });
  if (res.Ret === 200) {
    pageState.isShowStatus = res.Data.PublishStatus == 0;
    pageState.listForm = {
      title: res.Data.Title, //标题
      author: res.Data.SellerAndMobile, //作者
      time: res.Data.PublishDate, //时间
      industry: res.Data.ChartPermissionId > 0 ? res.Data.ChartPermissionId : "", //行业
      abstract: res.Data.Abstract,
      reportLink: res.Data.ReportLink,
      property: res.Data.IndustrialManagementId ? res.Data.IndustrialManagementId.split(",").map((item) => Number(item)) : [],
      target: res.Data.IndustrialSubjectIdStr ? res.Data.IndustrialSubjectIdStr.split(",").map((item) => Number(item)) : [],
    };
    pageState.richTetxValue = res.Data.Body;
    if (pageState.listForm.industry) {
      await getPropertyList();
      await getTargetList();
    }
  }
}
//获取行业
async function getIndustryList() {
  const res = await raiInterface.chartPermissionFirstHaveIco();
  if (res.Ret === 200) {
    pageState.optionsIndustry = res.Data.List || [];
  }
}
//获取产业
async function getPropertyList() {
  const str = pageState.listForm.industry;
  if (!str) return;
  const res = await raiInterface.getIndustrialManagement({ ChartPermissionId: str });
  if (res.Ret === 200) {
    pageState.optionsProperty = res.Data.List || [];
  }
}
//获取标的
async function getTargetList() {
  const str = pageState.listForm.property.join(",");
  if (!str) return;
  const res = await raiInterface.getindustrialSubjectlistIds({ IndustrialManagementIdStr: str });
  if (res.Ret === 200) {
    pageState.optionsTarget = res.Data.List || [];
  }
}

const ruleFormRef = ref(null);
//保存 / 发布
const confirm = _.debounce(function (type) {
  ruleFormRef.value.validate(async (value) => {
    if (value) {
      let params = {
        Abstract: pageState.listForm.abstract,
        Body: pageState.richTetxValue,
        ChartPermissionId: pageState.listForm.industry,
        IndustrialManagementId: pageState.listForm.property.join(","),
        IndustrialSubjectIdStr: pageState.listForm.target.join(","),
        ReportLink: pageState.listForm.reportLink,
        PublishDate: pageState.listForm.time,
        SellerAndMobile: pageState.listForm.author,
        Title: pageState.listForm.title,
        DoType: type == "发布" ? 1 : 0,
        ArticleId: $route.query.id ? Number($route.query.id) : 0,
      };
      if (type == "预览") {
        sessionStorage.setItem("roadShowPre", JSON.stringify(params));
        let { href } = $router.resolve({ name: "roadshowPre" });
        window.open(href, "_blank");
      } else {
        const res = await raiInterface.roadshowEssencePreserveAndPublish(params);
        if (res.Ret === 200) {
          ElMessage.success(`${type}成功!`);
          ruleFormRef.value.resetFields();
          clearInterval(pageState.timeInterval);
          sessionStorage.removeItem("addRoadshowReportQY");
          $router.back();
        }
      }
    }
  });
}, 500);
function industryClear() {
  pageState.listForm.property = [];
  pageState.optionsProperty = [];
  pageState.listForm.target = [];
  pageState.optionsTarget = [];
}
function propertyClear() {
  pageState.listForm.target = [];
  pageState.optionsTarget = [];
}
//取消事件
function cancel() {
  clearInterval(pageState.timeInterval);
  sessionStorage.removeItem("addRoadshowReportQY");
  ruleFormRef.value.resetFields();
  $router.back();
}

onMounted(() => {
  getIndustryList();
  if ($route.query.id) {
    getDetail();
  } else {
    dataInit();
  }
});

onBeforeRouteLeave((to, from, next) => {
  clearInterval(pageState.timeInterval);
  next();
});
const { listForm, property, rules, optionsIndustry, optionsProperty, optionsTarget, contentValue, propertyDetai, isShowStatus, timeInterval, richTetxValue } = toRefs(pageState);
</script>

<template>
  <!-- 路演精华添加/编辑 -->
  <div class="add-roadshow">
    <el-card>
      <el-form :model="listForm" :rules="rules" ref="ruleFormRef" class="demo-ruleForm">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="title">
              <el-input placeholder="请输入标题" v-model="listForm.title" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="author">
              <el-input placeholder="请输入作者" v-model="listForm.author" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="time">
              <el-date-picker v-model="listForm.time" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD"> </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px" :gutter="24">
          <el-col :span="12">
            <el-form-item prop="industry">
              <el-select v-model="listForm.industry" value-key="ChartPermissionId" clearable placeholder="请选择行业" @change="industryClear" @clear="industryClear">
                <el-option v-for="item in optionsIndustry" :key="item.ChartPermissionId" :label="item.PermissionName" :value="item.ChartPermissionId"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="property">
              <el-select v-model="listForm.property" value-key="IndustrialManagementId" multiple placeholder="请选择所属产业" @focus="getPropertyList" @remove-tag="propertyClear">
                <el-option v-for="item in optionsProperty" :key="item.IndustrialManagementId" :label="item.IndustryName" :value="item.IndustrialManagementId"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="property">
              <el-select v-model="listForm.target" multiple placeholder="请选择关联标的" @focus="getTargetList">
                <el-option v-for="item in optionsTarget" :key="item.IndustrialSubjectId" :label="item.SubjectName" :value="item.IndustrialSubjectId"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="margin-top: 10px">
          <el-input type="textarea" :rows="4" placeholder="请输入摘要" v-model="listForm.abstract"> </el-input>
        </div>
        <div style="margin: 30px 0">
          <RichText spareId="twoRich" :isText="contentValue" v-model="richTetxValue" />
        </div>
        <div class="content-link">
          <div class="txt">报告链接：</div>
          <div class="input">
            <el-input placeholder="请输入报告链接" v-model="listForm.reportLink" />
          </div>
        </div>
      </el-form>
      <div class="more-button">
        <el-button type="primary" @click="confirm('预览')">预览</el-button>
        <el-button type="primary" @click="confirm('保存')">保存</el-button>
        <el-button v-if="isShowStatus" type="primary" @click="confirm('发布')">发布</el-button>
        <el-button type="" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss">
.add-roadshow {
  .el-date-editor.el-input,
  .el-select {
    width: 100%;
  }
  .content-link {
    display: flex;
    align-items: center;
    .txt {
      width: 92px;
      color: #333333;
      font-size: 16px;
    }
    .input {
      flex: 1;
    }
  }
  .more-button {
    width: 100%;
    text-align: center;
    margin: 60px 0 80px;
    .el-button {
      height: 40px;
      padding: 0 30px;
      margin-right: 20px;
    }
  }
}
</style>
