<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="connectAnalysis">
    <div class="filter-area">
      <Row style="width: 100%">
        <Col :span="7">
          <div class="filter-section param-section">
            <span class="filter-label">煤矿名称：</span>
            <div class="param-selector">
              <MineCascader
                v-model:value="innerValue"
                style="width: 330px"
                :sync-to-store="false"
                :init-from-store="false"
                :change-on-select="false"
                @change="changeCascader"
              ></MineCascader>
            </div>
          </div>
        </Col>
        <Col :span="7">
          <!-- 时间选择 -->
          <div class="filter-section param-section">
            <span class="filter-label">老空区永久密闭：</span>
            <Select ref="select" v-model:value="goafId" style="width: 300px" placeholder="请选择老空区" @change="generateChart">
              <SelectOption v-for="(item, index) in goafOptions" :key="index" :value="item.value">
                {{ item.label }}
              </SelectOption>
            </Select>
          </div>
        </Col>
        <Col :span="6">
          <div class="filter-section param-section">
            <span class="filter-label">时间选择：</span>
            <RangePicker
              v-model:value="dateRange"
              format="YYYY-MM-DD HH:mm:ss"
              :placeholder="['开始时间', '结束时间']"
              style="width: 300px"
              :show-time="{ format: 'HH:mm:ss' }"
              @change="changeTime"
            />
          </div>
        </Col>
        <Col :span="4">
          <div class="filter-section">
            <Button type="primary" @click="generateChart" :loading="loading">
              <template #icon>
                <SvgIcon style="margin-right: 10px" name="shencen" />
              </template>
              生成
            </Button>
          </div>
        </Col>
      </Row>
    </div>
    <!-- 动态图表区域-->
    <div class="echart-box">
      <div class="check-title">
        <CheckboxNav :filters="checkList" :options="checkboxOptions" @check-box-change="checkBoxChange"></CheckboxNav>
      </div>
      <div class="check-line">
        <echartDivider></echartDivider>
      </div>
      <div class="echart-content">
        <echartContent :echartData="echartData" :x-axis="xAxis" :y-axis="yAxis"></echartContent>
      </div>
      <div class="check-line">
        <echartDivider></echartDivider>
      </div>
      <div class="check-title">
        <echartLegend :legends="legendsOptions"></echartLegend>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import dayjs from 'dayjs';
  import { Select, SelectOption, Row, Col, DatePicker, Button, message } from 'ant-design-vue';
  import MineCascader from '@/components/Form/src/jeecg/components/MineCascader/MineCascader.vue';
  import CheckboxNav from './components/checkbox-nav.vue';
  import echartLegend from './components/echart-legend.vue';
  import echartContent from './components/echart-content.vue';
  import echartDivider from './components/echart-divider.vue';
  import { getGoafHistory } from './connectAnalysis.api';
  import { SvgIcon } from '/@/components/Icon';
  import { useInitForm } from './hooks/form';
  import { useMineDepartmentStore } from '/@/store/modules/mine.js';

  // 这个页面被其他的页面需要，故添加部分props以作复用
  const props = withDefaults(
    defineProps<{
      /** 指定请求历史数据时携带的参数，指定后不会显示除了时间范围的表单 */
      requestParams?: any;
      /** 这是参数多选选项 */
      checkboxOptions: {
        label: string;
        value: string;
        color: string;
        areaColor: string[];
      }[];
      /** 这是图例显示的选项 */
      legendsOptions: {
        label: string;
      }[];
      /** 历史数据取多少天之前到现在的数据 */
      dateForm?: number;
      xAxis?: number[];
      yAxis?: {
        name: string;
        gridIndex: number;
        min?: number;
        position: string;
        max?: number;
      }[];
    }>(),
    {
      dateForm: 30,
    }
  );

  const mineStore = useMineDepartmentStore();
  const { goafOptions, goafId, innerValue, loading, filters, initGoafOptions } = useInitForm();

  // 组件注册
  const RangePicker: any = DatePicker.RangePicker;
  // const { currentRoute } = useRouter();
  // 筛选相关响应式数据
  const dateRange = ref([dayjs().add(-props.dateForm, 'day'), dayjs()]); // 默认时间范围（近1天）
  // const mineStore = useMineDepartmentStore();
  const checkList = ref<any[]>(filters.length ? filters : props.checkboxOptions.map((e) => e.value)); //当前选中要进行显示的选项
  const echartData = ref({
    xData: [] as any,
    yData: [] as any,
    flag: true,
  });

  //煤矿选项切换
  function changeCascader(val) {
    const dept = mineStore.findDepartById(innerValue.value);
    if (!dept || !dept?.isLeaf) return;

    innerValue.value = val;
    initGoafOptions(val).then(() => {
      generateChart();
    });
  }
  //时间选择选项切换
  function changeTime(val) {
    dateRange.value[0] = val[0];
    dateRange.value[1] = val[1];
    generateChart();
  }
  //图表选项标签切换
  function checkBoxChange(val) {
    checkList.value = val.checkedList;
    generateChart();
  }

  // 生成折线图核心逻辑
  async function generateChart() {
    if (!goafId.value) {
      echartData.value = { xData: [], yData: [], flag: true };
      return message.info('请先选择煤矿及老空区');
    }

    loading.value = true;
    echartData.value.yData = [];
    echartData.value.flag = false;

    const startTime = dateRange.value[0].format('YYYY-MM-DD HH:mm:ss');
    const endTime = dateRange.value[1].format('YYYY-MM-DD HH:mm:ss');
    const res = await getGoafHistory({
      pageNo: 1,
      pageSize: 1000,
      startTime: startTime,
      endTime: endTime,
      goafId: goafId.value,
      deptId: innerValue.value,
      sort: 'asc',
      ...(props.requestParams || {}),
    });

    loading.value = false;

    if (res) {
      const data = res.records || [];
      if (data.length) {
        echartData.value.xData = data.map((e) => e.createTime);
        if (checkList.value.length) {
          checkList.value.forEach((el) => {
            echartData.value.yData.push({
              label: el,
              value: data,
            });
          });
        }
      } else {
        // API 返回空数据时清空图表
        echartData.value = { xData: [], yData: [], flag: true };
      }
    }
  }

  //获取采空区列表
  // async function getGoafListData() {
  //   let res = await getGoafList({ mineCode: innerValue.value });
  //   console.log(res, '90');
  //   goafOption.value =
  //     res.map((el) => {
  //       return {
  //         label: el.devicePos,
  //         value: el.id,
  //       };
  //     }) || [];
  //   goafId.value = goafOption.value.length ? (goafId.value ? goafId.value : goafOption.value[0]['value']) : '';
  // }
