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

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

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

const pageState = reactive({
  ruleForm: {
    title: "", //标题
    author: "", //作者
    time: "", //时间
    explain: "", //说明
    alteration: "", //变更
  },
  rules: {
    title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    author: [{ required: true, message: "请输入作者", trigger: "blur" }],
    time: [{ required: true, message: "请输入时间", trigger: "change" }],
    explain: [{ required: true, message: "请输入摘要", trigger: "blur" }],
  },
  //产业调研纪要篇
  ListCydyjy: [],
  SortCydyjy: "",
  //上市公司调研纪要篇
  ListSsgs: [],
  SortSsgs: "",
  //产业调研纪要篇 上市公司调研纪要篇 输入框是否高亮
  isSortCydyjyShow: true,
  isSortSsgsShow: true,
  //深度报告篇
  ListSdbg: [],
  SortSdbg: "",
  //本周晨会精华
  ListBzchjh: [],
  SortBzchjh: "",
  //事件点评
  ListSjdp: [],
  SortSjdp: "",
  isShowStatus: true,
  isSortSdbgShow: true,
  isSortBzchjhShow: true,
  isSortSjdpShow: true,
});

function beforeunloadFn(e) {
  e = e || window.event;
  if (e) {
    e.returnValue = "关闭提示";
  }
  return "关闭提示";
}

//获取模板
async function getList() {
  const res = await raiInterface.chartPermissiondetailTemplate();
  if (res.Ret === 200) {
    pageState.ListSdbg = res.Data.ListSdbg;
    pageState.ListCydyjy = res.Data.ListCydyjy;
    pageState.ListBzchjh = res.Data.ListBzchjh;
    pageState.ListSsgs = res.Data.ListSsgs;
    pageState.SortBzchjh = res.Data.SortBzchjh;
    pageState.SortCydyjy = res.Data.SortCydyjy;
    pageState.SortSdbg = res.Data.SortSdbg;
    pageState.SortSsgs = res.Data.SortSsgs;
  }
}

