<script setup>
import { ref, onMounted, reactive, toRefs, watch } from "vue";
import { Calendar, Search, InfoFilled } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { onBeforeRouteLeave, useRouter, useRoute } from "vue-router";
import { raiInterface } from "@/api/api.js";
import _ from "lodash";

import RichText from "../../components/richText.vue";

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

const pageState = reactive({
  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,
});

// 报告的缓存处理数据
function dataInit() {
  if (sessionStorage.getItem("addHaveReportQY")) {
    let data = JSON.parse(sessionStorage.getItem("addHaveReportQY"));
    setTimeout(async () => {
      pageState.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,
      };
      pageState.isShowStatus = data.Detail.Status == 0;
      await industryChangeHandler();
      await propertyChangeHandler();
    }, 200);
  }
  pageState.timeInterval = setInterval(() => {
    let params = {
      PublishTime: pageState.addOfEditForm.publishTime,
      ColumnName: pageState.addOfEditForm.regions,
      Title: pageState.addOfEditForm.title,
      Abstract: pageState.addOfEditForm.synopsis,
      Department: pageState.addOfEditForm.department,
      Body: pageState.addOfEditForm.content,
      IndustrialManagementIds: pageState.addOfEditForm.property,
      IndustrialSubjectIds: pageState.addOfEditForm.subject,
      ChartPermissionId: pageState.addOfEditForm.industry,
      MatchTypeId: pageState.addOfEditForm.matchTypeName,
    };
    sessionStorage.setItem("addHaveReportQY", JSON.stringify(params));
  }, 120000);
}
// 产业的change事件
function propertyChangeHandler(val) {
  if (pageState.addOfEditForm.property && pageState.addOfEditForm.property.length) {
    if (val) {
      pageState.subjectData = [];
      pageState.addOfEditForm.subject = [];
    }
    getSubjectList();
  } else {
    pageState.subjectData = [];
    pageState.addOfEditForm.subject = [];
  }
}
// 行业的change事件
function industryChangeHandler(value) {
  if (pageState.addOfEditForm.industry) {
    if (value) {
      industryDataInit();
    }
    getIndustryList();
    getMatchTypeNameList();
    pageState.chartPermissionList.forEach((item) => item.ChartPermissionId === pageState.addOfEditForm.industry && (pageState.dlgTextRender = item.PermissionName));
  } else {
    industryDataInit();
  }
}
// 行业的筛选框发生change事件后 清理联动的数据
function industryDataInit() {
  pageState.selectedIndustryArr = [];
  pageState.addOfEditForm.property = "";
  //关联报告
  pageState.matchTypeNameList = [];
  pageState.addOfEditForm.matchTypeName = "";
  pageState.dlgTextRender = "";
  pageState.subjectData = [];
  pageState.addOfEditForm.subject = [];
}
//添加报告类型
function addMatchTypeDlgIsShow() {
  if (!pageState.addOfEditForm.industry) return ElMessage.error("请先选择行业");
  pageState.addMatchTypeDlg = true;
}
//获取报告类型
async function getMatchTypeNameList() {
  const res = await raiInterface.reportMappingMatchTypeRep({
    ChartPermissionId: pageState.addOfEditForm.industry,
  });
  if (res.Ret !== 200) return;
  pageState.matchTypeNameList = res.Data.List || [];
}
// 获取标的
async function getSubjectList() {
  const res = await raiInterface.getindustrialSubjectlistIds({
    IndustrialManagementIdStr: pageState.addOfEditForm.property.join(","),
  });
  if (res.Ret === 200) {
    pageState.subjectData = res.Data.List || [];
  }
}
// 获取产业
async function getIndustryList() {
  const res = await raiInterface.getIndustrialManagement({
    ChartPermissionId: pageState.addOfEditForm.industry,
  });
  if (res.Ret === 200) {
    pageState.selectedIndustryArr = res.Data.List || [];
  }
}
//获取行业
async function chartPermission() {
  const res = await raiInterface.reportChartPermissionFirstProduct();
  if (res.Ret === 200) {
    pageState.chartPermissionList = res.Data.List || [];
  }
}
//进来编辑的 获取内容的事件
async function getDetail() {
  const res = await raiInterface.internalProductInteriorDetail({
    ProductInteriorId: Number($route.query.id),
  });
  if (res.Ret !== 200) return;
  pageState.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,
  };
  pageState.isShowStatus = res.Data.Detail.Status == 0;
  await industryChangeHandler();
  await propertyChangeHandler();
}

