<template>
  <div class="main">
    <div class="content-box">
      <div>
        <div class="title">方案列表</div>
        <div class="content-tree">
          <a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="支持关键字查询" />
          <a-tree :selectedKeys="selectedKeysTree" v-if="gData.length" :expandedKeys="expandedKeys" :auto-expand-parent="autoExpandParent" :tree-data="gData"
            :defaultExpandAll="true" :replace-fields="{
              children: 'children',
              title: 'title',
              key: 'keyid',
            }" @expand="onExpand" @select="treeSelect">
            <template #title="{ title }">
              <span v-if="title.indexOf(searchValue) > -1">
                {{ title.substr(0, title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </div>
      </div>
      <div>
        <div class="right-top">
          <a-row>
            <a-col :span="9">
              <span class="right-top-title">时间范围：</span>
              <a-date-picker v-model:value="startValue" :disabled-date="disabledStartDate" :show-time="{ format: 'HH' }"
                format="YYYY-MM-DD HH:mm:ss" placeholder="开始时间" @openChange="handleStartOpenChange"
                @change="changePicker" />
              ～
              <a-date-picker v-model:value="endValue" :disabled-date="disabledEndDate" :show-time="{ format: 'HH' }"
                format="YYYY-MM-DD HH:mm:ss" placeholder="结束时间" :open="endOpen" @openChange="handleEndOpenChange"
                @change="changePicker1" />
            </a-col>
            <a-col :span="4">
              <span class="right-top-title-yujian">预见期：</span>
              <a-input class="my-input" v-model:value="dataCenter.forecast_time" placeholder="预见期" />
            </a-col>
            <a-col :span="6">
              <span class="right-top-title-all">数值天气预报模式选择：</span>
              <a-select placeholder="数值天气预报模式" class="my-select" v-model:value="dataCenter.forecast_type">
                <a-select-option value="EC">EC模式</a-select-option>
                <a-select-option value="SPCC">spcc模式</a-select-option>
                <a-select-option value="NO">无接入模式</a-select-option>
                <a-select-option value="GRAPE">grape模式</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="5" class="line-height">
              <a-button class="top-bottom" @click="imitate" type="primary">预报</a-button>
              <a-button class="top-bottom" @click="updatePlan" type="primary">更新参数</a-button>
              <a-button class="top-bottom" @click="saving" type="primary">保存入库</a-button>
            </a-col>
          </a-row>
        </div>
        <div class="right-box">
          <div :style="{ 'width': dataCenter.contractType == 1 ? '440px' : '40px' }" class="right-box-left">
            <div v-if="dataCenter.treeActiveData.modelid != 76">
              <div class="flex-left" v-show="dataSource.length > 0">
                <div @click="setContractType" class="flex-box-contract">
                  <MenuFoldOutlined v-if="dataCenter.contractType == 1" />
                  <MenuUnfoldOutlined v-else />
                </div>
                <div @click="showRain" :class="{ 'active-box-color': dataCenter.activeBox == 1 }">雨量列表</div>
                <div @click="setActive(2)" :class="{ 'active-box-color': dataCenter.activeBox == 2 }">模型参数</div>
                <div @click="showRain2" :class="{ 'active-box-color': dataCenter.activeBox == 3 }">产流状态变量</div>
                <div @click="showRain3" :class="{ 'active-box-color': dataCenter.activeBox == 3 }">汇流状态变量</div>
              </div>
              <div class="list1" v-show="dataCenter.activeBox == 2 && dataSource.length > 0">
                <a-table :pagination="false" bordered :data-source="dataSource" :columns="columns">
                  <template #value="{ text, record }">
                    <div class="editable-cell">
                      <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                        <a-input v-model:value="editableData[record.key].value" @pressEnter="save(record.key, record)" />
                        <check-outlined class="editable-cell-icon-check" @click="save(record.key, record)" />
                      </div>
                      <div v-else class="editable-cell-text-wrapper">
                        {{ text }}
                        <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                      </div>
                    </div>
                  </template>
                </a-table>
              </div>
            </div>
            <div v-else>
              <div class="flex-left">
                <div @click="setContractType" class="flex-box-contract">
                  <MenuFoldOutlined v-if="dataCenter.contractType == 1" />
                  <MenuUnfoldOutlined v-else />
                </div>
              </div>
              <div class="list1">
                <a-table :pagination="false" bordered :data-source="dataCenter.automaticList"
                  :columns="dataCenter.automaticColumnsList">
                  <template #value="{ text, record }">
                    <div class="editable-cell">
                      <div class="editable-cell-input-wrapper">
                        <a-input-number v-model:value="record.value" />
                      </div>
                    </div>
                  </template>
                </a-table>
              </div>
              <div class="regression-btn">
                <a-button class="regression-margin-btn" type="primary" @click="calibration">自动率定</a-button>
              </div>
            </div>
          </div>
          <div class="right-box-right">
            <div class="charts-box" id="charts-id"></div>
            <div v-if="dataCenter.chartsData.eval" class="result-box">
              <div class="result-title"> 预报成果 </div>
              <div class="result-table-box">
                <a-table
                  :columns="dataCenter.treeActiveData.modelid == 76 ? dataCenter.resultColumns1 : dataCenter.resultColumns"
                  :pagination="false" :data-source="dataCenter.sourceData" bordered size="middle" :scroll="{ y: 180 }" />
                <!-- <table class="result-table">
                  <thead>
                    <tr>
                      <th> 序号 </th>
                      <th> 降雨量P(mm) </th>
                      <th> 实测径流深R(mm) </th>
                      <th> 径流深绝对误差(％） </th>
                      <th> 径流深相对误差(%) </th>
                      <th> 实测洪峰(m³/s) </th>
                      <th> 预测洪峰(m³/s) </th>
                      <th> 预测洪峰相对误差 </th>
                      <th> 实测峰现时间 </th>
                      <th> 预测峰现时间 </th>
                      <th> 峰现时差 </th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(item, index) in dataCenter.resultList" :key="index">
                      <td>{{ index + 1 }}</td>
                      <td>{{ item[0] }}</td>
                      <td>{{ item[1] }}</td>
                      <td>{{ item[2] }}</td>
                      <td>{{ item[3] }}</td>
                      <td>{{ item[4] }}</td>
                      <td>{{ item[5] }}</td>
                      <td>{{ item[6] }}</td>
                      <td>{{ item[7] }}</td>
                      <td>{{ item[8] }}</td>
                      <td>{{ item[9] }}</td>
                    </tr>
                  </tbody>
                </table> -->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <BasicModal :maskClosable="false" @cancel="cancel" :footer="null" :visible="dataCenter.showRainModal" :width="1200"
      title="雨量列表">
      <div>
        <div class="rainfall-export">
          <a-button @click="rainfallExport" type="primary">导出excel</a-button>
        </div>
        <a-table :dataSource="dataCenter.rainData.dataSource" :columns="dataCenter.rainData.columns" bordered
          size="middle" />
      </div>
    </BasicModal>
    <!-- 产流状态变量弹窗 -->
    <BasicModal :closable='false' @ok="handle2Ok" @cancel="cancel2" :visible="dataCenter.showRainModal2" :width="1200"
      title="产流状态变量">
      <div>
        <div class="rainfall-export">
          <a-button @click="stateExport" type="primary">导出excel</a-button>
        </div>
        <div style="height: 600px; position: relative;">
          <div id="luckysheet" style="
            margin: 0px;
            padding: 0px;
            position: absolute;
            width: 100%;
            height: 100%;
            left: 0px;
            top: 0px;
          "></div>
        </div>
      </div>
    </BasicModal>
    <!-- 汇流状态变量 -->
    <BasicModal :maskClosable="false" @ok="handle3Ok" @cancel="cancel3" :visible="dataCenter.showRainModal3" :width="650"
      title="汇流状态变量">
      <div>
        <div class="top-number-form">
          <span>河段数：</span>
          <span>
            <a-input-number id="inputNumber" v-model:value="inputNumber.msk_num" :min="0" />
          </span>
          <span>时段末最大流量：</span>
          <span>
            <a-input-number id="inputNumber" v-model:value="inputNumber.Q0" :min="0" />
          </span>
          <a-button @click="subInputNumber" style="margin-left: 10px;" type="primary">查询</a-button>
          <a-button @click="reachExport" style="margin-left: 10px;" type="primary">导出excel</a-button>
        </div>
        <a-table :pagination="false" bordered :data-source="dataSource3" :columns="columns3" :scroll="{ y: 600 }">
          <template #Q0="{ text, record }">
            <div class="editable-cell">
              <div v-if="editableData12[record.key]" class="editable-cell-input-wrapper">
                <a-input-number class="my-input-table" v-model:value="editableData12[record.key].Q0"
                  @pressEnter="save3(record.key)" />
                <check-outlined class="editable-cell-icon-check" @click="save3(record.key)" />
              </div>
              <div v-else class="editable-cell-text-wrapper">
                {{ text }}
                <edit-outlined class="editable-cell-icon" @click="edit3(record.key)" />
              </div>
            </div>
          </template>
        </a-table>
      </div>
    </BasicModal>
    <Loading :loading="compState.loading" :absolute="compState.absolute" :tip="compState.tip" />
  </div>
</template>
<script lang="ts" setup>
import { createVNode, defineComponent, ref, watch, onMounted, reactive } from 'vue';
import { BasicModal } from '/@/components/Modal/index';
import { ImpExcel, ExcelData, jsonToSheetXlsx } from '/@/components/Excel';
import {
  getSimulateTree,
  getFcodeshow,
  getRainFlowShow,
  getIntermediateParamShow,
  getInitParamShow,
  getFloodForecast,
  getInitThreshold,
  forecastArtifical,
  getFloodUpdate,
  resultWrite,
  getRegressionParamShow,
  getCorresponding,
  getRegrssionUpdate,
  getCorrespondingOptimaze,
  schemeAddMsknum,
  forecastHour
} from '/@/api/swHome/index';
import { message, Modal } from 'ant-design-vue';
import { CheckOutlined, EditOutlined, ExclamationCircleOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons-vue';
import moment from 'moment';
import { cloneDeep } from 'lodash-es';
import { Loading } from '/@/components/Loading';
import * as echarts from 'echarts';
let inputNumber = ref({
  msk_num: '',
  Q0: ''
})
let dataCenter = reactive({
  automaticList: [],
  automaticColumnsList: [
    {
      title: '参数名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '参数值',
      dataIndex: 'value',
      key: 'value',
      slots: {
        customRender: 'value',
      },
    },
  ],
  contractType: 1,
  forecast_time: '',
  forecast_type: '',
  test1: 1,
  test2: '',
  test3: [],
  activeBox: 2,
  honghaoList: [],
  disabled: false,
  keyid: null,
  showRainModal: false,
  showRainModal2: false,
  showRainModal3: false,
  threshold: [],
  rainData: {
    dataSource: [],
    columns: [],
  },
  listData: {
    rainData: [],
    intermediateData: [],
    rainData: [],
    paramData: [],
  },
  resultList: [],
  ranges: { Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] },
  chartsData: {},
  treeActiveData: {},
  regressionFormData: {},
  resultColumns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 50,
      align: 'center',
      customRender: (text, record, index) => {
        return text.index + 1;
      }, //此处为重点
    },
    {
      title: '降雨量',
      dataIndex: '0',
      key: '0',
      width: 60,
      align: 'center',
      children: [
        {
          title: 'mm',
          dataIndex: '0',
          key: '0',
          width: 60,
          align: 'center'
        },
      ]
    },
    {
      title: '径流深',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      children: [
        {
          title: '实测值',
          dataIndex: 'index',
          key: 'index',
          width: 60,
          align: 'center',
          children: [
            {
              title: 'mm',
              dataIndex: '1',
              key: '1',
              width: 60,
              align: 'center'
            },
          ]
        },
        {
          title: '计算值',
          dataIndex: 'index',
          key: 'index',
          width: 60,
          align: 'center',
          children: [
            {
              title: 'mm',
              dataIndex: '2',
              key: '2',
              width: 60,
              align: 'center'
            },
          ]
        },
        {
          title: '绝对误差',
          dataIndex: 'index',
          key: 'index',
          width: 80,
          align: 'center',
          children: [
            {
              title: 'mm',
              dataIndex: '3',
              key: '3',
              width: 80,
              align: 'center'
            },
          ]
        },
        {
          title: '相对误差',
          dataIndex: 'index',
          key: 'index',
          width: 80,
          align: 'center',
          children: [
            {
              title: '%',
              dataIndex: '4',
              key: '4',
              width: 80,
              align: 'center'
            },
          ]
        },
      ]
    },
    {
      title: '洪峰',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      children: [
        {
          title: '实测值',
          dataIndex: 'index',
          key: 'index',
          width: 70,
          align: 'center',
          children: [
            {
              title: 'm³/s',
              dataIndex: '5',
              key: '5',
              width: 70,
              align: 'center'
            },
          ]
        },
        {
          title: '计算值',
          dataIndex: 'index',
          key: 'index',
          width: 70,
          align: 'center',
          children: [
            {
              title: 'm³/s',
              dataIndex: '6',
              key: '6',
              width: 70,
              align: 'center'
            },
          ]
        },
        {
          title: '相对误差',
          dataIndex: 'index',
          key: 'index',
          width: 80,
          align: 'center',
          children: [
            {
              title: '%',
              dataIndex: '7',
              key: '7',
              width: 80,
              align: 'center'
            },
          ]
        },
      ]
    },
    {
      title: '峰现时间',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      children: [
        {
          title: '实测值',
          dataIndex: '8',
          key: '8',
          width: 90,
          align: 'center'
        },
        {
          title: '计算值',
          dataIndex: '9',
          key: '9',
          width: 90,
          align: 'center'
        },
        {
          title: '峰现时差',
          dataIndex: '10',
          key: '10',
          width: 80,
          align: 'center',
          children: [
            {
              title: 'h',
              dataIndex: '10',
              key: '10',
              width: 80,
              align: 'center'
            },
          ]
        },
      ]
    },
    {
      title: '确定性系数',
      dataIndex: '11',
      key: '11',
      align: 'center',
      width: 110,
    },

  ],
  resultColumns1: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 50,
      align: 'center',
      customRender: (text, record, index) => {
        return text.index + 1;
      }, //此处为重点
    },
    // {
    //   title: '降雨量',
    //   dataIndex: '0',
    //   key: '0',
    //   width: 60,
    //   align: 'center',
    //   rowSpan: 1,
    //   children: [
    //     {
    //       title: 'mm',
    //       dataIndex: '0',
    //       key: '0',
    //       width: 60,
    //       rowSpan: 1,
    //       align: 'center',
    //     },
    //   ],
    // },
    {
      title: '径流深',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      rowSpan: 1,
      children: [
        {
          title: '实测值',
          dataIndex: 'index',
          key: 'index',
          width: 60,
          align: 'center',
          children: [
            {
              title: 'mm',
              dataIndex: '0',
              key: '0',
              width: 60,
              align: 'center',
            },
          ],
        },
        {
          title: '计算值',
          dataIndex: 'index',
          key: 'index',
          width: 60,
          align: 'center',
          children: [
            {
              title: 'mm',
              dataIndex: '1',
              key: '1',
              width: 60,
              align: 'center',
            },
          ],
        },
        {
          title: '绝对误差',
          dataIndex: 'index',
          key: 'index',
          width: 80,
          align: 'center',
          children: [
            {
              title: 'mm',
              dataIndex: '2',
              key: '2',
              width: 80,
              align: 'center',
            },
          ],
        },
        {
          title: '相对误差',
          dataIndex: 'index',
          key: 'index',
          width: 80,
          align: 'center',
          children: [
            {
              title: '%',
              dataIndex: '3',
              key: '3',
              width: 80,
              align: 'center',
            },
          ],
        },
      ],
    },
    {
      title: '洪峰',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      children: [
        {
          title: '实测值',
          dataIndex: 'index',
          key: 'index',
          width: 70,
          align: 'center',
          children: [
            {
              title: 'm³/s',
              dataIndex: '4',
              key: '4',
              width: 70,
              align: 'center',
            },
          ],
        },
        {
          title: '计算值',
          dataIndex: 'index',
          key: 'index',
          width: 70,
          align: 'center',
          children: [
            {
              title: 'm³/s',
              dataIndex: '5',
              key: '5',
              width: 70,
              align: 'center',
            },
          ],
        },
        {
          title: '相对误差',
          dataIndex: 'index',
          key: 'index',
          width: 80,
          align: 'center',
          children: [
            {
              title: '%',
              dataIndex: '6',
              key: '6',
              width: 80,
              align: 'center',
            },
          ],
        },
      ],
    },
    {
      title: '峰现时间',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      children: [
        {
          title: '实测值',
          dataIndex: '7',
          key: '7',
          width: 90,
          align: 'center',
        },
        {
          title: '计算值',
          dataIndex: '8',
          key: '8',
          width: 90,
          align: 'center',
        },
        {
          title: '峰现时差',
          dataIndex: '9',
          key: '9',
          width: 80,
          align: 'center',
          children: [
            {
              title: 'h',
              dataIndex: '9',
              key: '9',
              width: 80,
              align: 'center',
            },
          ],
        },
      ],
    },
    {
      title: '确定性系数',
      dataIndex: '10',
      key: '10',
      align: 'center',
      width: 110,
    },
  ],
  sourceData: []
});
const columns = [
  {
    title: '参数',
    dataIndex: 'param',
  },
  {
    title: '描述',
    dataIndex: 'desc',
  },
  {
    title: '数值',
    dataIndex: 'value',
    width: '30%',
    slots: {
      customRender: 'value',
    },
  },
];
const columns2 = ref([]);
const columns3 = ref([]);
const dataSource = ref([]);
const dataSource2 = ref([]);
const dataSource3 = ref([]);
const dataSource3Copy = ref([]);
const editableData = reactive({});
const editableData2 = reactive({});
const editableData3 = reactive({});
const editableData4 = reactive({});
const editableData5 = reactive({});
const editableData6 = reactive({});
const editableData7 = reactive({});
const editableData8 = reactive({});
const editableData9 = reactive({});
const editableData10 = reactive({});
const editableData11 = reactive({});
const editableData12 = ref({});
const edit3 = (key: string) => {
  editableData12.value[key] = cloneDeep(dataSource3.value.filter(item => key === item.key)[0]);
};
const save3 = (key: string) => {
  Object.assign(dataSource3.value.filter(item => key === item.key)[0], editableData12.value[key]);
  delete editableData12.value[key];
};
const genData = ref([]);