//事件点评 添加
function addListSjdp(item, indx) {
  pageState.ListSjdp.push({ Body: "", ReportLink: "" });
}
//事件点评 删除
function deleteListSjdp(item, index) {
  pageState.ListSjdp.splice(index, 1);
}
//获取详情
async function getDetail() {
  const res = await raiInterface.researchSummaryDetail({
    ArticleId: $route.query.id,
  });
  if (res.Ret === 200) {
    pageState.isShowStatus = res.Data.PublishStatus == 0;
    initGetList(res.Data.ListSdbg);
    initGetList(res.Data.ListCydyjy);
    initGetList(res.Data.ListBzchjh);
    initGetList(res.Data.ListSsgs);
    pageState.ListSdbg = res.Data.ListSdbg;
    pageState.ListCydyjy = res.Data.ListCydyjy;
    pageState.ListBzchjh = res.Data.ListBzchjh;
    pageState.ListSsgs = res.Data.ListSsgs;
    pageState.ListSjdp = res.Data.ListSjdp || [];
    pageState.SortBzchjh = res.Data.SortBzchjh;
    pageState.SortCydyjy = res.Data.SortCydyjy;
    pageState.SortSdbg = res.Data.SortSdbg;
    pageState.SortSjdp = res.Data.SortSjdp;
    pageState.SortSsgs = res.Data.SortSsgs;
    pageState.ruleForm = {
      title: res.Data.Title, //标题
      author: res.Data.Department, //作者
      time: res.Data.PublishDate, //时间
      explain: res.Data.Abstract, //说明
    };
  }
}
const ruleFormRef = ref(null);
//保存 发布
const confirm = _.debounce(function (type) {
  ruleFormRef.value.validate(async (val) => {
    if (!val) return;
    const isFlag = await fnConFirm();
    if (isFlag) return;
    let params = {
      Abstract: pageState.ruleForm.explain,
      ArticleId: $route.query.id ? Number($route.query.id) : 0,
      Department: pageState.ruleForm.author,
      DoType: type == "发布" ? 1 : 0,
      PublishDate: pageState.ruleForm.time.replace(/\./g, "-"),
      Title: pageState.ruleForm.title,
      Content: {
        ListBzchjh: pageState.ListBzchjh,
        ListCydyjy: pageState.ListCydyjy,
        ListSdbg: pageState.ListSdbg,
        ListSjdp: pageState.ListSjdp,
        ListSsgs: pageState.ListSsgs,
        SortBzchjh: pageState.SortBzchjh,
        SortCydyjy: pageState.SortCydyjy,
        SortSdbg: pageState.SortSdbg,
        SortSjdp: pageState.SortSjdp,
        SortSsgs: pageState.SortSsgs,
      },
    };
    if (type == "预览") {
      sessionStorage.setItem("pageStateWeekPre", JSON.stringify(params));
      let { href } = $router.resolve({ name: "thisWeekSummary" });
      window.open(href, "_blank");
    } else {
      const res = await raiInterface.researchSummaryPreserveAndPublish(params);
      if (res.Ret === 200) {
        ElMessage.success(`${type}成功!`);
        ruleFormRef.value.resetFields();
        $router.back();
      }
    }
  });
}, 500);
function fnConFirm() {
  let flag = false;
  let isSdbg = pageState.ListSdbg.some((item) => item.List.length > 0); //深度报告篇
  let isCydyjy = pageState.ListCydyjy.some((item) => item.List.length > 0); //产业调研
  let Bzchjh = pageState.ListBzchjh.some((item) => item.List.length > 0); //本周晨选
  let Ssgs = pageState.ListSsgs.some((item) => item.List.length > 0); //上司公司
  pageState.isSortSdbgShow = !(isSdbg && !pageState.SortSdbg);
  pageState.isSortCydyjyShow = !(isCydyjy && !pageState.SortCydyjy);
  pageState.isSortBzchjhShow = !(Bzchjh && !pageState.SortBzchjh);
  pageState.isSortSsgsShow = !(Ssgs && !pageState.SortSsgs); //上司公司
  pageState.isSortSjdpShow = !(pageState.ListSjdp.length !== 0 && !pageState.SortSjdp);
  if ((isSdbg && !pageState.SortSdbg) || (isCydyjy && !pageState.SortCydyjy) || (Bzchjh && !pageState.SortBzchjh) || (pageState.ListSjdp.length !== 0 && !pageState.SortSjdp)) {
    ElMessage.warning("有内容的报告分类和行业分类，序号不能为空");
    return (flag = true);
  }
  let str = new Array(pageState.SortSdbg, pageState.SortCydyjy, pageState.SortBzchjh, pageState.SortSjdp, pageState.SortSsgs);
  let isStr = str.sort();
  for (var i = 0; i < isStr.length - 1; i++) {
    if (isStr[i] == isStr[i + 1] && (isStr[i] || isStr[i + 1])) {
      ElMessage.warning("请勿填写重复的序号!");
      return (flag = true);
    }
  }
  let chidrenSdbg = chidrenList(pageState.ListSdbg);
  let chidrenCydyjy = chidrenList(pageState.ListCydyjy);
  let chidrenBzchjh = chidrenList(pageState.ListBzchjh);
  let chidrenSsgs = chidrenList(pageState.ListSsgs);
  if (chidrenSdbg || chidrenCydyjy || chidrenBzchjh || chidrenSsgs) {
    ElMessage.warning("有内容行业分类，序号不能为空");
    return (flag = true);
  }
}
function initGetList(list) {
  list.forEach((item) => {
    if (!item.List) {
      item.List = [];
    }
  });
}
//取消
function cancel() {
  ruleFormRef.value.resetFields();
  $router.back();
}

onMounted(() => {
  window.addEventListener("beforeunload", beforeunloadFn);
  if ($route.query.id) {
    getDetail();
  } else {
    getList();
  }
});

onUnmounted(() => {
  window.removeEventListener("beforeunload", beforeunloadFn);
});

const {
  ruleForm,
  rules,
  //产业调研纪要篇
  ListCydyjy,
  SortCydyjy,
  //上市公司调研纪要篇
  ListSsgs,
  SortSsgs,
  //产业调研纪要篇 上市公司调研纪要篇 输入框是否高亮
  isSortCydyjyShow,
  isSortSsgsShow,
  //深度报告篇
  ListSdbg,
  SortSdbg,
  //本周晨会精华
  ListBzchjh,
  SortBzchjh,
  //事件点评
  ListSjdp,
  SortSjdp,
  isShowStatus,
  isSortSdbgShow,
  isSortBzchjhShow,
  isSortSjdpShow,
} = toRefs(pageState);
</script>