const addOfEditFormRef = ref(null);

//表单保存发布事件
const submitForm = _.debounce(async function (type) {
  addOfEditFormRef.value.validate(async (valid) => {
    if (valid) {
      let params = {
        ProductInteriorId: $route.query.id ? Number($route.query.id) : 0,
        DoType: type == "保存" ? 0 : 1,
        PublishTime: pageState.addOfEditForm.publishTime,
        ColumnName: pageState.addOfEditForm.regions,
        Title: pageState.addOfEditForm.title,
        Abstract: pageState.addOfEditForm.synopsis,
        Department: pageState.addOfEditForm.department,
        Body: pageState.addOfEditForm.content.replace(/<p data-f-id=\"pbf\".*?<\/p>/g, ""),
        IndustrialManagementIds: pageState.addOfEditForm.property ? pageState.addOfEditForm.property.join(",") : "",
        IndustrialSubjectIds: pageState.addOfEditForm.subject ? pageState.addOfEditForm.subject.join(",") : "",
        ChartPermissionId: pageState.addOfEditForm.industry,
        MatchTypeId: pageState.addOfEditForm.matchTypeName,
      };
      const res = await raiInterface.internalPreserveAndPublish(params);
      if (res.Ret === 200) {
        ElMessage.success("操作成功！");
        clearInterval(pageState.timeInterval);
        sessionStorage.removeItem("addHaveReportQY");
        addOfEditFormRef.value.resetFields();
        $router.push("/internalTesting");
      }
    }
  });
}, 500);
//表单取消事件
function cancelBtn() {
  clearInterval(pageState.timeInterval);
  sessionStorage.removeItem("addHaveReportQY");
  addOfEditFormRef.value.resetFields();
  $router.push("/internalTesting");
}

const addMatchTypeDataRef = ref(null);

// 新增报告类型的确定事件
function addMatchSubmitForm() {
  addMatchTypeDataRef.value.validate(async (valid) => {
    if (valid) {
      console.log("ok");
      const res = await raiInterface.reportMappingAdd({
        ReportType: pageState.addMatchTypeData.type,
        MatchTypeName: pageState.addMatchTypeData.name,
        ChartPermissionId: pageState.addOfEditForm.industry,
        ChartPermissionName: pageState.dlgTextRender,
      });
      if (res.Ret === 200) {
        await getMatchTypeNameList();
        ElMessage.success("添加成功");
        pageState.addOfEditForm.matchTypeName = res.Data.Id;
        pageState.confirmMatchType();
      }
    }
  });
}
//关闭弹框事件
function confirmMatchType() {
  pageState.addMatchTypeDlg = false;
  addMatchTypeDataRef.value.resetFields();
  pageState.addMatchTypeData = {
    name: "",
    type: "",
  };
}

onMounted(() => {
  if ($route.query.id) {
    // 编辑进来的
    getDetail();
  } else {
    dataInit();
  }
  chartPermission();
});

onBeforeRouteLeave((to, from, next) => {
  clearInterval(pageState.timeInterval);
  next();
});

const {
  addOfEditForm,
  rulesOption,
  chartPermissionList,
  selectedIndustryArr,
  subjectData,
  matchTypeNameList,
  isShowStatus,
  addMatchTypeDlg,
  addMatchTypeData,
  matchTypeRules,
  dlgTextRender,
  timeInterval,
} = toRefs(pageState);
</script>

<template>
  <div class="container-summary">
    <el-form :model="addOfEditForm" :rules="rulesOption" ref="addOfEditFormRef">
      <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>
        <RichText spareId="froala-editor" isText="请输入报告内容" v-model="addOfEditForm.content" />
        <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 draggable :close-on-click-modal="false" :modal-append-to-body="false" center title="新建报告类型" v-model="addMatchTypeDlg" :before-close="confirmMatchType" width="500px">
      <p style="margin-bottom: 10px">所属行业：{{ dlgTextRender }}</p>
      <el-form :model="addMatchTypeData" :rules="matchTypeRules" ref="addMatchTypeDataRef">
        <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>

<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>
