<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="支持关键字查询"
          />
          <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 #toolbar>
            <Authority value="api:sw:hhgl:add">
              <a-button type="primary" @click="handleCreate">新增</a-button>
            </Authority>
            <!-- <Authority value="api:sw:hhgl:allDdd">
              <Popconfirm
                title="您确定要批量删除数据"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDeleteOrBatchDelete"
              >
                <a-button type="primary" color="error" :disabled="!hasSelected">
                  批量删除
                </a-button>
              </Popconfirm>
            </Authority> -->
            <Authority>
              <a-button type="primary" @click="exportDataFn">导出</a-button>
            </Authority>
          </template>
          <template #action="{ record }">
            <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: handleViewEidt.bind(null, record),
                },
                {
                  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-date-picker
                    mode="year"
                    format="YYYY"
                    placeholder="选择年份"
                    class="custom-input"
                    v-model:value="dataCenter.year"
                    @panelChange="yearPick"
                    @openChange="yearStatus"
                    :open="dataCenter.isopen"
                  />
                </a-col>
                <a-col :span="12">
                  <span class="span-label"> 洪峰流量(m³/s): </span>
                  <!-- {{ dataCenter.optionArr }} -->
                  <a-input
                    v-model:value="dataCenter.min"
                    style="width: calc(50% - 80px); text-align: center"
                    placeholder="最小值"
                  />
                  <a-input
                    style="
                      width: 30px;
                      border-left: 0;
                      pointer-events: none;
                      background-color: #fff;
                    "
                    placeholder="~"
                    disabled
                  />
                  <a-input
                    v-model:value="dataCenter.max"
                    style="width: calc(50% - 80px); text-align: center; border-left: 0"
                    placeholder="最大值"
                  />
                </a-col>
              </a-row>
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
    <BasicModal
      :maskClosable="false"
      id="honghao-modal"
      :footer="null"
      @cancel="cancel"
      :visible="dataCenter.showModal"
      :width="1200"
      :canFullscreen="false"
      :minHeight="600"
      :title="dataCenter.title"
    >
      <div class="honghao-modal-flex">
        <div class="box-basic" id="charts-box-honghao"> </div>
        <div class="table-list">
          <div class="right-box">
            <div>
              <ul>
                <li>
                  <div>时间</div>
                  <div>流量（m³/s）</div>
                </li>
                <li v-for="(item, index) in dataCenter.activeCharts.t" :key="index">
                  <div>{{ item }}</div>
                  <div>{{ dataCenter.activeCharts.q[index] }}</div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </BasicModal>
    <AccountModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { computed, defineComponent, ref, watch, onMounted, reactive } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { getTransectTree, getFcodeCalTree, fcodeDelte, getDetailsShow } from '/@/api/swHome/index';
import moment, { Moment } from 'moment';
import { message, Popconfirm } from 'ant-design-vue';
import { BasicModal } from '/@/components/Modal/index';
import * as echarts from 'echarts';
import { useModal } from '/@/components/Modal';
import { exportData } from '/@/utils/fnUtils.ts';
//弹窗开始
import AccountModal from './components/AccountModal.vue';
const [registerModal, { openModal }] = useModal();
function cancel() {
  dataCenter.showModal = false;
}
let dataCenter = reactive({
  title: '',
  showModal: false,
  hasBatchDelete: true,
  activeData: {},
  year: '',
  treeList: [],
  isopen: false,
  min: '',
  max: '',
  columns: [
    {
      title: '洪水编号',
      dataIndex: 'fcode',
      key: 'fcode',
    },
    {
      title: '开始时间',
      dataIndex: 'stime',
      key: 'stime',
    },
    {
      title: '结束时间',
      dataIndex: 'etime',
      key: 'etime',
    },
    {
      title: '洪量',
      dataIndex: 'volume',
      key: 'volume',
    },
    {
      title: '洪峰流量',
      dataIndex: 'peak',
      key: 'peak',
    },
    {
      title: '峰现时间',
      dataIndex: 'peaktime',
      key: 'peaktime',
    },
  ],
  searchFormSchema: [],
  listData: [],
  activeCharts: {},
});
// 新增
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) {
  console.log(e.node.dataRef);
  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 getgetFcodeCalTreeData(keyId) {
  getFcodeCalTree({ pid: keyId }).then((res) => {
    console.log(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 hasSelected = computed(() => {
  // const rowSelection = getRowSelection();
  // return rowSelection.selectedRowKeys?.length;
});
function submitFunc() {
  let arr = [];
  if (!dataCenter.year && !dataCenter.min && !dataCenter.max) {
    setTableData(dataCenter.listData);
  } else if (dataCenter.year && !dataCenter.min && !dataCenter.max) {
    dataCenter.listData.forEach((element) => {
      if (
        element.stime.indexOf(dataCenter.year) != -1 ||
        element.etime.indexOf(dataCenter.year) != -1
      ) {
        arr.push(element);
      }
    });
    setTableData(arr);
  } else if (!dataCenter.year && dataCenter.min && dataCenter.max) {
    dataCenter.listData.forEach((element) => {
      if (dataCenter.min <= element.peak && element.peak <= dataCenter.max) {
        arr.push(element);
      }
    });
    setTableData(arr);
  } else if (dataCenter.year && dataCenter.min && dataCenter.max) {
    let arr1 = [];
    dataCenter.listData.forEach((element) => {
      if (dataCenter.min <= element.peak && element.peak <= dataCenter.max) {
        arr1.push(element);
      }
    });
    arr1.forEach((element) => {
      if (
        element.stime.indexOf(dataCenter.year) != -1 ||
        element.etime.indexOf(dataCenter.year) != -1
      ) {
        arr.push(element);
      }
    });
    setTableData(arr);
  } else {
    message.info('请完善查询条件');
  }
}
function resetFunc() {
  dataCenter.year = '';
  dataCenter.min = '';
  dataCenter.max = '';
  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);
  });
};
function yearPick(e) {
  // 选择年
  dataCenter.year = moment(e).format('YYYY');
  dataCenter.isopen = false;
}
function yearStatus(status) {
  // 选择年后，关闭弹窗
  if (status) {
    dataCenter.isopen = true;
  } else {
    dataCenter.isopen = false;
  }
}
// 查看详情
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) => {
    console.log(res);
    dataCenter.activeCharts = res.data;
    setTimeout(() => {
      setCharts();
    }, 100);
  });
  dataCenter.showModal = true;
};
// 删除
const handleViewdel = (record) => {
  console.log(record);
  console.log(dataCenter.activeData);
  let obj = [{ fcode: record.fcode, pid: dataCenter.activeData.keyid }];
  fcodeDelte(obj)
    .then((res) => {
      if (res.code == 200) {
        getgetFcodeCalTreeData(dataCenter.activeData.keyid);
        message.success(res.msg);
      } else {
        message.error(res.msg);
      }
    })
    .catch(() => {
      message.error('删除失败！');
    });
};
// 编辑
const handleViewEidt = (record) => {
  record.pid = dataCenter.activeData.keyid;
  openModal(true, {
    isUpdate: true,
    formData: record,
  });
};
// 批量删除
function handleDeleteOrBatchDelete() {
  let dataArr = getRowSelection().selectedRowKeys;
  let arr = [];
  dataArr.forEach((element) => {
    let obj = {
      pid: dataCenter.activeData.keyid,
    };
    obj.fcode = element;
    arr.push(obj);
  });

  fcodeDelte(arr)
    .then((res) => {
      if (res.code == 200) {
        getgetFcodeCalTreeData(dataCenter.activeData.keyid);
        message.success(res.msg);
      } else {
        message.error(res.msg);
      }
    })
    .catch(() => {
      message.error('删除失败！');
    });
}
let chart = null;
function setCharts() {
  chart = echarts.init(document.getElementById('charts-box-honghao'));
  let option = {
    toolbox: {
      feature: {
        saveAsImage: {
          name:dataCenter.title
        }
      }
    },
    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');
      }),
      axisLabel: {
        //x轴文字的配置
        show: true,
        rotate: '45',
        interval:dataCenter.activeCharts.t.length/(dataCenter.activeCharts.t.length/2),
        formatter: function (val) {
          var strs = val.split(''); //字符串数组
          var str = '';
          console.log(strs)
          for (var i = 0, s; (s = strs[i++]); ) {
            //遍历字符串数组
            if (i >= 0 && i < 11) {
              str += s;
            }
            if(i == 12){
              str += ' ';
            }
            if (i >= 12 && i <= 13) {
              str += s;
            }
            if(i == 13){
              str += '时';
            }
          }
          console.log(str)
          return str;
        },
      },
    },
    yAxis: {
      type: 'value',
      scale: true,
    },
    series: [
      {
        name: '实测流量',
        type: 'line',
        stack: 'Total',
        data: dataCenter.activeCharts.q,
        smooth: true
      },
    ],
  };
  option && chart.setOption(option);
}
const exportDataFn = () => {
  console.log(getColumns())
  console.log(getDataSource())
  exportData(getColumns(),getDataSource(),'洪号管理.xlsx')
}
onMounted(() => {
  getTransectTreeData();
});
</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 {
  flex: 1;
  height: 600px;
}
.honghao-modal-flex {
  display: flex;
  .table-list {
    width: 400px;
  }
  .right-box {
    width: 400px;
    height: 600px;
    overflow: auto;
    margin-left: 20px;
    position: relative;
    ul {
      // position: relative;
      li {
        display: flex;
        line-height: 36px;
        & > div {
          // flex: 1;
          text-align: center;
        }
        & > div:nth-child(1) {
          min-width: 180px;
        }
        & > div:nth-child(2) {
          flex: 1;
        }
        & > div:nth-child(3) {
          flex: 1;
        }
      }
      li:nth-child(1) {
        position: absolute;
        width: 100%;
      }
      li:nth-child(2) {
        padding-top: 36px;
      }
    }
  }
}
</style>
