<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="gas-verify">
    <CustomHeader> 瓦斯抽采达标能力核定 </CustomHeader>
    <div class="flex mt-90px">
      <div class="nav-l"> 瓦斯抽采达标生产能力：{{ data.gasExtractionSystemCapacityResultLarge }} t/a </div>
      <div class="nav">
        <Tabs v-model:active-key="actived" :tabBarStyle="{ color: 'red' }">
          <TabPane key="product" tab="矿井瓦斯抽采达标生产能力核定" />
          <TabPane key="extract" tab="矿井瓦斯抽采能力核定" />
        </Tabs>
      </div>
      <div class="nav-r"> 瓦斯抽采能力：{{ data.gasExtractionSystemCapacityResultSmall }} m<sup>3</sup>/min </div>
    </div>
    <div class="flex">
      <div :style="{ flex: 1 }">
        矿井瓦斯抽采系统能力统计图
        <Bar :chart-data="productChartData" x-axis-prop-type="x" series-prop-type="y" height="300px" />
        矿井瓦斯抽采能力统计图
        <Bar :chart-data="extractChartData" x-axis-prop-type="x" series-prop-type="y" height="300px" />
      </div>
      <div class="gas-verify__content">
        <div v-show="true">
          <div class="flex flex-justify-between flex-items-center">
            <FormTitle class="flex-grow-1" icon="pump" title="矿井基本信息" />
            <Button class="mr-10px" @click="addPubFormSchema">添加回风井</Button>
            <Button class="mr-10px" @click="calculateBasicForm">计算</Button>
            <Button type="primary" @click="submitBasicForm">提交</Button>
          </div>
          <BasicForm :schemas="publicFormSchema" @register="regBasicForm" />
        </div>
        <div v-show="actived === 'product'">
          <div class="flex flex-justify-between flex-items-center">
            <FormTitle class="flex-grow-1" icon="pump" :title="`根据矿井实际抽采瓦斯量核定：${data.gasExtractionVolumeVerificationTotal}`" />
            <Button type="primary" @click="submitGasvalForm">提交</Button>
          </div>
          <BasicForm :schemas="valFormSchema" @register="regGasvalForm" />
        </div>
        <div v-show="actived === 'product'">
          <div class="flex flex-justify-between flex-items-center">
            <FormTitle class="flex-grow-1" icon="pump" :title="`根据矿井瓦斯抽采率核定：${data.gasExtractionRateVerificationTotal}`" />
            <Button class="mr-10px" @click="calculateGasrateForm">计算</Button>
            <Button type="primary" @click="submitGasrateForm">提交</Button>
          </div>
          <BasicForm :schemas="rateFormSchema" @register="regGasrateForm" />
        </div>
        <div v-show="false">
          <div class="flex flex-justify-between flex-items-center">
            <FormTitle class="flex-grow-1" icon="pump" title="核定区域信息" />
            <Button type="primary" @click="submitCheckForm">提交</Button>
          </div>
          <BasicForm :schemas="checkFormSchema" @register="regCheckForm" />
        </div>

        <div class="flex flex-justify-between flex-items-center">
          <FormTitle
            class="flex-grow-1"
            :title="
              {
                extract: `按瓦斯抽采泵站装机能力核定：${data.gasExtractionPumpStationCapacitySmall}`,
                product: `按矿井瓦斯抽采泵站装机能力核定：${data.gasExtractionMainPipelineCapacityLarge}`,
              }[actived]
            "
          />
          <Button type="primary" @click="editPumpHandler()">添加</Button>
        </div>
        <BasicTable class="mb-20px" :columns="pumpTableColumns" :data-source="pumpTableData" @register="regPumpTable">
          <template #action="{ record }">
            <a class="mr-5px" @click.prevent="editPumpHandler(record)">编辑</a>
            <Popconfirm @confirm="deletePumpHandler(record)"><a>删除</a></Popconfirm>
          </template>
        </BasicTable>

        <div class="flex flex-justify-between flex-items-center">
          <FormTitle
            class="flex-grow-1"
            :title="
              {
                extract: `按矿井瓦斯主管道系统能力核定：${data.gasExtractionMainPipelineCapacitySmall}`,
                product: `按矿井瓦斯抽采主管道系统能力核定：${data.gasExtractionMainPipelineCapacityLarge}`,
              }[actived]
            "
          />
          <Button type="primary" @click="editPipeHandler()">添加</Button>
        </div>
        <BasicTable :columns="pipeTableColumns" :data-source="pipeTableData" @register="regPipeTable">
          <template #action="{ record }">
            <a class="mr-5px" @click.prevent="editPipeHandler(record)">编辑</a>
            <Popconfirm @confirm="deletePipeHandler(record)"><a>删除</a></Popconfirm>
          </template>
        </BasicTable>
        <!-- <BasicTable :columns="workfaceTableColumns" :data-source="[{ ccbz: `1111` }, { ccbz: `2222` }]" @register="regTable">
          <template #action="{ record }">
            <a class="mr-5px" @click.prevent="openModal()">编辑</a>
            <a>删除</a>
          </template>
        </BasicTable> -->

        <BasicModal @register="regPipeModal" title="能力核定表单" @ok="submitPipeForm">
          <BasicForm :schemas="pipeFormSchema" @register="regPipeForm" />
        </BasicModal>
        <BasicModal @register="regPumpModal" title="能力核定表单" @ok="submitPumpForm">
          <BasicForm :schemas="pumpFormSchema" @register="regPumpForm" />
        </BasicModal>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import CustomHeader from '/@/components/vent/customHeader.vue';
  import { computed, nextTick, ref } from 'vue';
  import { message, TabPane, Tabs, Button, Popconfirm } from 'ant-design-vue';
  import { onMounted } from 'vue';
  import FormTitle from '@/views/vent/gas/components/form/formTitle.vue';
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';
  import Bar from '/@/components/chart/Bar.vue';
  import {
    getGasMainAllInfo,
    getGasMainpipesystemAllInfo,
    getGasPumpstationAllInfo,
    deleteGasMainpipesystem,
    deleteGasPumpstation,
    updateGasMain,
    updateGasMainpipesystem,
    updateGasPumpstation,
  } from './gasPumpSetting.api';
  import {
    publicFormSchema,
    valFormSchema,
    rateFormSchema,
    pumpTableColumns,
    pipeTableColumns,
    checkFormSchema,
    pipeFormSchema,
    pumpFormSchema,
    // workfaceTableColumns,
  } from './gasPumpSetting.data';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { get, inRange, isNil } from 'lodash-es';

  const actived = ref<'extract' | 'product'>('product');

  /** 计算参数相关的表单通用配置 */
  const formProps = {
    showActionButtonGroup: false,
    labelCol: { span: 10 },
    baseColProps: {
      flex: '20%',
    },
  };

  function submitHandler() {
    const data1 = ctxBasicForm.getFieldsValue();
    const data2 = ctxGasvalForm.getFieldsValue();
    const data3 = ctxGasrateForm.getFieldsValue();
    const airVolumeStr = get(data1, 'returnAirVolume', []).join(',');
    updateGasMain({
      ...data3,
      ...data2,
      ...data1,
      returnAirVolume: airVolumeStr,
    })
      .then(() => {
        message.success('提交成功');
        refresh();
      })
      .catch(() => {
        message.error('操作失败');
      });
  }

  const [regBasicForm, ctxBasicForm] = useForm(formProps);
  function submitBasicForm() {
    ctxBasicForm.validate().then(() => {
      submitHandler();
    });
  }
  /** 计算部分可以自动计算的参数 */
  function calculateBasicForm() {
    const { returnAirVolume } = data.value;
    const { mineGasExtractionRate } = ctxBasicForm.getFieldsValue();
    if (returnAirVolume && Array.isArray(returnAirVolume)) {
      const airVolumeArr = returnAirVolume.map((e) => parseFloat(e));
      ctxBasicForm.setFieldsValue({
        mineMaxTotalReturnAirVolume: airVolumeArr.reduce((t, n) => t + n, 0),
      });
    }
    // 根据抽采率生成总回瓦斯浓度
    if (mineGasExtractionRate) {
      const n = parseInt(mineGasExtractionRate);
      const config: [[number, number], number][] = [
        [[0, 35], 0.35],
        [[34.99, 40], 0.375],
        [[39.99, 45], 0.425],
        [[44.99, 50], 0.475],
        [[49.99, 55], 0.525],
        [[54.99, 60], 0.575],
        [[59.99, 100], 0.7],
      ];
      config.forEach((e) => {
        if (inRange(n, e[0][0], e[0][1])) {
          ctxBasicForm.setFieldsValue({
            mineTotalReturnAirGasConcentration: e[1],
          });
        }
      });
    }
  }

  /** 根据矿井实际抽采瓦斯量核定的表单数据 */
  const [regGasvalForm, ctxGasvalForm] = useForm(formProps);
  function submitGasvalForm() {
    ctxGasvalForm.validate().then(() => {
      submitHandler();
    });
  }

  /** 根据矿井瓦斯抽采率核定的表单数据 */
  const [regGasrateForm, ctxGasrateForm] = useForm(formProps);
  function submitGasrateForm() {
    ctxGasrateForm.validate().then(() => {
      submitHandler();
    });
  }
  /** 计算部分可以自动计算的参数 */
  function calculateGasrateForm() {
    const { mineGasExtractionRate } = ctxGasrateForm.getFieldsValue();
    // 根据抽采率生成最大绝对涌出量
    if (mineGasExtractionRate) {
      const n = parseInt(mineGasExtractionRate);
      const config: [[number, number], number][] = [
        [[0, 35], 20],
        [[34.99, 40], 30],
        [[39.99, 45], 60],
        [[44.99, 50], 120],
        [[49.99, 55], 230],
        [[54.99, 60], 400],
        [[59.99, 100], 500],
      ];
      config.forEach((e) => {
        if (inRange(n, e[0][0], e[0][1])) {
          ctxGasrateForm.setFieldsValue({
            maxAllowableAbsoluteGasEmission: e[1],
          });
        }
      });
    }
  }

  /** 核定区域信息的表单数据 */
  // const checkFormModel = ref<any>({});
  const [regCheckForm, ctxCheckForm] = useForm(formProps);
  function submitCheckForm() {
    ctxCheckForm.validate().then(() => {
      submitHandler();
    });
  }

  /** 矿井基本信息的表单配置，需要动态添加回风井。根据表单数据设置矿井基本信息的表单配置 */
  function resetPublicFormSchema() {
    const airVolumeArr = data.value.returnAirVolume;
    const extra: FormSchema[] = airVolumeArr.map((num, inx) => {
      return {
        label: `回风井${inx + 1}`,
        field: `__${inx + 1}`,
        defaultValue: num,
        component: 'Input',
        componentProps: {
          onChange: ({ target }) => {
            airVolumeArr[inx] = target.value;
          },
        },
      };
    });
    ctxBasicForm.resetSchema([...publicFormSchema, ...extra]);
  }
  /** 添加一项公用参数表单项 */
  function addPubFormSchema() {
    if (!data.value.returnAirVolume) return;
    data.value.returnAirVolume.push('0');
    resetPublicFormSchema();
  }

  /** 生产能力核定/抽采能力核定的数据，也是组件的数据依赖其一 */
  const data = ref<Record<string, any>>({});

  /** 按矿井瓦斯抽采主管道系统能力核定的表格 */
  const pipeTableData = ref<any[]>([]);

  const [regPipeModal, ctxPipeModal] = useModal();
  const [regPipeTable] = useTable({
    pagination: false,
  });
  const [regPipeForm, ctxPipeForm] = useForm({
    showActionButtonGroup: false,
    labelCol: { span: 10 },
  });
  function submitPipeForm() {
    ctxPipeForm.validate().then((data) => {
      updateGasMainpipesystem(data)
        .then(() => {
          ctxPipeModal.closeModal();
          refresh();
        })
        .catch(() => {
          message.error('操作失败');
        });
    });
  }
  function editPipeHandler(record?: Record<string, any>) {
    ctxPipeModal.openModal();
    nextTick(() => {
      if (record) {
        ctxPipeForm.setFieldsValue(record);
      } else {
        ctxPipeForm.resetFields();
      }
    });
  }
  function deletePipeHandler({ id }) {
    deleteGasMainpipesystem({ id })
      .then(() => {
        refresh();
      })
      .catch(() => {
        message.error('操作失败');
      });
  }

  /** 按矿井瓦斯抽采泵站装机能力核定的表格 */
  const pumpTableData = ref<any[]>([]);

  const [regPumpModal, ctxPumpModal] = useModal();
  const [regPumpTable] = useTable({
    pagination: false,
  });
  const [regPumpForm, ctxPumpForm] = useForm({
    showActionButtonGroup: false,
    labelCol: { span: 10 },
  });
  function submitPumpForm() {
    ctxPumpForm.validate().then((data) => {
      updateGasPumpstation(data)
        .then(() => {
          ctxPumpModal.closeModal();
          refresh();
        })
        .catch(() => {
          message.error('操作失败');
        });
    });
  }
  function editPumpHandler(record?: Record<string, any>) {
    ctxPumpModal.openModal();
    nextTick(() => {
      if (record) {
        ctxPumpForm.setFieldsValue(record);
      } else {
        ctxPumpForm.resetFields();
      }
    });
  }
  function deletePumpHandler({ id }) {
    deleteGasPumpstation({ id })
      .then(() => {
        refresh();
      })
      .catch(() => {
        message.error('操作失败');
      });
  }

  function refresh() {
    Promise.all([getGasMainAllInfo({}), getGasMainpipesystemAllInfo({}), getGasPumpstationAllInfo({})]).then((res) => {
      const [r1, r2, r3] = res.map((e) => e.obj);
      r1[0].returnAirVolume = r1[0].returnAirVolume.split(',');
      ctxBasicForm.setFieldsValue(r1[0]);
      ctxGasvalForm.setFieldsValue(r1[0]);
      ctxGasrateForm.setFieldsValue(r1[0]);
      pipeTableData.value = r2;
      pumpTableData.value = r3;
      data.value = r1[0];
      resetPublicFormSchema();
    });
  }

  // function getNum(data, path, defaultValue) {
  //   const r = get(data, path);

  //   return isNil(r) ? defaultValue : parseFloat(r);
  // }

  const productChartData = computed(() => {
    return [
      {
        x: '抽采系统能力',
        y: data.value.gasExtractionSystemCapacityResultSmall || 0,
      },
      {
        x: '实际抽采量',
        y: data.value.gasExtractionVolumeVerificationTotal || 0,
      },
      {
        x: '瓦斯抽采率',
        y: data.value.gasExtractionRateVerificationTotal || 0,
      },
      // {
      //   x: '防突抽采',
      //   y: data.value.ftcc || 0,
      // },
    ];
  });
  const extractChartData = computed(() => {
    const keyMap = {
      extract: ['gasExtractionPumpStationCapacitySmall', 'gasExtractionMainPipelineCapacitySmall'],
      product: ['gasExtractionMainPipelineCapacityLarge', 'gasExtractionMainPipelineCapacityLarge'],
    };
    return [
      {
        x: '瓦斯抽采泵装机能力',
        y: get(data.value, keyMap[actived.value][0], 0),
      },
      {
        x: '瓦斯抽采主管道系统能力',
        y: get(data.value, keyMap[actived.value][1], 0),
      },
    ];
  });

  onMounted(() => {
    refresh();
  });
