<template>
  <div class="menu-content">
    <div class="gradient-text title">雨情监测</div>
    <div class="card-header">
      <div class="title-box">水利站点降雨分布统计</div>
      <el-select
        v-model="timeOption"
        class="custom-select"
        popper-class="custom-select-popper"
        :teleported="false"
        style="width: 236px"
        @change="handleTimeChange"
      >
        <el-option v-for="item in timeOptions" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
    </div>
    <Chart :option="chartOption1" style="width: 100%; height: 505px" />
    <div class="card-header">
      <div class="title-box">
        <div>降雨量排行</div>
        <div class="line"></div>
        <div class="gradient-text text2">区县排行</div>
        <div class="text3">（过去{{ timeOption }}小时）</div>
      </div>
      <div class="btn-box">
        <div class="btn" @click="handleShowMore">
          <i class="more-icon"></i>
          <div class="btn-text">更多</div>
        </div>
        <div class="btn" @click="exportData">
          <i class="export-icon"></i>
          <div class="btn-text">导出</div>
        </div>
      </div>
    </div>
    <div class="table">
      <div class="table-header">
        <div class="td">序号</div>
        <div class="td">
          <div style="width: 201px">
            <el-select
              v-model="queryParams.area"
              placeholder="县区"
              size="large"
              class="custom-select2"
              popper-class="custom-select-popper2"
              :teleported="false"
            >
              <el-option label="县区" value="" />
              <el-option v-for="item in district_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
        </div>
        <div class="td">
          <el-select
            v-model="queryParams.township"
            placeholder="街镇"
            size="large"
            class="custom-select2"
            popper-class="custom-select-popper2"
            :teleported="false"
            @change="handleGetRainfallRange"
          >
            <el-option label="街镇" value="" />
            <el-option v-for="item in townshipList" :key="item.area_code" :label="item.area_name" :value="item.area_name" />
          </el-select>
        </div>
        <div class="td">站址</div>
        <div class="td td-cursor">
          <span>雨量(mm)</span>
          <i :class="queryParams.sort === 'desc' ? 'desc-icon' : 'asc-icon'" @click="handleSort" />
        </div>
      </div>
      <div v-for="(item, index) in rangeData" :key="index" class="tr">
        <div class="td">
          <div :class="getRankClass(item.rn)">{{ item.rn }}</div>
        </div>
        <div class="td">{{ item.area }}</div>
        <div class="td">{{ item.township }}</div>
        <div class="td">{{ item.address }}</div>
        <div class="gradient-text2 td">{{ item.rainfall }}</div>
      </div>
    </div>
    <div class="card-header">
      <div class="title-box">
        <div>影响分析</div>
      </div>
      <div class="btn-box">
        <div class="btn" @click="exportData2">
          <i class="export-icon"></i>
          <div class="btn-text">导出</div>
        </div>
      </div>
    </div>
    <div class="data-box">
      <div>
        <div class="line1">
          <div class="line-item">小雨</div>
          <div class="line-item">中雨</div>
          <div class="line-item">大雨</div>
          <div class="line-item">暴雨</div>
          <div class="line-item">大暴雨</div>
          <div class="line-item">特大暴雨</div>
        </div>
        <div ref="lineRef" class="line2" @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
          <div class="line-item"></div>
          <div class="line-item"></div>
          <div class="line-item"></div>
          <div class="line-item"></div>
          <div class="line-item"></div>
          <div class="line-item"></div>
          <div
            class="dot"
            :style="{ left: startLeft + 'px' }"
            @mousedown="
              (e) => {
                handleMouseDown(e, 'start');
              }
            "
          ></div>
          <div
            class="dot"
            :style="{ left: endLeft + 'px' }"
            @mousedown="
              (e) => {
                handleMouseDown(e, 'end');
              }
            "
          ></div>
        </div>
        <div class="line3">
          <div class="line-item">1</div>
          <div class="line-item">10</div>
          <div class="line-item">25</div>
          <div class="line-item">50</div>
          <div class="line-item">100</div>
          <div class="line-item">
            <div>250</div>
            <div>(mm)</div>
          </div>
        </div>
      </div>
      <div class="box">
        <div class="text1">雨量范围</div>
        <div class="text2">{{ rainRange[0] }}-{{ rainRange[1] }}</div>
      </div>
    </div>
    <div class="data-box2">
      <div class="data-item">
        <div class="icon1"></div>
        <div class="item-right">
          <div class="text-box">
            <div class="text1">行政镇</div>
            <div class="text2">(个)</div>
          </div>
          <div class="text3">{{ analyzeData.town_num }}</div>
        </div>
      </div>
      <div class="data-item">
        <div class="icon2"></div>
        <div class="item-right">
          <div class="text-box">
            <div class="text1">人口</div>
            <div class="text2">(万)</div>
          </div>
          <div class="text4">{{ analyzeData.populationSize }}</div>
        </div>
      </div>
      <div class="data-item">
        <div class="icon3"></div>
        <div class="item-right">
          <div class="text-box">
            <div class="text1">面积</div>
            <div class="text2">(km²)</div>
          </div>
          <div class="text5">{{ analyzeData.areaSize }}</div>
        </div>
      </div>
      <div class="data-item">
        <div class="icon4"></div>
        <div class="item-right">
          <div class="text-box">
            <div class="text1">GDP</div>
            <div class="text2">(亿)</div>
          </div>
          <div class="text6">{{ analyzeData.GDP }}</div>
        </div>
      </div>
    </div>
  </div>
  <RainRank v-if="showMore" v-model="showMore" />
