<template>
    <div>
        <div class="titleBox">
            <PageTitle title="态势预警列表">
                <el-button size="small" @click="goback">返回</el-button>
            </PageTitle>
        </div>
        <!-- 搜索 -->
        <div ref="searchBox">
            <Search :searchArr="searchConfiger" @submit="onSearch"></Search>
        </div>
        <!-- 表格 -->
        <div class="tabBox">
            <MyTable :tableData="pageData.tableData" :tableColumn="pageData.tableColumn"
                :tableHeight="pageData.tableHeight" :key="pageData.keyCount" :tableConfiger="pageData.tableConfiger"
                :controlsWidth="pageData.controlsWidth">
                <template #jqlbdm="{ row }">
                    <DictTag :tag="false" :value="row.jqlbdm" :options="JQLB" />
                </template>
                <template #jqzldm="{ row }">
                     <DictTag :tag="false" :value="row.jqzldm" :options="JQZL" />
                </template>
                <!-- 操作 -->
                <template #controls="{ row }">
                    <el-link type="primary" @click="viewDetails(row)">详情</el-link>
                    <el-link type="primary" @click="generateReport(row.id)">研判报告</el-link>
                </template>
            </MyTable>
            <Pages @changeNo="changeNo" @changeSize="changeSize" :tableHeight="pageData.tableHeight" :pageConfiger="{
                ...pageData.pageConfiger,
                total: pageData.total
            }"></Pages>
        </div>
    </div>
    <YjDetail ref="yjDetail"></YjDetail>
     <YpModel v-model="showModel" @SaveReport="SaveReport" :heightNumber="436" v-model:textContent="textContent"></YpModel>
</template>

<script setup>
import { timeValidate } from '@/utils/tools.js'
import YpModel from '@/components/ypModel/index.vue'
import { getItem } from '@/utils/storage.js'
import YjDetail from './yjDetail.vue'
import PageTitle from "@/components/aboutTable/PageTitle.vue";
import MyTable from "@/components/aboutTable/MyTable.vue";
import Pages from "@/components/aboutTable/Pages.vue";
import Search from "@/components/aboutTable/Search.vue";
import { jqypDywdtj, jqypfxbgJqlxtj, jqypfxbgYdfx, jqypfxbgJqlytj, jqypfxbgTj, jqypfxbgCljgf, jqypfxbgCzlfx, getDictItem } from '@/api/semanticAnalysis'
import { textStyle, Firstlevelheading, Subheading, BiheadlinegTitle, BigTitle, headTitle, report, signature } from './content.js'
import { qcckGet, qcckPost, qcckDelete } from "@/api/qcckApi.js";
import { reactive, ref, onMounted,defineProps, getCurrentInstance, defineEmits } from "vue";
const props = defineProps({
    item: {
        type: Object,
        default: {}
    }
})
const showModel = ref(false)
const sortingRatioValue = ref({})
const textContent = ref('');

const emit = defineEmits(['change']);
const { proxy } = getCurrentInstance();
const { JQLB,JQZL} = proxy.$dict( "JQLB",'JQZL' ); //获取字典数据
const searchBox = ref(); //搜索框
const searchConfiger = ref([
    {
        label: "预警名称",
        prop: "yjMc",
        placeholder: "预警名称",
        showType: "input"
    },
    {
        label: "预警时间",
        prop: "timeRange",
        placeholder: "预警时间",
        showType: "datetimerange"
    }
]);
const yjDetail = ref();
const queryFrom = ref({});
const pageData = reactive({
    tableData: [], //表格数据
    keyCount: 0,
    tableConfiger: {
        rowHieght: 61,
        showSelectType: "null",
        loading: false
    },
    total: 0,
    pageConfiger: {
        pageSize: 20,
        pageCurrent: 1
    }, //分页
    controlsWidth: 160, //操作栏宽度
    tableColumn: [
        { label: "预警类型",  prop: "ypmc" },
        { label: "预警时间", prop: "yjsj" },
        { label: "预警名称大类", prop: "jqlbdm" ,showSolt: true },
        { label: "预警名称细类",  prop: "jqzldm" ,showSolt: true}
    ]
});
const timeDate = ref()
const endYears = ref()

onMounted(() => {
    tabHeightFn();
    getList();
    Time()
});