</script>

<style lang="less" scoped>
  @import '/@/design/theme.less';

  .gas-verify {
    --image-verify-nav-bg-l: url('/@/assets/images/vent/gas/verify-nav-bg-l.png');
    --image-verify-nav-bg-r: url('/@/assets/images/vent/gas/verify-nav-bg-r.png');
    --image-verify-nav-bg: url('/@/assets/images/vent/gas/verify-nav-bg.png');

    color: var(--vent-font-color);
    padding: 0 20px;

    .nav-l {
      flex: 1;
      height: 83px;
      padding-top: 31px;
      text-align: center;
      background-repeat: no-repeat;
      background-size: 100% 85px;
      background-position: center 12px;
      background-image: var(--image-verify-nav-bg-l);
    }
    .nav {
      flex: 3;
      height: 83px;
      padding: 20px 40px 0 40px;
      background-repeat: no-repeat;
      background-size: 100% 70px;
      background-position: center 0;
      background-image: var(--image-verify-nav-bg);
    }
    .nav-r {
      flex: 1;
      height: 83px;
      padding-top: 31px;
      text-align: center;
      background-repeat: no-repeat;
      background-size: 100% 85px;
      background-position: center 12px;
      background-image: var(--image-verify-nav-bg-r);
    }

    .gas-verify__content {
      flex: 4;
      height: 740px;
      overflow-y: auto;
    }
  }

  :deep(.zxm-tabs-ink-bar) {
    display: none;
  }
  :deep(.form-title) {
    background-size: 800px 100%;
  }
</style>
