<template>
  <div class="main">
    <div class="main-box">
      <div>
        <div class="title">断面列表</div>
        <div class="content-tree">
          <a-input-search
            v-model:value="searchValue"
            style="margin-bottom: 8px"
            placeholder="支持关键字查询"
          />
          <!-- 新增 -->
          <div class="duanmian-btn">
            <a-button size="small" @click="showSection" type="primary">新增断面</a-button>
          </div>
          <a-tree
            :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>
        <!-- 列表区域 -->
        <BasicTable :clickToRowSelect="false" @register="registerTable">
          <!-- 雨量站 -->
          <template #stcd_p="{ text, record }">
            <div>
              <a-select
                v-if="dataCenter.editableData[record.ordern]"
                v-model:value="dataCenter.editableData[record.ordern]['stcd_p']"
                style="width: 120px"
              >
                <a-select-option
                  v-for="(item, index) in dataCenter.rainfall"
                  :key="index"
                  :value="item.stcd_q"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
              <template v-else>
                {{ setSpinner(text, dataCenter.rainfall, 'stcd_q') }}
              </template>
            </div>
          </template>
          <!-- 气象站meteorological -->
          <template #stcd_m="{ text, record }">
            <div>
              <a-select
                v-if="dataCenter.editableData[record.ordern]"
                v-model:value="dataCenter.editableData[record.ordern]['stcd_m']"
                style="width: 120px"
              >
                <a-select-option
                  v-for="(item, index) in dataCenter.meteorological"
                  :key="index"
                  :value="item.stcd_m"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
              <template v-else>
                {{ setSpinner(text, dataCenter.meteorological, 'stcd_m') }}
              </template>
            </div>
          </template>
          <!-- 河段数 -->
          <template #msk_num="{ text, record }">
            <div>
              <a-input-number
                v-if="dataCenter.editableData[record.ordern]"
                id="inputNumber"
                v-model:value="dataCenter.editableData[record.ordern]['msk_num']"
                :min="0"
                :step="1"
                :max="999"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <!-- 雨量站权重 -->
          <template #p_weight="{ text, record }">
            <div>
              <a-input-number
                v-if="dataCenter.editableData[record.ordern]"
                id="inputNumber"
                v-model:value="dataCenter.editableData[record.ordern]['p_weight']"
                :min="0"
                :step="0.01"
                :max="1"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <!-- 气象站权重 -->
          <template #m_weight="{ text, record }">
            <div>
              <a-input-number
                v-if="dataCenter.editableData[record.ordern]"
                id="inputNumber"
                v-model:value="dataCenter.editableData[record.ordern]['m_weight']"
                :min="0"
                :step="0.01"
                :max="1"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <!-- 回归参数 -->
          <template #coef="{ text, record }">
            <div>
              <a-input-number
                v-if="dataCenter.editableData[record.ordern]"
                id="inputNumber"
                v-model:value="dataCenter.editableData[record.ordern]['coef']"
                :min="0"
                :step="0.01"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <!-- 截距 -->
          <template #intercept="{ text, record }">
            <div>
              <a-input-number
                v-if="dataCenter.editableData[record.ordern]"
                id="inputNumber"
                v-model:value="dataCenter.editableData[record.ordern]['intercept']"
                :min="0"
                :step="0.01"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <!-- 上游来水站 upstream-->
          <template #stcd_inq="{ text, record }">
            <div>
              <a-select
                v-if="dataCenter.editableData[record.ordern]"
                v-model:value="dataCenter.editableData[record.ordern]['stcd_inq']"
                style="width: 120px"
              >
                <a-select-option
                  v-for="(item, index) in dataCenter.upstream"
                  :key="index"
                  :value="item.stcd_inq"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
              <template v-else>
                {{ setSpinner(text, dataCenter.upstream, 'stcd_inq') }}
              </template>
            </div>
          </template>
          <!-- 接入方案programme -->
          <template #stcd_inqup="{ text, record }">
            <div>
              <a-select
                v-if="dataCenter.editableData[record.ordern]"
                v-model:value="dataCenter.editableData[record.ordern]['stcd_inqup']"
                style="width: 120px"
              >
                <a-select-option
                  v-for="(item, index) in dataCenter.programme"
                  :key="index"
                  :value="item.stcd_inqup"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
              <template v-else>
                {{ setSpinner(text, dataCenter.programme, 'stcd_inqup') }}
              </template>
            </div>
          </template>
          <!-- 接入类型 -->
          <template #optimaze_type="{ text, record }">
            <div>
              <a-select
                v-if="dataCenter.editableData[record.ordern]"
                v-model:value="dataCenter.editableData[record.ordern]['optimaze_type']"
                style="width: 120px"
              >
                <a-select-option
                  v-for="(item, index) in dataCenter.accessType"
                  :key="index"
                  :value="item.optimaze_type"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
              <template v-else>
                {{ setSpinner(text, dataCenter.accessType, 'optimaze_type') }}
              </template>
            </div>
          </template>
          <template #toolbar>
            <Authority value="api:sw:hhgl:add">
              <a-button type="primary" @click="handleCreate">新增</a-button>
            </Authority>
            <Authority value="api:sw:hhgl:allDdd">
              <a-button type="primary" @click="handleDeleteOrBatchDelete" :disabled="!hasSelected">
                修改方案
              </a-button>
            </Authority>
            <!-- <Authority>
              <a-button type="primary" @click="exportDataFn">导出</a-button>
            </Authority> -->
          </template>
          <template #action="{ record }">
            <!-- v-if="dataCenter.editableData[record.ordern]" -->
            <!-- <div>{{dataCenter.editableData[record.ordern]}}</div> -->
            <TableAction
              :actions="[
                // {
                //   label: '详情',
                //   auth: 'api:sw:hhgl:detail',
                //   icon: 'clarity:info-standard-line',
                //   onClick: handleViewDetail.bind(null, record),
                // },
                {
                  label: '取消',
                  // auth: 'api:sw:hhgl:eidt',
                  icon: 'clarity:note-edit-line',
                  onClick: handleViewCancel.bind(null, record.ordern),
                  ifShow: dataCenter.editableData[record.ordern] ? true : false,
                },
                {
                  label: '保存',
                  // auth: 'api:sw:hhgl:eidt',
                  icon: 'clarity:note-edit-line',
                  onClick: handleViewSave.bind(null, record.ordern),
                  ifShow: dataCenter.editableData[record.ordern] ? true : false,
                },
                {
                  label: '编辑',
                  // auth: 'api:sw:hhgl:eidt',
                  icon: 'clarity:note-edit-line',
                  onClick: handleViewEidt.bind(null, record.ordern),
                  ifShow: dataCenter.editableData[record.ordern] ? false : true,
                },
                {
                  label: '删除',
                  // auth: 'api:sw:hhgl:del',
                  icon: 'ant-design:delete-outlined',
                  popConfirm: {
                    title: '是否确认删除',
                    confirm: handleViewdel.bind(null, record),
                  },
                },
              ]"
            />
          </template>
          <template #form-formHeader="{ model, field }">
            <div class="form-box">
              <a-row>
                <a-col :span="12">
                  <span class="span-label"> 预报模型: </span>
                  <a-select @change="modelChange" class="my-select" v-model:value="dataCenter.model" style="width: 120px">
                    <a-select-option
                      v-for="(item, index) in dataCenter.listData"
                      :key="item.model_id"
                      :value="item.scheme_id"
                      >{{ item.scheme_name }}</a-select-option
                    >
                  </a-select>
                </a-col>
              </a-row>
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
    <programmeModal @register="registerModal" @success="handleSuccess" />
    <sectionName @register="registerSection" @success="sectionSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { computed, defineComponent, createVNode, ref, watch, onMounted, reactive } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { exportData } from '/@/utils/fnUtils.ts';