</template>

<script lang="ts" setup name="RainMonitor">
import { option6 } from '../echartOptions';
import { graphic } from 'echarts';
import {
  getRainfallRange1,
  getRainfallRange2,
  getRainfallStatisticsCount,
  getRainfallTownDataExport,
  getRainfallTownNumCount
} from '@/api/globalMap/rainMonitor';
import RainRank from '@/views/globalMap/RightMenu/RainMonitor/RainRank.vue';
import * as XLSX from 'xlsx';
import { getNextAreaInfo } from '@/api/common';
import BigNumber from 'bignumber.js';
import { useDebounce } from '@vueuse/core';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { district_type } = toRefs<any>(proxy?.useDict('district_type'));
const containerScale = inject('containerScale');
const timeOptions = reactive([
  { name: '1小时', value: '1' },
  { name: '3小时', value: '3' },
  { name: '6小时', value: '6' },
  { name: '12小时', value: '12' },
  { name: '24小时', value: '24' },
  { name: '242小时', value: '10000' }
]);
// 水利站点降雨分布统计
let timeOption = ref('24');
const handleTimeChange = () => {
  initData();
};
const chartOption1 = ref(option6);
const handleGetRainfallStatisticsCount = () => {
  getRainfallStatisticsCount(timeOption.value).then((res) => {
    const data = res.rows && res.rows.length > 0 ? res.rows.reverse() : [];
    const colorList = [
      [168, 204, 221],
      [67, 147, 255],
      [1, 251, 230],
      [151, 213, 100],
      [232, 161, 22],
      [251, 46, 60]
    ];
    let yData = [];
    let filterData = [];
    data.forEach((item, index) => {
      const color = colorList[index];
      yData.push(item.name);
      filterData.push({
        value: item.num,
        itemStyle: {
          color: new graphic.LinearGradient(1, 0, 0, 0, [
            {
              offset: 0,
              color: `rgba(${color[0]},${color[1]},${color[2]}, 1)`
            },
            {
              offset: 1,
              color: `rgba(${color[0]},${color[1]},${color[2]}, 0.1)`
            }
          ])
        },
        label: {
          show: true,
          distance: 18,
          textStyle: {
            color: '#a7ccdf',
            fontSize: 32,
            fontWeight: 'bold'
          },
          position: 'right'
        }
      });
    });
    chartOption1.value.yAxis.data = yData;
    chartOption1.value.series[0].data = filterData;
  });
};
// 降雨量排行榜
// true 降序
const rangeData = ref([]);
const queryParams = reactive({
  current: 1,
  size: 5,
  area: '',
  township: '',
  sort: 'desc'
});
const townshipList = ref([]);
let showMore = ref(false);
const getRankClass = (rank) => {
  let res = 'rank-other';
  if (rank === 1) {
    res = 'rank1';
  } else if (rank === 2) {
    res = 'rank2';
  } else if (rank === 3) {
    res = 'rank3';
  }
  return res;
};
const handleGetRainfallRange = () => {
  let area = '';
  for (let i = 0; i < district_type.value.length; i++) {
    if (district_type.value[i].value === queryParams.area) {
      area = district_type.value[i].label;
    }
  }
  const params = {
    current: queryParams.current,
    size: queryParams.size,
    query: {
      area: area,
      township: queryParams.township,
      sort: queryParams.sort,
      timeOption: timeOption.value
    }
  };
  getRainfallRange2(params).then((res) => {
    rangeData.value = res.rows;
  });
};
watch(
  () => queryParams.area,
  () => {
    queryParams.township = '';
    townshipList.value = [];
    if (queryParams.area) {
      getNextAreaInfo(queryParams.area).then((res) => {
        townshipList.value = res.data.list;
      });
    }
    handleGetRainfallRange();
  },
  { immediate: true }
);
const handleSort = () => {
  if (queryParams.sort === 'desc') {
    queryParams.sort = 'asc';
  } else {
    queryParams.sort = 'desc';
  }
  handleGetRainfallRange();
};
const handleShowMore = () => {
  showMore.value = true;
};
// 影响分析
const rainRange = reactive(['25', '50']);
const analyzeData = ref({
  GDP: 0,
  areaSize: 0,
  populationSize: 0,
  town_num: 0
});
const lineRef = ref();
const startLeft = ref(384);
const endLeft = ref(576);
const mouseStatus = reactive({
  move: false,
  type: '',
  downLeft: 0,
  left: 0
});
const handleMouseDown = (event, type) => {
  event.preventDefault();
  // 获取目标元素的边界框
  const rect = lineRef.value.getBoundingClientRect();
  // 获取鼠标位置
  const mouseX = event.clientX;
  mouseStatus.move = true;
  mouseStatus.type = type;
  // mouseStatus.downLeft = mouseX - rect.left;
  mouseStatus.downLeft = mouseX;
  if (type === 'start') {
    mouseStatus.left = startLeft.value;
  } else {
    mouseStatus.left = endLeft.value;
  }
};
const handleMouseMove = (event) => {
  if (!mouseStatus.move) return;
  event.preventDefault();
  // 获取鼠标位置
  const mouseX = event.clientX;
  let distance = mouseX - mouseStatus.downLeft;
  let value = mouseStatus.left + distance / containerScale().scaleX;
  if (mouseStatus.type === 'start') {
    startLeft.value = value >= 0 ? value : 0;
  } else {
    endLeft.value = value <= 1152 ? value : 1152;
  }
};
const handleMouseUp = (event) => {
  event.preventDefault();
  mouseStatus.move = false;
  mouseStatus.type = '';
  mouseStatus.downLeft = 0;
  mouseStatus.left = 0;
};
const getRainRange = () => {
  getRainfallTownNumCount({
    query: {
      start_num: rainRange[0],
      end_num: rainRange[1],
      timeOption: timeOption.value
    }
  }).then((res) => {
    analyzeData.value = res.rows[0];
  });
};
useDebounce(getRainRange, 1000);
watch(startLeft, () => {
  getNewRange(0, startLeft.value);
  useDebounceFn(getRainRange, 1000);
});
watch(endLeft, () => {
  getNewRange(1, endLeft.value);
  useDebounceFn(getRainRange, 1000);
});
const getNewRange = (index, value) => {
  if (value >= 0 && value < 192) {
    const data = new BigNumber(value).dividedBy(new BigNumber(19.2)).toFixed(0);
    rainRange[index] = data;
  } else if (value >= 192 && value < 384) {
    const data = new BigNumber(value).minus(new BigNumber(192)).dividedBy(new BigNumber(12.8)).plus(new BigNumber(10)).toFixed(0);
    rainRange[index] = data;
  } else if (value >= 384 && value < 576) {
    const data = new BigNumber(value).minus(new BigNumber(384)).dividedBy(new BigNumber(7.68)).plus(new BigNumber(25)).toFixed(0);
    rainRange[index] = data;
  } else if (value >= 576 && value < 768) {
    const data = new BigNumber(value).minus(new BigNumber(576)).dividedBy(new BigNumber(3.84)).plus(new BigNumber(50)).toFixed(0);
    rainRange[index] = data;
  } else if (value >= 768 && value < 960) {
    const data = new BigNumber(value).minus(new BigNumber(768)).dividedBy(new BigNumber(1.28)).plus(new BigNumber(100)).toFixed(0);
    rainRange[index] = data;
  } else if (value >= 960 && value < 1152) {
    const data = new BigNumber(value).minus(new BigNumber(960)).dividedBy(new BigNumber(1.28)).plus(new BigNumber(250)).toFixed(0);
    rainRange[index] = data;
  }
};
const initData = () => {
  handleGetRainfallStatisticsCount();
  handleGetRainfallRange();
  getRainRange();
};
const exportData = () => {
  const params = {
    area: queryParams.area,
    township: queryParams.township,
    sort: queryParams.sort,
    timeOption: timeOption.value
  };
  getRainfallRange1(params).then((res) => {
    const data = res.data.list;
    const title = '降雨量排行(过去' + timeOption.value + '小时)';
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 创建工作表数据
    const ws_data = [['序号', '县区', '街镇', '站址', '雨量(mm)']];
    data.forEach((item) => {
      ws_data.push([item.rn, item.area, item.township, item.address, item.rainfall]);
    });
    const ws = XLSX.utils.aoa_to_sheet(ws_data);
    ws['!cols'] = [{ wch: 10 }, { wch: 15 }, { wch: 15 }, { wch: 50 }, { wch: 10 }];
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    // 导出Excel文件
    XLSX.writeFile(wb, title + '.xlsx');
  });
};
const exportData2 = () => {
  const params = {
    area: '',
    township: '',
    sort: queryParams.sort,
    timeOption: timeOption.value
  };
  getRainfallTownDataExport(params).then((res) => {
    const data = res.data.list;
    const title = '影响分析(过去' + timeOption.value + '小时)';
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 创建工作表数据
    const ws_data = [['雨量范围', '行政镇', '人口(万)', '面积(km²)', 'GDP(亿)']];
    const rainList = {
      '小雨': '小雨(0-9)',
      '中雨': '中雨(10-24)',
      '大雨': '大雨(25-49)',
      '暴雨': '暴雨(50-99)',
      '大暴雨': '大暴雨(100-249)',
      '特大暴雨': '特大暴雨(>250)'
    };
    data.forEach((item) => {
      ws_data.push([rainList[item.rain_type], item.town_num, item.populationSize, item.areaSize, item.GDP]);
    });
    // 将数据转换为工作表，并添加合并单元格的配置
    const ws = XLSX.utils.aoa_to_sheet(ws_data);
    ws['!cols'] = [{ wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }];
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    // 导出Excel文件
    XLSX.writeFile(wb, title + '.xlsx');
  });
};
initData();
</script>