<template>
  <!-- 本周研究汇总添加/编辑 -->
  <div class="add-summarizing">
    <el-card>
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" class="demo-ruleForm">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="title">
              <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="author">
              <el-input v-model="ruleForm.author" placeholder="请输入作者"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="time">
              <el-date-picker type="date" placeholder="选择发布时间" value-format="YYYY-MM-DD" v-model="ruleForm.time"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="explain">
          <el-input v-model="ruleForm.explain" placeholder="请输入摘要"></el-input>
        </el-form-item>
      </el-form>
      <!-- //深度报告篇 -->
      <div class="content-list">
        <div class="list-top">
          <span>深度报告篇</span>
          <input maxlength="1" :class="isSortSdbgShow ? '' : 'red'" v-model="SortSdbg" placeholder="序号" onkeyup="value=value.replace(/[^A-Z]/g,'')" />
          <el-tooltip class="item" placement="top-start">
            <template #content>
              <div>
                一级分类的序号请以大写字母A\B\C\D...排序 <br />
                二级分类请以1\2\3\4...排序
              </div>
              <el-icon><InfoFilled /></el-icon>
            </template>
          </el-tooltip>
        </div>
        <div class="list-ul" v-for="(item, index) in ListSdbg" :key="item.ChartPermissionId">
          <div class="list-title">
            <img :src="item.IcoLink" alt="" />
            <span>{{ item.ChartPermissionName }}</span>
            <input maxlength="1" :class="item.isShow ? 'red' : ''" placeholder="序号" v-model="item.ChartPermissionSort" onkeyup="value=value.replace(/[^\d]/g,'')" />
          </div>
          <div class="list-li">
            <div v-for="(val, num) in item.List" :key="num" class="list-children">
              <div class="box">
                <RichText v-model="val.Body" :spareId="num + 'froalaCy'" isText="请输入文字描述" />
                <el-input v-model="val.ReportLink" placeholder="请输入报告链接"></el-input>
              </div>
              <img @click="deleteListSdbg(item, num, index, '深度报告篇')" src="~@/assets/img/icons/delete-Item.png" />
            </div>
            <p @click="addListSdbg(item, index, '深度报告篇')" :class="item.List && item.List.length > 0 ? 'active' : ''">+添加栏目</p>
          </div>
        </div>
      </div>
      <!-- //产业调研纪要篇 -->
      <div class="content-list">
        <div class="list-top">
          <span>产业调研纪要篇</span>
          <input maxlength="1" :class="isSortCydyjyShow ? '' : 'red'" v-model="SortCydyjy" placeholder="序号" onkeyup="value=value.replace(/[^A-Z]/g,'')" />
        </div>
        <div class="list-ul" v-for="(item, index) in ListCydyjy" :key="item.ChartPermissionId">
          <div class="list-title">
            <img :src="item.IcoLink" alt="" />
            <span>{{ item.ChartPermissionName }}</span>
            <input maxlength="1" placeholder="序号" :class="item.isShow ? 'red' : ''" v-model="item.ChartPermissionSort" onkeyup="value=value.replace(/[^\d]/g,'')" />
          </div>
          <div class="list-li">
            <div v-for="(val, num) in item.List" :key="num" class="list-children">
              <div class="box">
                <!-- <el-input type="textarea" :rows="4" placeholder="请输入文字描述" v-model="val.Body"></el-input> -->
                <froala :id="num + 'froalaCy'" :ref="num + 'froalaCy'" :tag="'textarea'" :config="froalaConfig" v-model="val.Body"></froala>
                <el-input v-model="val.ReportLink" placeholder="请输入报告链接"></el-input>
              </div>
              <img @click="deleteListSdbg(item, num, index, '产业调研纪要篇')" src="~@/assets/img/icons/delete-Item.png" />
            </div>
            <p @click="addListSdbg(item, index, '产业调研纪要篇')" :class="item.List && item.List.length > 0 ? 'active' : ''">+添加栏目</p>
          </div>
        </div>
      </div>
      <!-- //上市公司调研纪要篇 -->
      <div class="content-list">
        <div class="list-top">
          <span>上市公司调研纪要篇</span>
          <input maxlength="1" :class="isSortSsgsShow ? '' : 'red'" v-model="SortSsgs" placeholder="序号" onkeyup="value=value.replace(/[^A-Z]/g,'')" />
        </div>
        <div class="list-ul" v-for="(item, index) in ListSsgs" :key="item.ChartPermissionId">
          <div class="list-title">
            <img :src="item.IcoLink" alt="" />
            <span>{{ item.ChartPermissionName }}</span>
            <input maxlength="1" placeholder="序号" :class="item.isShow ? 'red' : ''" v-model="item.ChartPermissionSort" onkeyup="value=value.replace(/[^\d]/g,'')" />
          </div>
          <div class="list-li">
            <div v-for="(val, num) in item.List" :key="num" class="list-children">
              <div class="box">
                <!-- <el-input type="textarea" :rows="4" placeholder="请输入文字描述" v-model="val.Body"></el-input> -->
                <froala :id="num + 'froalaCy'" :ref="num + 'froalaCy'" :tag="'textarea'" :config="froalaConfig" v-model="val.Body"></froala>
                <el-input v-model="val.ReportLink" placeholder="请输入报告链接"></el-input>
              </div>
              <img @click="deleteListSdbg(item, num, index, '上市公司调研纪要篇')" src="~@/assets/img/icons/delete-Item.png" />
            </div>
            <p @click="addListSdbg(item, index, '上市公司调研纪要篇')" :class="item.List && item.List.length > 0 ? 'active' : ''">+添加栏目</p>
          </div>
        </div>
      </div>
      <!-- //事件点评 -->
      <div class="content-list">
        <div class="list-top">
          <span>市场QA汇总</span>
          <input maxlength="1" :class="isSortSjdpShow ? '' : 'red'" v-model="SortSjdp" placeholder="序号" onkeyup="value=value.replace(/[^A-Z]/g,'')" />
        </div>
        <div class="list-ul">
          <div class="list-li">
            <div v-for="(item, index) in ListSjdp" :key="index" class="list-children">
              <div class="box">
                <froala :id="item + 'froalaDp'" :ref="item + 'froalaDp'" :tag="'textarea'" :config="froalaConfig" v-model="item.Body"></froala>
                <el-input v-model="item.ReportLink" :class="item.isShow ? 'red' : ''" placeholder="请输入报告链接"></el-input>
              </div>
              <img @click="deleteListSjdp(item, index)" src="~@/assets/img/icons/delete-Item.png" />
            </div>
            <p @click="addListSjdp(item, index)" :class="ListSjdp && ListSjdp.length > 0 ? 'active' : ''">+添加栏目</p>
          </div>
        </div>
      </div>
      <!-- //本周晨会精华 -->
      <div class="content-list">
        <div class="list-top">
          <span>本周晨会精华</span>
          <input maxlength="1" :class="isSortBzchjhShow ? '' : 'red'" v-model="SortBzchjh" placeholder="序号" onkeyup="value=value.replace(/[^A-Z]/g,'')" />
        </div>
        <div class="list-ul" v-for="(item, index) in ListBzchjh" :key="item.ChartPermissionId">
          <div class="list-title">
            <img :src="item.IcoLink" alt="" />
            <span>{{ item.ChartPermissionName }}</span>
            <input maxlength="1" placeholder="序号" :class="item.isShow ? 'red' : ''" v-model="item.ChartPermissionSort" onkeyup="value=value.replace(/[^\d]/g,'')" />
          </div>
          <div class="list-li">
            <div v-for="(val, num) in item.List" :key="num" class="list-children">
              <div class="box">
                <froala :id="num + 'froalaJh'" :ref="num + 'froalaJh'" :tag="'textarea'" :config="froalaConfig" v-model="val.Body"></froala>
                <el-input v-model="val.ReportLink" placeholder="请输入报告链接"></el-input>
              </div>
              <img @click="deleteListSdbg(item, num, index, '本周晨会精华')" src="~@/assets/img/icons/delete-Item.png" />
            </div>
            <p @click="addListSdbg(item, index, '本周晨会精华')" :class="item.List && item.List.length > 0 ? 'active' : ''">+添加栏目</p>
          </div>
        </div>
      </div>
      <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 scoped lang="scss">
.add-summarizing {
  @import "./selection/strictSelection.scss";
}
</style>