const Time = () => {
  const currentYear = new Date().getFullYear();
  const startOfYear = new Date(currentYear, 0, 1); // 今年1月1日
  const endOfYear = new Date(currentYear, 11, 31, 23); // 今年12月31日23:59:59.999
  const year = startOfYear.getFullYear();
  const month = String(startOfYear.getMonth() + 1).padStart(2, '0');
  const day = String(startOfYear.getDate()).padStart(2, '0');
  const endYear = endOfYear.getFullYear();
  const endMonth = String(endOfYear.getMonth() + 1).padStart(2, '0');
  const endDay = String(endOfYear.getDate()).padStart(2, '0');
  timeDate.value = `${endYear}年${endMonth}月${endDay}日`
  endYears.value = year
  return `${year}年${month}月${day}日 至${endYear}年${endMonth}月${endDay}日`
}

// 搜索
const onSearch = (val) => {
    queryFrom.value = { ...queryFrom.value,...val };
    queryFrom.value.startTime = val.timeRange ? val.timeRange[0] : '';
    queryFrom.value.endTime = val.timeRange ? val.timeRange[1] : '';
    pageData.pageConfiger.pageCurrent = 1;
    getList();
};

const changeNo = (val) => {
    pageData.pageConfiger.pageCurrent = val;
    getList();
};
const changeSize = (val) => {
    pageData.pageConfiger.pageSize = val;
    getList();
};

const getList = () => {
    pageData.tableConfiger.loading = true;
    let data = {
        yjid:props.item.id,
        ...queryFrom.value,
        pageCurrent: pageData.pageConfiger.pageCurrent,
        pageSize: pageData.pageConfiger.pageSize
    }
    delete data.timeRange;
    qcckPost(data, "/mosty-gsxt/jjdbYp/yjPageList").then((res) => {
        pageData.tableData = res.records;
        pageData.total = res.total;
        pageData.tableConfiger.loading = false;
    }).catch(() => {
        pageData.tableConfiger.loading = false;
    });
};

// 查看详情
const viewDetails = (row) => {
    emit('change', { type: '预警详情', data: row })
};

// 生成研判报告
const generateReport = (val) => {
const dev = getItem('deptId')[0]
  sortingRatioValue.value = {}
  textContent.value = BigTitle(`${endYears.value}年度西藏公安执法数据分析`) + headTitle({
    orgName: dev.deptName,
    serialNumber: timeValidate("", "mm"),
    time: timeValidate(),
  })
  const data = `为全面、客观、准确掌握全区公安机关的执法状况，自治区公安厅基于数据统计，对全区公安机关${endYears.value}年度的执法状况作了客观分析。`
  textContent.value += BiheadlinegTitle('1.接处预警况') + textStyle(data) + Firstlevelheading('一、执法状况总体分析')
  getfxbgYdfx(val)
  getfxbgTj(val)
  getfxbgJqlxtj(val)
  getfxbgJqlytj(val)
  getfxbgDywdtj(val)
  getfxgbCljgf(val)
  getfxgbCzlfx(val)
  showModel.value = true;
};

//分析报告-时间维度-月分析
const getfxbgYdfx = (val) => {
  jqypfxbgYdfx({ yjid: val }).then(res => {
    const model = sortingRatio(res)
    const data = `我们将所有预警按照月份划分进行统计发现，每月预警分布较为平均。最高月份为${model[0].month}月，占到${model[0].number}；最低月份为${model[res.length - 1].month}月，占到${model[res.length - 1].number}。考虑是因为${model[0].month}月为我区传统旅游旺季，进藏人员较多。 ${model[res.length - 1].month}月一般春节及藏历新年期间，在藏人员较少。`
    sortingRatioValue.value.ydfx = Subheading('1.1.4时间维度') + textStyle(data)
  })
}

const getfxbgTj = (val) => {
  jqypfxbgTj({ yjid: val }).then(res => {
    const data = `${Time()} ，全区公安机关共接报各类预警${res.total}起,同比上升 ${res.tbbsb}%,同比上升${res.hbbsb}%`
    textContent.value += BiheadlinegTitle('1.1接报预警') + textStyle(data)
    dataList.XsfxTj = res
  })
}