const dataList = [];
const generateList = (data) => {
  console.log(data);
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.title;
    dataList.push({
      key,
      title: key,
    });
    expandedKeys.value.push(node.keyid)
    if (node.children) {
      generateList(node.children);
    }
  }
};

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    console.log(node);
    if (node.children) {
      if (node.children.some((item) => item.title === key)) {
        parentKey = node.keyid;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
const edit = (key) => {
  editableData[key] = cloneDeep(dataSource.value.filter((item) => key === item.key)[0]);
};
const save = (key, item) => {
  let obj = threshold(editableData[key]);
  console.log(obj);
  if (obj.type) {
    Object.assign(dataSource.value.filter((item) => key === item.key)[0], editableData[key]);
    delete editableData[key];
  } else {
    message.warning(`您的值超出阀值,最小值：${obj.minValue},最大值：${obj.maxValue}`);
  }
};
const compState = reactive({
  absolute: false,
  loading: false,
  tip: '加载中...',
});
function openLoading(loading) {
  compState.loading = loading;
}
// 多个修改
const edit2 = (key, editableDataName) => {
  editableDataName[key] = cloneDeep(dataSource2.value.filter((item) => key === item.name)[0]);
};
const save2 = (key, editableDataName) => {
  Object.assign(dataSource2.value.filter((item) => key === item.name)[0], editableDataName[key]);
  delete editableDataName[key];
};
const expandedKeys = ref([]);
const searchValue = ref('');
const autoExpandParent = ref(true);
const gData = ref(genData);
function setActive(e) {
  dataCenter.activeBox = e;
}
const onExpand = (keys) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};
watch(searchValue, (value) => {
  const expanded = dataList
    .map((item) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, gData.value);
      }
      return null;
    })
    .filter((item, i, self) => item && self.indexOf(item) === i);
  console.log(expanded);
  expandedKeys.value = expanded;
  searchValue.value = value;
  autoExpandParent.value = true;
});