</script>

<style lang="less" scoped>
  .connectAnalysis {
    width: 100%;
    // height: 100%;
    // margin: 10px 0px 0px 10px;
    // padding: 10px;
    box-sizing: border-box;
    // border: 1px solid @border-color-base;
    // border-radius: 4px;
    // background: @card-bg-color;
    //background-color: @card-bg-color;
    align-items: center;
    // box-shadow: 0px 0px 8px 1px rgba(202, 211, 225, 1);
  }

  .filter-area {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    padding: 20px;
    border: 1px solid @border-color-base;
    border-radius: 4px;
    // background: @card-bg-color;
    background-color: @card-bg-color;
    align-items: center;
    // box-shadow: 0px 0px 8px 1px rgba(202, 211, 225, 1);
  }

  .filter-section {
    display: flex;
    align-items: center;
  }

  .filter-label {
    color: #666;
    min-width: 70px;
    flex-shrink: 0;
    font-weight: 500;
  }

  .param-section {
    flex: 1;
    // min-width: 300px;
  }

  .param-selector {
    display: flex;
    align-items: center;
    gap: 8px;
    position: relative;
  }

  .echart-box {
    width: 100%;
    height: calc(100% - 95px);
  }

  .check-title {
    height: 40px;
    line-height: 40px;
    background-color: @table-thead-bg-color;
    border-radius: 4px;
    padding: 0px 20px;
    box-sizing: border-box;
    margin: 15px 0px;
  }

  .check-line {
    width: 100%;
  }

  .echart-content {
    width: 100%;
    height: calc(100% - 112px);
  }

  :deep(.ant-btn-primary) {
    display: flex !important;
    align-items: center !important;
  }
</style>