// 预警类型统计
const getfxbgJqlxtj = (val) => {
  let params = {
    ...pageData.parameter,
    yjid: val
  }
  jqypfxbgJqlxtj(params).then(res => {
    const model = sortingRatio(res)
    const data = `按预警类型来看，${model[0].name}最多，占到${model[0].ratio}；其次为${model[1].name}最多，占到${model[1].ratio}。`
    sortingRatioValue.value.jqlx = Subheading('1.1.1类型维度') + textStyle(data)
  })
}

// 预警来源统计
const getfxbgJqlytj = (val) => {
  jqypfxbgJqlytj({ yjid: val }).then(res => {
    const model = sortingRatio(res)
    const data = `按预警来源来看，${model[0].name}最多，占到${model[0].ratio}；其次为${model[1].name}最多，占到${model[1].ratio}。`
    sortingRatioValue.value.jqly = Subheading('1.1.2来源维度') + textStyle(data)
  })
}

// 地域统计
const getfxbgDywdtj = (val) => {
  jqypDywdtj({ yjid: val }).then(res => {
    dataList.dyTj.xAxisData = res.map(it => it.ssbm)
    dataList.dyTj.seriesData = [];
    for (let i = 0; i < res.length; i++) {
      dataList.dyTj.seriesData[i] = [];
      for (let j = 0; j < res.length; j++) {
        dataList.dyTj.seriesData[i][j] = 0;
      }
    }
    for (let i = 0; i < dataList.dyTj.seriesData.length; i++) {
      dataList.dyTj.seriesData[i][i] = res[i].number
    }
    const model = sortingRatio(res)
    let data
    if (model.length > 1) {
      data = `从地市分布地市来看，${model[0].ssbm}预警量最大，占到全区预警总量的${model[0].number}。其次为${model[1].ssbm}和${model[2].ssbm}，两市预警量较为接近。预警量最少的为${model[model.length - 1].ssbm}。`
    } else {
      data = `从地市分布地市来看，${model[0].ssbm}预警量最大，占到全区预警总量的${model[0].number}。`
    }
    sortingRatioValue.value.dywd = Subheading('1.1.3地域维度') + textStyle(data)

  })
}

// 分析报告-处理结果分析
const getfxgbCljgf = (val) => {
  jqypfxbgCljgf({ yjid: val }).then(res => {
    // sortingRatioValue.Cljgf =
    const model = sortingRatio(res)

    let czjgfx = `从预警处置结果来看，`
    model.forEach(item => {
      czjgfx += `${item.name}，占到${item.ratio};`
    })
    sortingRatioValue.value.xlwdfx = BiheadlinegTitle('1.2预警处置') + Firstlevelheading('1.2.1结果维度') + textStyle(czjgfx)
  })
}

// 分析报告-处置率分析
const getfxgbCzlfx = (val) => {

  jqypfxbgCzlfx({ yjid: val }).then(res => {
    dataList.withinTj = [{
      name: "超时分流(超过24小时)",
      value: res.within24h ? res.within24h : 0
    }, {
      name: "按时分流(24小时内)",
      value: res.over24h ? res.over24h : 0
    }]
    const data = `从处警效率来看，24小时以内处警的，占到${res.over24h}%。表明我区公安机关在接警之后能够在第一时间处警。`
    sortingRatioValue.value.czjgfx = Subheading('1.2.2效率维度') + textStyle(data)
  })
}

const SaveReport = (val) => {
  ElMessageBox.prompt('请输入名称', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    // inputPattern:/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    // inputErrorMessage: 'Invalid Email',
  })
    .then(({ value }) => {
      const promes = {
        bgmc:value,
        bgnr: val,
        yjid:chageData.value
      }
      qcckPost( promes , "/mosty-gsxt/gsxtYpbg/addEntity")
        .then(() => {
          ElMessage.success("保存成功");
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消保存',
      })
    })
    .catch(() => { });
}

const goback = () => {
    emit('change', { type: '研判首页', data: null })
}

// 表格高度计算
const tabHeightFn = () => {
    pageData.tableHeight = window.innerHeight - searchBox.value.offsetHeight - 250;
    window.onresize = function () {
        tabHeightFn();
    };
};
</script>

<style>
.el-loading-mask {
    background: rgba(0, 0, 0, 0.5) !important;
}
</style>