// 设置选中节点
let selectedKeysTree = ref([])
const getSimulateTreeData = () => {
  getSimulateTree().then((res) => {
    genData.value = res.data[0].children;
    gData.value = res.data[0].children;
    generateList(res.data[0].children);
    // 默认选中第一个
    console.log('gData',gData.value)
    if(gData.value.length>0 && gData.value[0].children.length>0 && gData.value[0].children[0].children.length>0){
      let eData = {
        node:{
          dataRef:gData.value[0].children[0].children[0]
        }
      }
      selectedKeysTree.value = [gData.value[0].children[0].children[0].keyid]
      treeSelect('',eData)
    }
  });
};
async function getRegressionParamShowData(item, scheme_id) {
  let data = {
    scheme_id: scheme_id,
    model_id: item.modelid
  }
  await getRegressionParamShow(data).then(res => {
    console.log(res)
    dataCenter.regressionFormData = res.data
    // 新增表体
    dataCenter.automaticList = []
    res.data.stcd.forEach((element, index) => {
      let element2 = res.data.coef[index]
      let obj = {
        value: '',
        name: ''
      }
      obj.name = element + '系数'
      obj.value = element2
      dataCenter.automaticList.push(obj)
    });
    dataCenter.automaticList.push({
      name: '截距',
      value: res.data.intercept
    })
  })
}
async function treeSelect(selectedKeys, e) {
  selectedKeysTree.value = [e.node.dataRef.keyid]
  dataCenter.sourceData = []
  dataCenter.forecast_type = 'EC'
  dataCenter.resultList = [];
  dataCenter.chartsData = {};
  dataSource.value = [];
  let sTime = moment().subtract(1, "day").format("YYYY-MM-DD HH:mm:ss")
  let eTime = moment().subtract(0, "day").format("YYYY-MM-DD HH:mm:ss")
  // let sTimeInit = sTime.split(':')[0] + ':00:00';
  let sTimeInit = new Date().getFullYear() + '-05-01 08:00:00';
  let eTimeInit = eTime.split(':')[0] + ':00:00';
  // 销毁echarts
  if (chart) {
    chart.clear();
  }
  if (e.node.dataRef.children.length != 0) return;
  //获取keyid和PID
  dataCenter.keyid = e.node.dataRef.keyid;
  dataCenter.treeActiveData = e.node.dataRef
  if (e.node.dataRef.modelid == 76) {
    // 查询id为76的
    dataCenter.treeActiveData = e.node.dataRef
    await getRegressionParamShowData(e.node.dataRef, dataCenter.keyid)
  } else {
    dataCenter.treeActiveData = e.node.dataRef
  }
  startValue.value = sTimeInit;
  endValue.value = eTimeInit;
  dataCenter.test3 = [sTimeInit, eTimeInit];
  await changePicker()
  // 获取预见期
  forecastHour().then(res => {
    if (res.code == 200) {
      dataCenter.forecast_time = res.data.forecast_time
      imitate()
    }
  })
}
async function changePicker(e) {
  if (!dataCenter.keyid) {
    message.warning('请选择方案');
    return false;
  }
  dataCenter.test3[0] =
    moment(startValue.value).format('YYYY-MM-DD HH:mm:ss').split(':')[0] + ':00:00';
  startValue.value = moment(
    moment(startValue.value).format('YYYY-MM-DD HH:mm:ss').split(':')[0] + ':00:00'
  );
  let a = [dataCenter.test3[0], dataCenter.test3[1]];
  if (dataCenter.test3[0] && dataCenter.test3[1]) {
    if (chart) {
      chart.clear();
    }
    await getListData(a);
  }
}
// 导出雨量列表
function rainfallExport() {
  let name = '人工预报-雨量列表.xlsx';
  let header = {};
  let data = [];
  dataCenter.rainData.columns.forEach((element) => {
    header[element.key] = element.title;
  });
  data = dataCenter.rainData.dataSource;
  jsonToSheetXlsx({
    data,
    header: header,
    filename: name,
  });
}
// 导出产汇流状态变量
function stateExport() {
  let name = '人工预报-产流状态变量.xlsx';
  let header = {};
  let data = [];
  columns2.value.forEach((element) => {
    header[element.key] = element.title;
  });
  data = dataSource2.value;
  jsonToSheetXlsx({
    data,
    header: header,
    filename: name,
  });
}
// 河段数导出
function reachExport() {
  let name = '人工预报-汇流状态变量.xlsx';
  let header = {};
  let data = [];
  columns3.value.forEach((element) => {
    header[element.key] = element.title;
  });
  data = dataSource3.value;
  jsonToSheetXlsx({
    data,
    header: header,
    filename: name,
  });
}
function changePicker1(e) {
  if (!dataCenter.keyid) {
    message.warning('请选择方案');
    return false;
  }
  dataCenter.test3[1] =
    moment(endValue.value).format('YYYY-MM-DD HH:mm:ss').split(':')[0] + ':00:00';
  endValue.value = moment(
    moment(endValue.value).format('YYYY-MM-DD HH:mm:ss').split(':')[0] + ':00:00'
  );
  let a = [dataCenter.test3[0], dataCenter.test3[1]];
  if (dataCenter.test3[0] && dataCenter.test3[1]) {
    if (chart) {
      chart.clear();
    }
    getListData(a);
  }
}
// function changePicker(e) {
//   let e1 = moment(e[0]).format('YYYY-MM-DD HH:mm:ss').split(':')[0] + ':00:00';
//   let e2 = moment(e[1]).format('YYYY-MM-DD HH:mm:ss').split(':')[0] + ':00:00';
//   dataCenter.test3 = [e1,e2]
//   let time1 = e1.split(':');
//   let time2 = e2.split(':');