import {
  getTransectTree,
  getTransectDetails,
  fcodeDelte,
  getDetailsShow,
  schemeAddSpinner,
  getSchemeShow,
  getSchemeSpinner,
  getSchemeUpdata,
  getSchemeDelete,
  postRegressionLinear,
  postRegressionLinearDel
} from '/@/api/swHome/index';
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage } = useMessage();
import { message } from 'ant-design-vue';
import * as echarts from 'echarts';
import { useModal } from '/@/components/Modal';
import { cloneDeep } from 'lodash-es';
import { Modal } from 'ant-design-vue';
//弹窗开始
import programmeModal from './components/programmeModal.vue';
//新增断面
import sectionName from './components/sectionName.vue';

const [registerModal, { openModal: openModal }] = useModal();
const [registerSection, { openModal: registerOpenModal }] = useModal();

let dataCenter = reactive({
  model_id:'',
  editableData: {},
  programme: [],
  accessType: [],
  upstream: [],
  dataSource: [],
  rainfall: [],
  meteorological: [],
  title: '',
  keywords: '',
  model: '',
  showModal: false,
  hasBatchDelete: true,
  activeData: {},
  year: '',
  treeList: [],
  isopen: false,
  min: '',
  max: '',
  columns: [
    {
      title: '方案号',
      dataIndex: 'scheme_id',
      key: 'scheme_id',
    },
    {
      title: '方案名称',
      dataIndex: 'scheme_name',
      key: 'scheme_name',
    },
    {
      title: '模型名称',
      dataIndex: 'model_name',
      key: 'model_name',
    },
    // {
    //   title: '区间来水站',
    //   dataIndex: 'stcd_a',
    //   key: 'stcd_a',
    // },
    {
      title: '雨量站',
      dataIndex: 'stcd_p',
      key: 'stcd_p',
      slots: { customRender: 'stcd_p' },
    },
    {
      title: '气象预报站',
      dataIndex: 'stcd_m',
      key: 'stcd_m',
      slots: { customRender: 'stcd_m' },
    },
    {
      title: '马斯京根河段数',
      dataIndex: 'msk_num',
      key: 'msk_num',
      slots: { customRender: 'msk_num' },
    },
    {
      title: '雨量站权重',
      dataIndex: 'p_weight',
      key: 'p_weight',
      slots: { customRender: 'p_weight' },
    },
    {
      title: '气象站权重',
      dataIndex: 'm_weight',
      key: 'm_weight',
      slots: { customRender: 'm_weight' },
    },
    {
      title: '上游来水站',
      dataIndex: 'stcd_inq',
      key: 'stcd_inq',
      slots: { customRender: 'stcd_inq' },
    },
    {
      title: '上游预报方案接入',
      dataIndex: 'stcd_inqup',
      key: 'stcd_inqup',
      slots: { customRender: 'stcd_inqup' },
    },
    {
      title: '接入类型',
      dataIndex: 'optimaze_type',
      key: 'optimaze_type',
      slots: { customRender: 'optimaze_type' },
    },
  ],
  columns2:[
    {
      title: '方案号',
      dataIndex: 'scheme_id',
      key: 'scheme_id',
    },
    {
      title: '方案名称',
      dataIndex: 'scheme_name',
      key: 'scheme_name',
    },
    {
      title: '模型名称',
      dataIndex: 'model_name',
      key: 'model_name',
    },
    {
      title: '回归参数',
      dataIndex: 'coef',
      key: 'coef',
      slots: { customRender: 'coef' },
    },
    {
      title: '截距',
      dataIndex: 'intercept',
      key: 'intercept',
      slots: { customRender: 'intercept' },
    },
    {
      title: '上游来水站',
      dataIndex: 'stcd_inq',
      key: 'stcd_inq',
      slots: { customRender: 'stcd_inq' },
    },
    {
      title: '上游预报方案接入',
      dataIndex: 'stcd_inqup',
      key: 'stcd_inqup',
      slots: { customRender: 'stcd_inqup' },
    },
    {
      title: '接入类型',
      dataIndex: 'optimaze_type',
      key: 'optimaze_type',
      slots: { customRender: 'optimaze_type' },
    },
  ],
  searchFormSchema: [],
  listData: [],
  activeCharts: {},
});
// 设置新增模型id
const modelChange = (value,e) => {
  dataCenter.model_id = e.key
  if(dataCenter.model_id == 76){
    setColumns(dataCenter.columns2)
  }else{
    setColumns(dataCenter.columns)
  }
}
function setSpinner(text, arr, name) {
  if(!arr){
    return text
  }
  for (let index = 0; index < arr.length; index++) {
    const element = arr[index];
    if (text == element[name]) {
      return element.name;
    }
  }
}
// 打开断面弹窗
function showSection() {
  registerOpenModal(true, {
    isUpdate: false,
  });
}
// 新增
function handleCreate() {
  openModal(true, {
    isUpdate: false,
  });
}
// 树状控件
const genData = ref([]);
const searchValue = ref('');
const expandedKeys = ref([]);
const autoExpandParent = ref(true);
const gData = ref(genData);
const dataList = [];
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);
  expandedKeys.value = expanded;
  searchValue.value = value;
  autoExpandParent.value = true;
});

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 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,
    });
    if (node.children) {
      generateList(node.children);
    }
  }
};
const onExpand = (keys) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};
function treeSelect(selectedKeys, e) {
  if (e.node.dataRef.children.length != 0) return;
  dataCenter.activeData = e.node.dataRef;
  getgetFcodeCalTreeData(e.node.dataRef.keyid);
}
function handleSuccess() {
  getgetFcodeCalTreeData(dataCenter.activeData.keyid);
}
function sectionSuccess() {
  getTransectTreeData();
}
function getgetFcodeCalTreeData(keyId) {
  getTransectDetails({ pid: keyId }).then((res) => {
    dataCenter.listData = res.data;
    // setTableData(res.data);
  });
}
// 表格控件
const [
  registerTable,
  { reload,getColumns,getDataSource, getForm, setColumns, getSelectRowKeys, getRowSelection, setTableData },
] = useTable({
  title: '方案管理',
  // api: getFcodeCalTree,
  columns: dataCenter.columns,
  showIndexColumn: true,
  clickToRowSelect: false,
  inset: true,
  formConfig: {
    labelWidth: 120,
    schemas: dataCenter.searchFormSchema,
    // 自定义提交逻辑
    submitFunc: submitFunc,
    // 自定义重置逻辑
    resetFunc: resetFunc,
  },
  // rowSelection: { type: 'checkbox' },
  tableSetting: {
    redo: false,
    setting: false,
  },
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  rowKey: 'fcode',
  actionColumn: {
    width: 200,
    title: '操作',
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: 'right',
  },
});
// 编辑数据
// const dataCenter.editableData = reactive({});
// 判断表格数据是否选中
const hasSelected = computed(() => {
  const rowSelection = getRowSelection();
  if(!rowSelection){
    return false
  }
  return rowSelection.selectedRowKeys?.length;
});
function tableList(pid) {
  getSchemeShow({ scheme_id: pid,model_id:dataCenter.model_id }).then((res) => {
    dataCenter.dataSource = res.data;
    setTableData(res.data);
  });
}
function submitFunc() {
  console.log(dataCenter.model);
  dataCenter.editableData = {};
  if (dataCenter.model) {
    // 查询列表数据
    tableList(dataCenter.model);
  } else {
    message.info('请完善查询条件');
  }
}
function resetFunc() {
  dataCenter.model = '';
  submitFunc();
}
const getTransectTreeData = () => {
  getTransectTree().then((res) => {
    dataCenter.treeList = res.data;
    genData.value = res.data[0].children;
    gData.value = res.data[0].children;
    generateList(res.data[0].children);
  });
};
// 查看详情
const handleViewDetail = async (record) => {
  dataCenter.title = `${dataCenter.activeData.title}(${record.fcode})-${record.stime}~${record.etime}`;
  // 获取详情图表
  getDetailsShow({
    pid: dataCenter.activeData.keyid,
    stime: record.stime,
    etime: record.etime,
  }).then((res) => {
    if (res.code == 200) {
      dataCenter.activeCharts = res.data;
      setTimeout(() => {
        setCharts();
      }, 100);
    }
  });
  dataCenter.showModal = true;
};
// 删除
const handleViewdel = (record) => {
  
  if(dataCenter.model_id == 76){
    let item = JSON.parse(JSON.stringify(record))
    item.model_id = 76
    postRegressionLinearDel([item]).then(res =>{
      if (res.code == 200) {
        tableList(dataCenter.model);
        createMessage.success('删除成功');
      }
    })
  }else{
    getSchemeDelete([
      {
        scheme_id: record.scheme_id,
        ordern: record.ordern,
      },
    ]).then((res) => {
      if (res.code == 200) {
        tableList(dataCenter.model);
        createMessage.success('删除成功');
      }
    });
  }
  
};
// 保存
const handleViewSave = (key) => {
  let data = Object.assign(
    dataCenter.dataSource.filter((item) => key === item.ordern)[0],
    dataCenter.editableData[key]
  );
  Modal.confirm({
    title: '确定修改该条方案？',
    content: '点击是或否',
    okText: '是',
    okType: 'danger',
    cancelText: '否',
    onOk: () => {
      //判断模型id是不是76
      if(dataCenter.model_id == 76){
        console.log(data)
        data.model_id = 76
        postRegressionLinear([data]).then(res => {
          if (res.code == 200) {
            // delete dataCenter.editableData[key];
            dataCenter.editableData = {};
            tableList(dataCenter.model);
            createMessage.success('保存成功');
          }
        })
      }else{
        // 调用保存数据
        getSchemeUpdata([data]).then((res) => {
          if (res.code == 200) {
            // delete dataCenter.editableData[key];
            dataCenter.editableData = {};
            tableList(dataCenter.model);
            createMessage.success('保存成功');
          }
        });
      }
    },
  });
};
// 编辑
const handleViewEidt = (key) => {
  dataCenter.editableData[key] = cloneDeep(
    dataCenter.dataSource.filter((item) => key === item.ordern)[0]
  );
};
// 取消
const handleViewCancel = (key) => {
  delete dataCenter.editableData[key];
};
// 总体保存
function handleDeleteOrBatchDelete() {
  Modal.confirm({
    title: '方案整体修改会导致产汇流过程变化，是否修改？',
    content: '点击是或否',
    okText: '是',
    okType: 'danger',
    cancelText: '否',
    onOk: () => {
      // 调用保存数据
      let dataArr = getRowSelection().selectedRowKeys;
      let data = [];
      dataArr.forEach((element) => {
        data.push(dataCenter.dataSource[element]);
      });
      getSchemeUpdata(data).then((res) => {
        if (res.code == 200) {
          // delete dataCenter.editableData[key];
          dataCenter.editableData = {};
          tableList(dataCenter.model);
          createMessage.success('保存成功');
        }
      });
    },
  });
}
let chart = null;
function setCharts() {
  chart = echarts.init(document.getElementById('charts-box-honghao'));
  let option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['实测流量'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dataCenter.activeCharts.t.map(function (str) {
        return str.replace(' ', '\n');
      }),
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '实测流量',
        type: 'line',
        stack: 'Total',
        data: dataCenter.activeCharts.q,
      },
    ],
  };
  option && chart.setOption(option);
}
function getselectData() {
  // 雨量站
  getSchemeSpinner({ colume_id: 'stcd_p' }).then((res) => {
    res.data.forEach(element => {
      element.stcd_q = element.stcd_q+''
    });
    dataCenter.rainfall = res.data;
  });
  // 气象站
  getSchemeSpinner({ colume_id: 'stcd_m' }).then((res) => {
    res.data.forEach(element => {
      element.stcd_m = element.stcd_m+''
    });
    dataCenter.meteorological = res.data;
  });
  // 上游来水站
  getSchemeSpinner({ colume_id: 'stcd_inq' }).then((res) => {
    res.data.forEach(element => {
      element.stcd_inq = element.stcd_inq+''
    });
    dataCenter.upstream = res.data;
  });
  // 上游预报方案
  getSchemeSpinner({ colume_id: 'stcd_inqup' }).then((res) => {
    res.data.forEach(element => {
      element.stcd_inqup = element.stcd_inqup+''
    });
    dataCenter.programme = res.data;
  });
  // 接入类型
  getSchemeSpinner({ colume_id: 'optimaze_type' }).then((res) => {
    dataCenter.accessType = res.data;
  });
}
const exportDataFn = () => {
  console.log(getColumns())
  console.log(getDataSource())
  exportData(getColumns(),getDataSource(),'方案管理.xlsx')
}
onMounted(() => {
  getTransectTreeData();
  getselectData();
  // 获取预报模型
  schemeAddSpinner({ colume_id: 'model_id' }).then((res) => {
    console.log(res);
  });
});
</script>

<style scoped lang="less">
.main-box {
  display: flex;
  & > 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;
      ul {
        padding: 10px;
        li {
          border-left: 4px solid transparent;
          padding-left: 10px;
          margin: 10px 0 10px 0;
        }
        .active-list {
          border-left: 4px solid #2083e8;
        }
      }
    }
  }
  & > div:nth-child(2) {
    flex: 1;
    overflow: hidden;
  }
}
.form-box {
  position: absolute;
  z-index: 9;
  width: 66.666666%;
  .custom-input {
    width: calc(100% - 120px);
  }
}
.span-label {
  width: 120px;
  padding-right: 10px;
  display: inline-block;
  text-align: right;
  line-height: 32px;
}
::v-deep .vben-basic-table-form-container {
  padding: 0 !important;
  padding-left: 10px !important;
}
.box-basic {
  width: 100%;
  height: 600px;
}
.my-select {
  width: calc(100% - 120px) !important;
  display: inline-block;
}
.duanmian-btn {
  text-align: right;
}
</style>
