<template>
  <BasicModal
    :maskClosable="false"
    :width="1200"
    @register="registerModal"
    v-bind="$attrs"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <div class="modal-box">
      <div>
        <BasicForm @register="registerForm">
          <template #customSlot="{ model, field }">
            <div class="btn-query">
              <a-button @click="queryData" type="primary">查询</a-button>
            </div>
          </template>
        </BasicForm>
      </div>
      <div class="charts-box-modal" id="charts-box-honghao-form"></div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref, reactive, onMounted } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
const { createMessage } = useMessage();
import { useMessage } from '/@/hooks/web/useMessage';
import * as echarts from 'echarts';
import moment from 'moment';
import {
  getNewStation,
  getUpdateTree,
  getPisSelect,
  getDetailsShow,
  getFcodeAdd,
  getFcodeUpDate,
  getFcodeAddCal
} from '/@/api/swHome/index';
import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();
export default defineComponent({
  name: 'AccountModal',
  components: { BasicModal, BasicForm },
  setup(_, { emit }) {
    const disabledStartDate = (startValue: Moment) => {
      if (!startValue || !getFieldsValue().etime) {
        return false;
      }
      return startValue.valueOf() > moment(getFieldsValue().etime).valueOf();
    };

    const disabledEndDate = (endValue: Moment) => {
      if (!endValue || !getFieldsValue().stime) {
        return false;
      }
      return moment(getFieldsValue().stime).valueOf() >= endValue.valueOf();
    };
    let accountFormSchema = ref([
      {
        field: 'pid',
        label: '预报断面',
        component: 'ApiSelect',
        colProps: { span: 24 },
        required: true,
        componentProps: {
          api: getPisSelect,
          labelField: 'name',
          valueField: 'pid',
          resultField: 'data',
          // onChange: setChartsData,
        },
      },
      {
        field: 'stime',
        label: '开始时间',
        component: 'DatePicker',
        colProps: { span: 24 },
        required: true,
        componentProps: {
          showTime: {
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            format: 'YYYY-MM-DD HH',
          },
          onChange: setChartsDataTime,
          disabledDate: disabledStartDate,
        },
      },
      {
        field: 'etime',
        label: '结束时间',
        component: 'DatePicker',
        colProps: { span: 24 },
        required: true,
        componentProps: {
          showTime: {
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            format: 'YYYY-MM-DD HH',
          },
          onChange: setChartsDataTime1,
          disabledDate: disabledEndDate,
        },
      },
      // 按钮
      {
        field: 'btn',
        label: ' ',
        component: 'Input',
        slot: 'customSlot',
        componentProps: {},
      },

      {
        field: 'fcode',
        label: '洪号',
        component: 'Input',
        colProps: { span: 24 },
        required: true,
        componentProps: {
          maxLength: 30,
        },
      },
      {
        field: 'peak',
        label: '洪峰流量',
        component: 'Input',
        colProps: { span: 24 },
        required: true,
        componentProps: {
          maxLength: 30,
        },
      },
      {
        field: 'volume',
        label: '洪量',
        component: 'Input',
        colProps: { span: 24 },
        required: true,
        componentProps: {
          maxLength: 30,
        },
      },
      // {
      //   field: 'peak',
      //   label: '洪峰',
      //   component: 'Input',
      //   colProps: { span: 24 },
      //   required: true,
      //   componentProps: {
      //     maxLength: 30,
      //   },
      // },
      {
        field: 'peaktime',
        label: '峰现时间',
        component: 'DatePicker',
        colProps: { span: 24 },
        required: true,
        componentProps: {
          showTime: {
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            format: 'YYYY-MM-DD HH:mm:ss',
          },
        },
      },
    ]);
    let chartsData = {};
    const isUpdate = ref(true);
    let chart = null;
    function setCharts() {
      chart = echarts.init(document.getElementById('charts-box-honghao-form'));
      let option = {
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['实测流量'],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: chartsData.t.map(function (str) {
            return str.replace(' ', '\n');
          }),
        },
        yAxis: {
          type: 'value',
          scale: true,
        },
        series: [
          {
            name: '实测流量',
            type: 'line',
            stack: 'Total',
            data: chartsData.q,
            smooth: true
          },
        ],
      };
      option && chart.setOption(option);
    }
    function queryData() {
      if (getFieldsValue().stime && getFieldsValue().etime && getFieldsValue().pid) {
        setChartsData();
      }else{
        createMessage.warning('请完善参数');
      }
    }
    // 时间选择
    function setChartsDataTime(e, dateString) {
      let str = dateString.split(':');
      setFieldsValue({
        stime: str[0] + ':00:00',
      });
      setTimeout(() => {
        if (getFieldsValue().stime && getFieldsValue().etime) {
          // setChartsData();
        }
      }, 0);
    }
    // 时间选择
    function setChartsDataTime1(e, dateString) {
      let str = dateString.split(':');
      setFieldsValue({
        etime: str[0] + ':00:00',
      });
      setTimeout(() => {
        if (getFieldsValue().stime && getFieldsValue().etime) {
          // setChartsData();
        }
      }, 0);
    }
    // 查询图表
    function setChartsData() {
      setTimeout(() => {
        if (getFieldsValue().etime && getFieldsValue().pid && getFieldsValue().stime) {
          let obj = {
            etime: getFieldsValue().etime,
            pid: getFieldsValue().pid + '',
            stime: getFieldsValue().stime,
          };
          // getDetailsShow(obj).then((res) => {
            
          // });
          obj.type = isUpdate.value?'update':'add'
          getFcodeAddCal(obj).then(res => {
            if (res.code == 200) {
              chartsData = {q:res.data.q, t:res.data.t};
              accountFormSchema.value[5].show = true
              accountFormSchema.value[6].show = true
              accountFormSchema.value[7].show = true
              setFieldsValue({
                fcode: fcode.value?fcode.value:res.data.fcode,
                peak: res.data.peak,
                peaktime: res.data.peaktime,
                volume: res.data.volume,
              });
              setTimeout(() => {
                setCharts();
              }, 0);
            } else {
              if (chart) {
                chart.dispose();
              }
              createMessage.warning(res.msg);
            }
          })
        }
      }, 0);
    }
    let fcode = ref('')
    let peaktime = ref('')
    let volume = ref('')
    let peak = ref('')
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      console.log('data', data);

      isUpdate.value = !!data?.isUpdate;
      accountFormSchema.value[4].show = !isUpdate.value
      accountFormSchema.value[5].show = !isUpdate.value
      accountFormSchema.value[6].show = !isUpdate.value
      accountFormSchema.value[7].show = !isUpdate.value
      fcode.value = ''
      if (chart) {
        chart.dispose();
      }
      if (data?.details) {
        setFieldsValue({
          etime: data?.formData.etime, //通信协议
          fcode: data?.formData.fcode, //数据协议
          peak: data?.formData.peak, //IP
          peaktime: data?.formData.peaktime, //端口
          stime: data?.formData.stime,
          volume: data?.formData.volume,
          pid: data?.formData.pid,
        });
        accountFormSchema.value.forEach((element) => {
          element.componentProps.disabled = true;
        });
        updateSchema(accountFormSchema.value);
        return;
      }
      // 编辑
      if (unref(isUpdate)) {
        fcode.value = data?.formData.fcode
        peaktime.value = data?.formData.peaktime
        volume.value = data?.formData.volume
        peak.value = data?.formData.peak
        setFieldsValue({
          etime: data?.formData.etime, //通信协议
          fcode: data?.formData.fcode, //数据协议
          peak: data?.formData.peak, //IP
          peaktime: data?.formData.peaktime, //端口
          stime: data?.formData.stime,
          volume: data?.formData.volume,
          pid: data?.formData.pid,
        });
        // setChartsData();
        
      } else {
        if (chart) {
          chart.dispose();
        }
        await resetFields();
      }

      accountFormSchema.value.forEach((element) => {
        element.componentProps.disabled = false;
      });
      updateSchema(accountFormSchema.value);
    });
    const [registerForm, { setFieldsValue, updateSchema, resetFields, validate, getFieldsValue }] =
      useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 18,
        },
      });
    const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    async function handleSubmit() {
      setModalProps({ confirmLoading: true });
      try {
        const values = await validate(['name', 'tx_pro', 'data_pro', 'ip', 'port']);

        let formData = getFieldsValue();
        console.log(formData);
        // 新增
        if (!unref(isUpdate)) {
          let resData = await getFcodeAdd(formData);
          if (resData.code != 200) {
            createMessage.warning(resData.msg);
            return false;
          }
          console.log(resData);
        } else {
          // const userInfo = await userStore;
          // formData.attr.user = userInfo.userInfo.username;
          let formDataArr = [formData];
          //编辑
          let resData = await getFcodeUpDate(formDataArr);
          if (resData.code != 200) {
            createMessage.warning(resData.msg);
            return false;
          }
          console.log(resData);
        }
        closeModal();
        emit('success');
        createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
      } finally {
        setTimeout(() => {
          setModalProps({ confirmLoading: false });
        }, 300);
      }
    }
    return {
      registerModal,
      getTitle,
      handleSubmit,
      registerForm,
      disabledStartDate,
      disabledEndDate,
      queryData
    };
  },
});
</script>
<style lang="less" scoped>
.modal-box {
  display: flex;
  & > div:nth-child(1) {
    width: 40%;
  }
  & > div:nth-child(2) {
    width: 60%;
  }
}
::v-deep(.ant-calendar-picker) {
  width: 100% !important;
}
.btn-query {
  text-align: right;
}
</style>