//   if (!dataCenter.keyid) {
//     message.warning('请选择方案');
//     return false;
//   }
//   if (time1[1] * 1 == 0 && time1[2] * 1 == 0 && time2[1] * 1 == 0 && time2[2] * 1 == 0) {
//     dataCenter.resultList = [];
//     dataCenter.chartsData = {};
//     // 销毁echarts
//     if (chart) {
//       chart.clear();
//     }

//     let a = [
//       moment(e[0]).format('YYYY-MM-DD HH:mm:ss'),
//       moment(e[1]).format('YYYY-MM-DD HH:mm:ss'),
//     ];
//     getListData(a);
//   } else {
//     message.warning('时间日期必须为整点');
//   }
// }
function cancel(e) {
  dataCenter.showRainModal = false;
}
function cancel2(e) {
  dataCenter.showRainModal2 = false;
}
function cancel3(e) {
  var arr = Object.getOwnPropertyNames(editableData12.value);
  if (arr.length != 0) {
    editableData12.value = {}
  }
  dataCenter.showRainModal3 = false;

}
// 打开弹窗
function showRain() {
  dataCenter.showRainModal = true;
}
let columns3Luck = ref([])
function showRain2() {
  dataCenter.showRainModal2 = true;
  processingData()
  setTimeout(() => {

    //配置项
    var options = {
      container: 'luckysheet', //luckysheet为容器id
      title: '测试', // 设定表格名称
      lang: 'zh', // 设定表格语言
      showtoolbar: false,
      showsheetbar: false,
      myFolderUrl: false,
      showinfobar: false,
      enableAddRow: false,
      enableAddBackTop: false,
      showstatisticBar: false,
      column: 0,
      row: 0,
      data: [
        {
          name: 'Cell',
          celldata: columns3Luck.value,

        },
      ],
    };
    luckysheet.create(options);


  }, 0);
}
function showRain3() {
  dataSource3.value = JSON.parse(JSON.stringify(dataSource3Copy.value))
  dataCenter.showRainModal3 = true;
}
// 请求列表数据
async function getListData(time) {
  //----------------当modelid为76的时候-----------------
  if (dataCenter.treeActiveData.modelid == 76) {
    return false
  }
  openLoading(true);
  let formData = {
    scheme_id: dataCenter.keyid,
    stime: time[0],
    etime: time[1],
  };
  getInitThreshold({ scheme_id: dataCenter.keyid }).then((res) => {
    dataCenter.threshold = res.data;
  });
  // 查询雨量列表
  let rainData = await getRainFlowShow(formData).then((res) => {
    return res;
  });
  // 查询产流状态变量
  let intermediateData = await getIntermediateParamShow(formData).then((res) => {
    return res;
  });
  // 查询模型参数
  let paramData = await getInitParamShow({ scheme_id: dataCenter.keyid }).then((res) => {
    return res;
  });
  // 获取阀值

  if (rainData.code == 200 && intermediateData.code == 200 && paramData.code == 200) {
    dataCenter.listData.rainData = rainData.data;
    dataCenter.listData.intermediateData = intermediateData.data;
    dataCenter.listData.paramData = paramData.data;
    processingData();
  } else {
    if (rainData.code == 500) {
      message.warning(rainData.msg);
    }
    if (intermediateData.code == 500) {
      message.warning(intermediateData.msg);
    }
    if (paramData.code == 500) {
      message.warning(paramData.msg);
    }
    openLoading(false);
  }
}
// 数据处理
function processingData() {
  dataCenter.rainData.dataSource = []
  dataSource.value = []
  columns2.value = []
  dataSource2.value = []
  columns3.value = []
  dataSource3.value = []
  dataSource3Copy.value = []
  dataCenter.rainData.columns = [{ title: '时间', key: 'time', dataIndex: 'time', width: 200, align: 'center' }];
  // console.log(dataCenter.listData.rainData);
  // 处理雨量列表
  // 头部
  for (const key in dataCenter.listData.rainData) {
    if (Object.prototype.hasOwnProperty.call(dataCenter.listData.rainData, key)) {
      const element = dataCenter.listData.rainData[key];
      if (key != '时间') {
        let obj = {};
        obj.title = key;
        obj.key = key;
        obj.dataIndex = key;
        obj.align = 'center';
        dataCenter.rainData.columns.push(obj);
      }
    }
  }
  //表格内容
  dataCenter.listData.rainData['时间'].forEach((item, index) => {
    let obj = {};
    obj.time = item;
    for (const key in dataCenter.listData.rainData) {
      if (Object.prototype.hasOwnProperty.call(dataCenter.listData.rainData, key)) {
        const element = dataCenter.listData.rainData[key];
        if (key != '时间') {
          obj[key] = element[index];
        }
      }
    }
    dataCenter.rainData.dataSource.push(obj);
  });
  // 处理模型参数
  // console.log(dataCenter.listData.paramData);
  dataCenter.listData.paramData.forEach((element) => {
    element.key = element.param;
  });
  dataSource.value = dataCenter.listData.paramData;
  // 处理产流状态变量
  // 处理表头
  columns2.value = [{ title: '参数', key: 'name', dataIndex: 'name' }];
  columns3Luck.value = [{ r: 0, c: 0, v: { v: '参数', 'name': 'name' } }]
  dataCenter.listData.intermediateData.value1[0].value.forEach((element, index) => {
    columns2.value.push({
      title: element,
      key: element,
      dataIndex: element,
      slots: { customRender: element },
    });
    columns3Luck.value.push(
      { r: 0, c: index + 1, v: { v: element, 'name': element } }
    )
  });
  // 处理表体
  dataCenter.listData.intermediateData.value1.forEach((element, index) => {
    if (element.name != '中间变量') {
      let obj = {};
      obj.name = element.name;
      dataCenter.listData.intermediateData.value1[0].value.forEach((elements, indexs) => {
        obj[elements] = element.value[indexs];
        if (indexs == 0) {
          columns3Luck.value.push(
            { r: index, c: indexs, v: { v: element.name, 'name': element.name } }
          )
          columns3Luck.value.push(
            { r: index, c: indexs + 1, v: { v: element.value[indexs], 'name': elements } }
          )
        } else {
          columns3Luck.value.push(
            { r: index, c: indexs + 1, v: { v: element.value[indexs], 'name': elements } }
          )
        }
      });

      dataSource2.value.push(obj);
    }
  });
  // 处理3号弹窗表格
  columns3.value = [{
    title: '河段数',
    dataIndex: 'key',
    key: 'key',
    align: 'center',
    width: 80,
    customRender: (text, record, index) => {
      return text.index + 1;
    }, //此处为重点
  },
  {
    title: 'Q0',
    key: 'Q0',
    dataIndex: 'Q0',
    slots: { customRender: 'Q0' }
  }];
  dataCenter.listData.intermediateData.value2.value.forEach((elements, index) => {
    let obj = {
      Q0: elements,
      key: index,
    }
    dataSource3.value.push(obj);
  });
  dataSource3Copy.value = JSON.parse(JSON.stringify(dataSource3.value))
  openLoading(false);
}
// 点击自动率定
function calibration() {
  if (!dataCenter.keyid || dataCenter.test3.length != 2) {
    message.warning('请先选择方案和时间范围或者洪号');
    return false;
  }
  let formData = {
    scheme_id: dataCenter.keyid,
    stime: moment(dataCenter.test3[0]).format('YYYY-MM-DD HH:mm:ss'),
    etime: moment(dataCenter.test3[1]).format('YYYY-MM-DD HH:mm:ss'),
    forecast_hour: dataCenter.forecast_time,
  }
  if(dataCenter.treeActiveData.modelid == 76){
    formData.model_id = "76"
  }
  getCorrespondingOptimaze(formData).then(res => {
    dataCenter.regressionFormData = res.data
    res.data.coef.forEach((element, index) => {
      dataCenter.automaticList[index].value = element
    });
    dataCenter.automaticList[res.data.coef.length].value = res.data.intercept
  })

}
// 处理阀值
function threshold(item) {
  console.log(item);
  let obj = {
    type: false,
    minValue: '',
    maxValue: '',
  };
  for (let index = 0; index < dataCenter.threshold.length; index++) {
    const element = dataCenter.threshold[index];
    if (item.param == element.name) {
      obj.minValue = element.minValue;
      obj.maxValue = element.maxValue;
    }
    if (
      item.param == element.name &&
      element.minValue <= item.value * 1 &&
      item.value * 1 <= element.maxValue
    ) {
      obj.type = true;
      break;
    }
  }
  return obj;
}
let chart = null;
function setCharts() {
  chart = echarts.init(document.getElementById('charts-id'));
  let option = {
    toolbox: {
      right: 26,
      feature: {
        dataView: {
          show: true,
          // readOnly: true,
          iconStyle: {
            borderColor: '#2D74E7',
          },
          lang: ['', '关闭', '导出Excel'],
          optionToContent: function (opt) {
            let axisData = opt.xAxis[0].data; //坐标数据
            let series = opt.series; //折线图数据
            let tdHeads = '<th>时间</th>'; //表头
            let tdBodys = ''; //数据
            series.forEach(function (item) {
              //组装表头
              tdHeads += `<th>${item.name}</th>`;
            });
            let table = `<table id="tableExcel" class="bordered"><thead><tr>${tdHeads} </tr></thead><tbody>`;
            for (let i = 0, l = axisData.length; i < l; i++) {
              for (let j = 0; j < series.length; j++) {
                //组装表数据
                tdBodys += `<td>${series[j].data[i] || series[j].data[i] == 0 ? series[j].data[i] : ''}</td>`;
              }
              table += `<tr><td>${axisData[i]}</td>${tdBodys}</tr>`;
              tdBodys = '';
            }
            table += '</tbody></table>';
            return table;
          },
          contentToOption: function (item, item1) {
            console.log(item1)
            let name = `人工模拟-雨洪对照表.xlsx`;
            let header = {
              'time': '时间',
              'rain': '面均雨量（mm）',
              'q_real': '实测流量（m³/s）',
              'q_forecast': '预测流量（m³/s）',
              'rls_optimaze': '实时校正（mm）',
              'q_calibration': '在线校正/s）',
              'q_smooth': '光滑流量（m³/s）'
            };
            let data = []
            console.log()
            dataCenter.chartsData.t.forEach((item, index) => {
              let obj = {
                time: item,
                'rain': dataCenter.chartsData['rain'][index],
                'q_real': dataCenter.chartsData['q_real'][index],
                'q_forecast': dataCenter.chartsData['q_forecast'][index],
                'rls_optimaze': dataCenter.chartsData['rls_optimaze'][index],
                'q_calibration': dataCenter.chartsData['q_calibration'][index],
                'q_smooth': dataCenter.chartsData['q_smooth'][index],
              }
              data.push(obj)
            });
            jsonToSheetXlsx({
              data,
              header: header,
              filename: name,
            });
          },
        },
        // magicType: { show: true, type: ['line', 'bar'] },
        // restore: { show: true },
        saveAsImage: {
          show: true,
          iconStyle: {
            borderColor: '#2D74E7',
          },
        },
      },
    },
    title: {
      text: '雨洪对照图',
      left: '1%',
      top: '1%',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: false
      },
      formatter(params) {
        var relVal = params[0].name;
        for (var i = 0, l = params.length; i < l; i++) {
          console.log('tooltip数据值', params[i].value);
          //遍历出来的值一般是字符串，需要转换成数字，再进项tiFixed四舍五入
          relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + Number(params[i].value);
        }
        return relVal;
      },
    },
    axisPointer: {
      link: [
        {
          xAxisIndex: 'all'
        }
      ]
    },
    legend: {
      data: ['实测流量', '预测流量', '实时校正', '在线校正', '光滑流量', '面均雨量'],
      selected: { '实测流量': true, '预测流量': true, '实时校正': false, '在线校正': false, '光滑流量': false, '面均雨量': true },
      top: '10px',
      textStyle: {
        fontSize: 12, //字体大小
        color: '#333333', //字体颜色
      },
    },
    xAxis: [
      {
        show: false,
        data: dataCenter.chartsData.t.map(function (str) {
          return str.replace(' ', '\n');
        }),
        axisTick:{
          alignWithLabel:true
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#333333',
          },
          formatter: function (val) {
            var strs = val.split(''); //字符串数组
            var str = '';
            for (var i = 0, s; (s = strs[i++]);) {
              //遍历字符串数组
              if (i > 5 && i < 17) {
                str += s;
              }

              if (!(i % 10)) str += '\n'; //按需要求余
            }
            return str;
          },
        },
      },
      {
        data: dataCenter.chartsData.t.map(function (str) {
          return str.replace(' ', '\n');
        }),
        axisTick:{
          alignWithLabel:true
        },
        gridIndex: 1,
        axisLabel: {
          show: true,
          textStyle: {
            color: '#333333',
          },
          formatter: function (val) {
            var strs = val.split(''); //字符串数组
            var str = '';
            for (var i = 0, s; (s = strs[i++]);) {
              //遍历字符串数组
              if (i > 5 && i < 17) {
                str += s;
              }

              if (!(i % 10)) str += '\n'; //按需要求余
            }
            return str;
          },
        },
      },
    ],
    dataZoom: [
      {
        show: true,
        // realtime: true,

        realtime: true,
        start: 65,
        end: 100,
        xAxisIndex: [0, 1]
      },
      {
        show: false,
        start: 70,
        end: 100,
        type: 'inside',
        xAxisIndex: [0, 1]
      }
    ],
    yAxis: [
      {
        position: 'right',
        name: '降雨\n(mm)',
        nameLocation: 'center',
        nameGap: 40,
        nameRotate: 0,
        axisLabel: {
          textStyle: {
            color: '#333333',
          },
          formatter: function (value) {
            return value + '';
          },
        },
        nameTextStyle: {
          color: '#333',
          fontSize: 12,
          textAlign: 'center',
          padding: [0, 0, 0, 0], //距离坐标位置的距离
        },
        splitLine: {
          lineStyle: {
            type: 'dashed', //虚线
            color: '#484849',
          },
        },
        inverse: true,
        scale: true,
      },
      {
        // position: 'right',
        name: '流量  \n(m³/s)',
        gridIndex: 1,
        nameLocation: 'center',
        nameGap: 40,
        nameRotate: 0,
        axisLabel: {
          textStyle: {
            color: '#333333',
          },
          formatter: function (value) {
            return value + '';
          },
        },
        nameTextStyle: {
          color: '#333',
          fontSize: 12,
          textAlign: 'center',
          padding: [0, 0, 0, 0], //距离坐标位置的距离
        },
        splitLine: {
          lineStyle: {
            type: 'dashed', //虚线
            color: '#484849',
          },
        },
        scale: true,
      },
    ],
    grid: [
      {
        bottom: '70%',
        left: '100',
        right: '100',
      },
      {
        top: '30%',
        left: '100',
        right: '100',
        bottom: '100',
      },
    ],
    series: [
      {
        name: '面均雨量',
        data: dataCenter.chartsData.rain,
        type: 'bar',
        barWidth: 5, // 设置每个柱子的宽度为40
        showSymbol: false,
        lineStyle: {
          width: 1,
        },
        itemStyle: {
          color: '#00CB98',
        },
        emphasis: {
          focus: 'series',
        },
      },
      {
        name: '实测流量',
        smooth: true,
        type: 'line',
        showSymbol: false,
        data: dataCenter.chartsData.q_real,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
      {
        name: '预测流量',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_forecast,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
      {
        name: '实时校正',
        smooth: true,
        type: 'line',
        showSymbol: false,
        data: dataCenter.chartsData.rls_optimaze,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
      {
        name: '在线校正',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_calibration,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
      {
        name: '光滑流量',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_smooth,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
    ],
  };
  option && chart.setOption(option);
}
function setCharts76() {
  chart = echarts.init(document.getElementById('charts-id'));
  let option = {
    toolbox: {
      right: 26,
      feature: {
        dataView: {
          show: true,
          // readOnly: true,
          iconStyle: {
            borderColor: '#2D74E7',
          },
          lang: ['', '关闭', '导出Excel'],
          optionToContent: function (opt) {
            let axisData = opt.xAxis[0].data; //坐标数据
            let series = opt.series; //折线图数据
            let tdHeads = '<th>时间</th>'; //表头
            let tdBodys = ''; //数据
            series.forEach(function (item) {
              //组装表头
              tdHeads += `<th>${item.name}</th>`;
            });
            let table = `<table id="tableExcel" class="bordered"><thead><tr>${tdHeads} </tr></thead><tbody>`;
            for (let i = 0, l = axisData.length; i < l; i++) {
              for (let j = 0; j < series.length; j++) {
                //组装表数据
                tdBodys += `<td>${series[j].data[i] || series[j].data[i] == 0 ? series[j].data[i] : ''}</td>`;
              }
              table += `<tr><td>${axisData[i]}</td>${tdBodys}</tr>`;
              tdBodys = '';
            }
            table += '</tbody></table>';
            return table;
          },
          contentToOption: function (item, item1) {
            console.log(item1)
            let name = `人工模拟-雨洪对照表.xlsx`;
            let header = {
              'time': '时间',
              'rain': '面均雨量（mm）',
              'q_real': '实测流量（m³/s）',
              'q_forecast': '预测流量（m³/s）',
              'rls_optimaze': '实时校正（mm）',
              'q_calibration': '在线校正/s）',
              'q_smooth': '光滑流量（m³/s）'
            };
            let data = []
            console.log()
            dataCenter.chartsData.t.forEach((item, index) => {
              let obj = {
                time: item,
                'rain': dataCenter.chartsData['rain'][index],
                'q_real': dataCenter.chartsData['q_real'][index],
                'q_forecast': dataCenter.chartsData['q_forecast'][index],
                'rls_optimaze': dataCenter.chartsData['rls_optimaze'][index],
                'q_calibration': dataCenter.chartsData['q_calibration'][index],
                'q_smooth': dataCenter.chartsData['q_smooth'][index],
              }
              data.push(obj)
            });
            jsonToSheetXlsx({
              data,
              header: header,
              filename: name,
            });
          },
        },
        // magicType: { show: true, type: ['line', 'bar'] },
        // restore: { show: true },
        saveAsImage: {
          show: true,
          iconStyle: {
            borderColor: '#2D74E7',
          },
        },
      },
    },
    title: {
      text: '雨洪对照图',
      left: '1%',
      top: '1%',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: false
      },
      formatter(params) {
        var relVal = params[0].name;
        for (var i = 0, l = params.length; i < l; i++) {
          console.log('tooltip数据值', params[i].value);
          //遍历出来的值一般是字符串，需要转换成数字，再进项tiFixed四舍五入
          relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + Number(params[i].value);
        }
        return relVal;
      },
    },
    axisPointer: {
      link: [
        {
          xAxisIndex: 'all'
        }
      ]
    },
    legend: {
      data: ['实测流量', '预测流量', '实时校正', '在线校正', '光滑流量'],
      selected: { '实测流量': true, '预测流量': true, '实时校正': false, '在线校正': false, '光滑流量': false},
      top: '10px',
      textStyle: {
        fontSize: 12, //字体大小
        color: '#333333', //字体颜色
      },
    },
    xAxis:{
      data: dataCenter.chartsData.t.map(function (str) {
        return str.replace(' ', '\n');
      }),
      axisTick:{
        alignWithLabel:true
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#333333',
        },
        formatter: function (val) {
          var strs = val.split(''); //字符串数组
          var str = '';
          for (var i = 0, s; (s = strs[i++]);) {
            //遍历字符串数组
            if (i > 5 && i < 17) {
              str += s;
            }

            if (!(i % 10)) str += '\n'; //按需要求余
          }
          return str;
        },
      },
    },
    dataZoom: [
      {
        show: true,
        // realtime: true,

        realtime: true,
        start: 65,
        end: 100,
        xAxisIndex: [0, 1]
      },
      {
        show: false,
        start: 70,
        end: 100,
        type: 'inside',
        xAxisIndex: [0, 1]
      }
    ],
    yAxis:{
      name: '流量  \n(m³/s)',
      nameLocation: 'center',
      nameGap: 40,
      nameRotate: 0,
      axisLabel: {
        textStyle: {
          color: '#333333',
        },
        formatter: function (value) {
          return value + '';
        },
      },
      nameTextStyle: {
        color: '#333',
        fontSize: 12,
        textAlign: 'center',
        padding: [0, 0, 0, 0], //距离坐标位置的距离
      },
      splitLine: {
        lineStyle: {
          type: 'dashed', //虚线
          color: '#484849',
        },
      },
      scale: true,
    },

    grid: {
      top: '100',
      left: '100',
      right: '100',
      bottom: '100',
    },
    series: [
      {
        name: '实测流量',
        smooth: true,
        type: 'line',
        showSymbol: false,
        data: dataCenter.chartsData.q_real,
      },
      {
        name: '预测流量',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_forecast,
      },
      {
        name: '实时校正',
        smooth: true,
        type: 'line',
        showSymbol: false,
        data: dataCenter.chartsData.rls_optimaze,
      },
      {
        name: '在线校正',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_calibration,
      },
      {
        name: '光滑流量',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_smooth,
      },
    ],
  };
  option && chart.setOption(option);
}
// 处理结果数据
const setResultData = (res) => {
  if (dataCenter.sourceData.length == 0) {
    // dataCenter.resultList.push(res.data.eval);
    let obj = {}
    if (dataCenter.treeActiveData.modelid == 76) {
      res.forEach((element, index) => {
        if (index == '7' || index == '8') {
          let str = element;
          let strArr = str.split(' ');
          obj[index] = strArr[0].substring(5, 10) + '/' + strArr[1].substring(0, 2);
        } else {
          obj[index] = element;
        }
      });
    } else {
      res.forEach((element, index) => {
        if (index == '8' || index == '9') {
          let str = element;
          let strArr = str.split(' ');
          obj[index] = strArr[0].substring(5, 10) + '/' + strArr[1].substring(0, 2);
        } else {
          obj[index] = element;
        }
      });
    }
    dataCenter.sourceData.push(obj);
    console.log(dataCenter.sourceData)
    return;
  }
  if (dataCenter.sourceData.length == 1) {
    let obj = {}
    if (dataCenter.treeActiveData.modelid == 76) {
      res.forEach((element, index) => {
        if (index == '7' || index == '8') {
          let str = element;
          let strArr = str.split(' ');
          obj[index] = strArr[0].substring(5, 10) + '/' + strArr[1].substring(0, 2);
        } else {
          obj[index] = element;
        }
      });
    } else {
      res.forEach((element, index) => {
        if (index == '8' || index == '9') {
          let str = element;
          let strArr = str.split(' ');
          obj[index] = strArr[0].substring(5, 10) + '/' + strArr[1].substring(0, 2);
        } else {
          obj[index] = element;
        }
      });
    }
    dataCenter.sourceData.unshift(obj);
    console.log(dataCenter.sourceData)
    return;
  }
  if (dataCenter.sourceData.length == 2) {
    dataCenter.sourceData.pop();
    let obj = {}
    if (dataCenter.treeActiveData.modelid == 76) {
      res.forEach((element, index) => {
        if (index == '7' || index == '8') {
          let str = element;
          let strArr = str.split(' ');
          obj[index] = strArr[0].substring(5, 10) + '/' + strArr[1].substring(0, 2);
        } else {
          obj[index] = element;
        }
      });
    } else {
      res.forEach((element, index) => {
        if (index == '8' || index == '9') {
          let str = element;
          let strArr = str.split(' ');
          obj[index] = strArr[0].substring(5, 10) + '/' + strArr[1].substring(0, 2);
        } else {
          obj[index] = element;
        }
      });
    }
    dataCenter.sourceData.unshift(obj);
    console.log(dataCenter.sourceData)
    return;
  }
}
// 点击模拟// 组装数据
function imitate(isUpdate) {
  console.log(dataCenter.test3)
  if (!dataCenter.keyid || dataCenter.test3.length != 2) {
    message.warning('请先选择方案和时间范围');
    return false;
  }
  openLoading(true);
  if (dataCenter.treeActiveData.modelid == 76 && isUpdate != 'update') {
    let coef = []
    dataCenter.automaticList.forEach(element => {
      coef.push(element.value)
    });
    coef.pop()
    let formData = {
      scheme_id: dataCenter.keyid,
      stime: moment(dataCenter.test3[0]).format('YYYY-MM-DD HH:mm:ss'),
      etime: moment(dataCenter.test3[1]).format('YYYY-MM-DD HH:mm:ss'),
      coef: coef,
      model_id: "76",
      intercept: dataCenter.automaticList[dataCenter.automaticList.length - 1].value,
      forecast_hour: dataCenter.forecast_time
    };
    getCorresponding(formData).then(res => {
      if (res.code == 200) {
        openLoading(false);
        dataCenter.chartsData = res.data;
        setCharts76()
        setResultData(res.data.eval)
      }

    }).catch((err) => {
      openLoading(false);
    });
    return false
  }
  if (dataCenter.treeActiveData.modelid == 76 && isUpdate == 'update') {
    let coef = []
    dataCenter.automaticList.forEach(element => {
      coef.push(element.value)
    });
    coef.pop()
    let formData = {
      scheme_id: dataCenter.keyid,
      coef: coef,
      intercept: dataCenter.automaticList[dataCenter.automaticList.length - 1].value
    };
    if(dataCenter.treeActiveData.modelid == 76){
      formData.model_id = "76"
    }
    getRegrssionUpdate(formData).then(res => {
      if (res.code == 200) {
        message.success(res.msg);
      } else {
        message.error(res.msg);
      }
      openLoading(false);
    }).catch((err) => {
      openLoading(false);
    });

    return false
  }
  //模拟成果计算
  // 模型参数
  let init_param = dataSource.value;
  // console.log(init_param);
  // intermediate_param
  // 产流状态变量
  let intermediate_param = {
    value1: dataCenter.listData.intermediateData.value1,
    value2: dataCenter.listData.intermediateData.value2,
  };
  // 处理中间变量
  // let centerObj = {};
  // centerObj.name = '中间变量';
  // centerObj.value = [];
  // // console.log(columns2.value);
  // columns2.value.forEach((item, index) => {
  //   if (item.title != '参数') {
  //     centerObj.value.push(item.title);
  //   }
  // });
  // intermediate_param.value1.push(centerObj);
  // // console.log(intermediate_param);
  // dataSource2.value.forEach((item, index) => {
  //   let obj = {};
  //   obj.name = item.name;
  //   obj.value = [];
  //   intermediate_param.value1[0].value.forEach((items, indexs) => {
  //     obj.value.push(item[items]);
  //   });
  //   intermediate_param.value1.push(obj);
  // });
  intermediate_param.value2 = {
    name: 'Q0',
    value: []
  }
  // 处理表格3数据
  dataSource3Copy.value.forEach((item, index) => {
    intermediate_param.value2.value.push(item.Q0)
  });
  let formData = {
    scheme_id: dataCenter.keyid,
    stime: moment(dataCenter.test3[0]).format('YYYY-MM-DD HH:mm:ss'),
    etime: moment(dataCenter.test3[1]).format('YYYY-MM-DD HH:mm:ss'),
    init_param: init_param,
    intermediate_param: intermediate_param,
  };
  if (dataCenter.forecast_time) {
    formData.forecast_time = dataCenter.forecast_time;
  }
  if (dataCenter.forecast_type) {
    formData.forecast_type = dataCenter.forecast_type;
  }
  if (isUpdate == 'update') {
    getFloodUpdate(formData)
      .then((res) => {
        console.log(res.data);
        if (res.code == 200) {
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
        openLoading(false);
      })
      .catch((err) => {
        openLoading(false);
      });
  } else {
    forecastArtifical(formData)
      .then((res) => {
        openLoading(false);

        dataCenter.chartsData = res.data;
        setCharts();
        setResultData(res.data.eval)
      })
      .catch((err) => {
        openLoading(false);
      });
  }
}
// 更新方案updatePlan
function updatePlan() {
  if (!dataCenter.keyid || dataCenter.test3.length != 2) {
    message.warning('请先选择方案和意见范围');
    return false;
  }
  Modal.confirm({
    title: '参数更新后无法还原，是否确认？',
    content: '点击是或否',
    okText: '是',
    okType: 'danger',
    cancelText: '否',
    onOk: () => {
      imitate('update');
    },
  });
}
// 保存入库
function saving() {
  let obj = { ...dataCenter.chartsData };
  obj.scheme_id = dataCenter.keyid;
  obj.e_time = moment(dataCenter.test3[1]).format('YYYY-MM-DD HH:mm:ss');
  Modal.confirm({
    title: '保存入库，是否确认？',
    content: '点击是或否',
    okText: '是',
    okType: 'danger',
    cancelText: '否',
    onOk: () => {
      resultWrite(obj).then((res) => {
        if (res.code == 200) {
          message.success(res.msg);
        } else {
          message.warning(res.msg);
        }
      });
    },
  });
}
// ------------时间选择开始------------
const startValue = ref<Moment | undefined>();
const endValue = ref<Moment>();
const endOpen = ref<boolean>(false);

const disabledStartDate = (startValue: Moment) => {
  if (!startValue || !endValue.value) {
    return false;
  }

  return startValue.valueOf() > endValue.value.valueOf();
};

const disabledEndDate = (endValue: Moment) => {
  if (!endValue || !startValue.value) {
    return false;
  }

  return startValue.value.valueOf() >= endValue.valueOf();
};

const handleStartOpenChange = (open: boolean) => {
  if (!open) {
    endOpen.value = true;
  }
};

const handleEndOpenChange = (open: boolean) => {
  endOpen.value = open;
};
const setContractType = () => {
  if (dataCenter.contractType == 1) {
    dataCenter.contractType = 0
  } else {
    dataCenter.contractType = 1
  }
  setTimeout(() => {
    if (chart) {
      chart.resize();
    }
  }, 600);
}
// 弹窗2点击ok
const handle2Ok = () => {
  let tableList = luckysheet.getAllSheets()[0].data
  tableList.forEach((element, index) => {
    if (index >= 1) {
      element.forEach((element1, index1) => {
        if (index1 >= 1) {
          dataCenter.listData.intermediateData.value1[index].value[index1 - 1] = element1.v * 1
        }
      });
    }
  });
  dataCenter.showRainModal2 = false
}
const handle3Ok = () => {
  var arr = Object.getOwnPropertyNames(editableData12.value);
  if (arr.length != 0) {
    message.warning('请先确定当前数据是否写入');
    return false
  }
  dataSource3Copy.value = JSON.parse(JSON.stringify(dataSource3.value))
  dataCenter.showRainModal3 = false;
}
const subInputNumber = () => {
  if (inputNumber.value.msk_num == '' || inputNumber.value.Q0 == '') {
    message.warning('请输入河段数或时段末最大流量');
    return
  }
  schemeAddMsknum(inputNumber.value).then(res => {
    if (res.code == 200) {
      dataCenter.listData.intermediateData.value2.value = res.data
      processingData();
    }

  })

}
onMounted(() => {
  startValue.value = undefined;
  endValue.value = undefined;
  dataCenter.test3 = []
  getSimulateTreeData();
});
</script>
<style scoped lang="less">
.main {
  height: 100%;
  ::v-deep(.ant-table-tbody > tr > td){
    padding-top: 13px;
    padding-bottom: 13px;
  }
}

.content-box {
  display: flex;
  padding: 10px;
  height: 100%;
  background-color: #fff;

  &>div:nth-child(1) {
    width: 200px;
    height: 100%;
    overflow: hidden;

    .title {
      background-color: #f8f8f8;
      line-height: 45px;
      text-align: center;
      font-weight: 500;
    }

    .content-tree {
      margin-top: 10px;
      height: calc(100vh - 155px);
      background-color: #f8f8f8;
      overflow: auto;
    }
  }

  &>div:nth-child(2) {
    flex: 1;
    margin-left: 10px;
    overflow: hidden;
  }
}

.right-inner-box {
  display: inline-block;
  width: calc(100% - 80px);
  line-height: 42px;
}

.right-top-title {
  width: 80px;
  line-height: 42px;
  display: inline-block;
  text-align: right;
}

.right-top-title-yujian {
  width: 60px;
  line-height: 42px;
  display: inline-block;
  text-align: right;
}

.right-top-title-all {
  width: 170px;
  line-height: 42px;
  display: inline-block;
  text-align: right;
}

.right-inner-input {
  display: inline-block;
  width: calc(100% - 80px);
}

.right-top-picker {
  display: inline-block;
  width: calc(100% - 80px) !important;
}

.line-height {
  line-height: 42px;

  .top-bottom {
    margin-left: 20px;
  }
}

.right-box {
  height: calc(100% - 42px);
  display: flex;
}

.right-box-left {
  width: 440px;
  height: calc(100vh - 142px);
  overflow: auto;
  position: relative;
  padding-left: 40px;
  transition: width 0.5s;
}

.right-box-right {
  flex: 1;
  height: calc(100vh - 142px);
  overflow: auto;
}

.flex-left {
  width: 40px;
  position: absolute;
  left: 0px;
  top: 100px;
  z-index: 1;

  &>div {
    width: 40px;
    height: 126px;
    background-color: #d8d8d8;
    writing-mode: vertical-rl;
    /*让文字沿着垂直方向排列*/
    text-orientation: mixed;
    /*让文字正向排列*/
    text-align: center;
    line-height: 40px;
    letter-spacing: 5px;
    margin-bottom: 10px;
    cursor: pointer;
  }

  .active-box-color {
    background-color: #0671dd;
    color: #fff;
  }
}

::v-deep .ant-table {
  width: 100%;
  max-height: calc(100vh - 142px) !important;
}

::v-deep .ant-table-scroll-position-left {
  max-height: calc(100vh - 142px);
  overflow: auto scroll;
}

::v-deep .ant-table-wrapper {
  width: 100%;
}

.list1 {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  height: 100%;
}

.charts-box {
  width: 100%;
  height: 60vh;
}

::v-deep .ant-table {
  width: 100% !important;

  .ant-table-body {
    overflow: auto !important;

    th,
    tr,
    td {
      white-space: nowrap;
      text-overflow: ellipsis;
      word-break: break-word;
      overflow: hidden;
    }
  }

  .ant-table-tbody {
    overflow: auto;

    th,
    tr,
    td {
      white-space: nowrap;
      text-overflow: ellipsis;
      word-break: break-word;
      overflow: hidden;
    }
  }
}

.modal-input {
  width: 60px;
}

.result-box {
  .result-title {
    text-align: center;
    font-size: 20px;
    padding: 10px;
  }

  .result-title:before {
    content: '';
    display: block;
    height: 1px;
    width: calc(50% - 60px);
    background-color: #ccc;
    /*颜色需与主题大背景色一致*/
    position: relative;
    top: 14px;
    /*调节线高*/
    left: 0;
  }

  .result-title:after {
    content: '';
    display: block;
    height: 1px;
    width: calc(50% - 60px);
    background-color: #ccc;
    /*颜色需与主题大背景色一致*/
    position: relative;
    top: -18px;
    /*调节线高*/
    left: calc(50% + 60px);
  }
}

.result-table {
  border: 1px solid #c2c2c2;

  th {
    font-weight: 400;
    background-color: #fafafa;
    border-left: 1px solid #c2c2c2;
    min-height: 60px;
    border-bottom: 1px solid #c2c2c2;
  }

  td {
    font-weight: 400;
    // background-color: #fafafa;
    border-left: 1px solid #c2c2c2;
    min-height: 60px;
    border-bottom: 1px solid #c2c2c2;
  }
}

.result-table-box {
  padding: 10px;
}

.my-input {
  width: calc(100% - 80px);
}

.my-select {
  width: calc(100% - 200px);
}

.regression-margin {
  margin-top: 20px;
  width: 200px
}

.regression-btn {
  text-align: center;
}

.regression-margin-btn {
  margin-top: 20px;
}

.my-input-table {
  width: 200px;
}

.flex-box-contract {
  height: 40px !important;
  line-height: 52px !important;
  font-size: 20px;
}
</style>

<style lang="less">
#charts-id table {
  cellspacing: 0;
  *border-collapse: collapse;
  /* IE7 and lower */
  border-spacing: 0;
  width: 100%;
  // position: relative;
  padding-top: 40px;
}

#charts-id thead {
  position: absolute;
  left: 0px;
  top: 44px;
  width: 100%;
}