<style lang="scss" scoped>
.menu-content {
  width: 1589px;
  height: 2071px;
  background: url('@/assets/images/map/rightMenu/rainMonitor/dialog.png') no-repeat;
  padding: 130px 20px 20px 20px;
  font-size: 36px;
  position: relative;
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 35px;
    .title-box {
      background-image: url('@/assets/images/map/rightMenu/rainMonitor/titleBox.png');
      background-repeat: no-repeat;
      background-size: 370px 35px;
      background-position: bottom left;
      font-size: 44px;
      color: #fff;
      padding-left: 50px;
      display: flex;
      align-items: center;
      .line {
        background-color: #dce2ec;
        width: 3px;
        height: 44px;
        margin: 0 30px;
      }
      .text2 {
        font-size: 44px;
      }
      .text3 {
        font-size: 38px;
        color: #a7ccdf;
      }
    }
    .btn-box {
      display: flex;
      align-items: center;
      .btn {
        width: 244px;
        height: 120px;
        background: url('@/assets/images/map/rightMenu/rainMonitor/btn.png') no-repeat;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        .more-icon {
          width: 47px;
          height: 43px;
          background: url('@/assets/images/map/rightMenu/rainMonitor/more.png') no-repeat;
          margin-right: 5px;
        }
        .export-icon {
          width: 43px;
          height: 45px;
          background: url('@/assets/images/map/rightMenu/rainMonitor/export.png') no-repeat;
          margin-right: 5px;
        }
        .btn-text {
          color: #edfaff;
          font-size: 32px;
        }
      }
    }
  }
}
.table {
  margin-left: 28px;
  .table-header {
    width: 1490px;
    height: 88px;
    background: url('@/assets/images/common/header.png') no-repeat;
    display: flex;
    align-items: center;
    .td-cursor {
      cursor: pointer;
    }
  }
  .tr {
    width: 1487px;
    height: 88px;
    background: url('@/assets/images/common/tr.png') no-repeat;
    display: flex;
    align-items: center;
    margin-top: 10px;
    .td {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  .gradient-text2 {
    color: transparent !important;
  }
  .td {
    font-size: 38px;
    color: #edfaff;
    display: flex;
    justify-content: center;
    align-items: center;
    &:nth-child(1) {
      width: 140px;
    }
    &:nth-child(2) {
      width: 220px;
    }
    &:nth-child(3) {
      width: 280px;
    }
    &:nth-child(4) {
      flex: 1;
    }
    &:nth-child(5) {
      width: 230px;
    }
  }
  .down-icon {
    display: inline-block;
    width: 33px;
    height: 15px;
    background: url('@/assets/images/map/rightMenu/rainMonitor/down.png') no-repeat;
    cursor: pointer;
    margin-left: 8px;
  }
  .asc-icon {
    display: inline-block;
    width: 33px;
    height: 33px;
    background: url('@/assets/images/common/asc.png') no-repeat;
    cursor: pointer;
    margin-left: 8px;
  }
  .desc-icon {
    display: inline-block;
    width: 33px;
    height: 33px;
    background: url('@/assets/images/common/desc.png') no-repeat;
    cursor: pointer;
    margin-left: 8px;
  }
  .rank1,
  .rank2,
  .rank3,
  .rank-other {
    width: 50px;
    height: 48px;
    color: #ecfaff;
    font-family: BEBAS-1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .rank1 {
    height: 47px;
    background: url('@/assets/images/map/rightMenu/rainMonitor/first.png') no-repeat;
  }
  .rank2 {
    background: url('@/assets/images/map/rightMenu/rainMonitor/second.png') no-repeat;
  }
  .rank3 {
    background: url('@/assets/images/map/rightMenu/rainMonitor/third.png') no-repeat;
  }
  .rank-other {
    background: url('@/assets/images/map/rightMenu/rainMonitor/other.png') no-repeat;
  }
}
.data-box {
  width: 1495px;
  height: 172px;
  background: url('@/assets/images/map/rightMenu/rainMonitor/box1.png') no-repeat;
  margin-left: 28px;
  color: #a7ccdf;
  padding-left: 50px;
  padding-top: 20px;
  font-size: 32px;
  display: flex;
  .line1 {
    display: flex;
    .line-item {
      width: 192.46px;
    }
  }
  .line2 {
    display: flex;
    margin: 10px 0;
    position: relative;
    .dot {
      width: 65px;
      height: 65px;
      background: url('@/assets/images/map/rightMenu/rainMonitor/dot.png') no-repeat;
      cursor: pointer;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      margin-left: -32.5px;
    }
    .line-item {
      width: 192px;
      height: 30px;
      &:nth-child(1) {
        border-bottom-left-radius: 30px;
        border-top-left-radius: 30px;
        background-color: #a8ccdd;
      }
      &:nth-child(2) {
        background-color: #2b81ff;
      }
      &:nth-child(3) {
        background-color: #00fce6;
      }
      &:nth-child(4) {
        background-color: #97d664;
      }
      &:nth-child(5) {
        background-color: #ffaf00;
      }
      &:nth-child(6) {
        border-bottom-right-radius: 30px;
        border-top-right-radius: 30px;
        background-color: #ff2e3b;
      }
    }
  }
  .line3 {
    display: flex;
    .line-item {
      width: 192.46px;
      &:last-child {
        display: flex;
        justify-content: space-between;
      }
    }
  }
  .box {
    width: 203px;
    height: 119px;
    background: url('@/assets/images/map/rightMenu/rainMonitor/box2.png') no-repeat;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-left: 40px;
    margin-top: 5px;
    .text1 {
      font-size: 32px;
      color: #a7ccdf;
    }
    .text2 {
      font-size: 38px;
      font-family: BEBAS-1;
      color: transparent;
      background-image: linear-gradient(to bottom, #ffffff 25%, #d2fff8 50%, #6bffec 70%, #00fde8 100%);
      /* 使用 -webkit-background-clip 属性将背景剪裁至文本形状 */
      -webkit-background-clip: text;
      /* 非Webkit内核浏览器需要使用标准前缀 */
      background-clip: text;
      /* 把当前元素设置为行内块，以便能够应用背景 */
      display: inline-block;
    }
  }
}
.data-box2 {
  width: 1492px;
  height: 200px;
  background: url('@/assets/images/map/rightMenu/rainMonitor/dataBox.png') no-repeat;
  background-size: 1492px 123px;
  background-position: bottom;
  margin-left: 28px;
  display: flex;
  padding: 0 70px;
  align-items: center;
  .data-item {
    display: flex;
    flex: 1;
    .item-right {
      margin-left: 20px;
      .text-box {
        display: flex;
        margin-bottom: 20px;
        .text1 {
          font-size: 32px;
          color: #ffffff;
        }
        .text2 {
          font-size: 32px;
          color: #a7ccdf;
          margin-left: 5px;
        }
      }
      .text3,
      .text4,
      .text5,
      .text6 {
        font-size: 38px;
        font-family: BEBAS-1;
        /* 设置字体透明 */
        color: transparent;
        /* 使用 -webkit-background-clip 属性将背景剪裁至文本形状 */
        -webkit-background-clip: text;
        /* 非Webkit内核浏览器需要使用标准前缀 */
        background-clip: text;
        /* 把当前元素设置为行内块，以便能够应用背景 */
        display: inline-block;
      }
      .text3 {
        background-image: linear-gradient(to bottom, #ffffff 25%, #e58400 100%);
      }
      .text4 {
        background-image: linear-gradient(to bottom, #ffffff 25%, #6fe695 100%);
      }
      .text5 {
        background-image: linear-gradient(to bottom, #ffffff 25%, #00fde8 100%);
      }
      .text6 {
        background-image: linear-gradient(to bottom, #ffffff 25%, #2b72d6 100%);
      }
    }
    .icon1,
    .icon2,
    .icon3,
    .icon4 {
      width: 152px;
      height: 138px;
    }
    .icon1 {
      width: 141px;
      height: 126px;
      background: url('@/assets/images/map/rightMenu/rainMonitor/icon1.png') no-repeat;
    }
    .icon2 {
      background: url('@/assets/images/map/rightMenu/rainMonitor/icon2.png') no-repeat;
    }
    .icon3 {
      background: url('@/assets/images/map/rightMenu/rainMonitor/icon3.png') no-repeat;
    }
    .icon4 {
      background: url('@/assets/images/map/rightMenu/rainMonitor/icon4.png') no-repeat;
    }
  }
}
.title {
  font-size: 60px;
  position: absolute;
  top: 30px;
  left: 160px;
}
</style>