#charts-id .bordered tr:hover {
  background: #fbf8e9;
  -o-transition: all 0.1s ease-in-out;
  -webkit-transition: all 0.1s ease-in-out;
  -moz-transition: all 0.1s ease-in-out;
  -ms-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}

#charts-id .bordered th {
  padding: 7px;
  text-align: center;
  cellspacing: 0;

}

#charts-id .bordered th:nth-child(1) {
  width: 40%;
}

#charts-id .bordered th:nth-child(2) {
  width: 10%;
}

#charts-id .bordered th:nth-child(3) {
  width: 10%;
}

#charts-id .bordered th:nth-child(4) {
  width: 10%;
}

#charts-id .bordered th:nth-child(5) {
  width: 10%;
}

#charts-id .bordered th:nth-child(6) {
  width: 10%;
}

#charts-id .bordered th:nth-child(7) {
  width: 10%;
}

#charts-id .bordered td {
  padding: 7px;
  text-align: center;
  cellspacing: 0;
}

#charts-id .bordered td:nth-child(1) {
  width: 40%;
}

#charts-id .bordered td:nth-child(2) {
  width: 10%;
}

#charts-id .bordered td:nth-child(3) {
  width: 10%;
}

#charts-id .bordered td:nth-child(4) {
  width: 10%;
}

#charts-id .bordered td:nth-child(5) {
  width: 10%;
}


#charts-id .bordered td:nth-child(6) {
  width: 10%;
}


#charts-id .bordered td:nth-child(7) {
  width: 10%;
}

#charts-id .bordered th {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#ebf3fc), to(#dce9f9));
  background-image: -webkit-linear-gradient(top, #ebf3fc, #dce9f9);
  background-image: -moz-linear-gradient(top, #ebf3fc, #dce9f9);
  background-image: -ms-linear-gradient(top, #ebf3fc, #dce9f9);
  background-image: -o-linear-gradient(top, #ebf3fc, #dce9f9);
  background-image: linear-gradient(top, #ebf3fc, #dce9f9);
}

#charts-id .bordered td:first-child,
#charts-id .bordered th:first-child {
  border-left: none;
}

#charts-id .bordered tr:nth-of-type(2n) {
  background: #ffffff;
  cursor: pointer;
}

#charts-id .bordered tr {
  width: 100%;
  display: flex;
}

#charts-id .bordered tr:nth-of-type(2n + 1) {
  background: #f7fafc;
  cursor: pointer;
}

#charts-id .bordered tbody {
  padding-top: 36px;
}

#charts-id .bordered tbody tr:hover {
  background: #fbf8e9;
  -o-transition: all 0.1s ease-in-out;
  -webkit-transition: all 0.1s ease-in-out;
  -moz-transition: all 0.1s ease-in-out;
  -ms-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}

#charts-id .bordered {
  margin-top: 36px;
}

.top-number-form {
  text-align: right;
  margin-bottom: 10px;

  &>span {
    margin-left: 10px;
  }
}

.rainfall-export {
  text-align: right;
  margin-bottom: 10px;
}
</style>
