<template>
  <BasicModal :maskClosable="false" :width="1400" @register="registerModal" v-bind="$attrs" title="新增断面"
    @ok="handleSubmit" :showOkBtn="false" :showCancelBtn="false">
    <div>
      <a-steps :current="dataCenter.current">
        <a-step v-for="(item, index) in dataCenter.steps" :key="index" :title="item.title" />
      </a-steps>
    </div>
    <div v-show="dataCenter.current == 0" class="form-box">
      <a-form :rules="rules1" :model="dataCenter.formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }"
        ref="formRef1">
        <a-form-item label="预报模型：" name="model_id">
          <a-select @change="modelChange" v-model:value="dataCenter.formState.model_id" placeholder="请选择所属流域">
            <a-select-option v-for="(item, index) in dataCenter.basinList4" :key="index" :value="item.model_id + ''">{{
              item.model_name }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </div>
    <div v-show="dataCenter.current == 1" class="form-box">
      <a-form :rules="rules1" :model="dataCenter.formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }"
        ref="formRef">
        <a-form-item label="断面名称：" name="pid">
          <a-select @change="duanmianChange" v-model:value="dataCenter.formState.pid" placeholder="请选择所属流域">
            <a-select-option v-for="(item, index) in dataCenter.basinList" :key="index" :value="item.pid">{{ item.pid_name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="方案名称：" name="scheme_name">
          <a-input v-model:value="dataCenter.formState.scheme_name" placeholder="请输入方案名称" />
        </a-form-item>
        <a-form-item label="控制积水面积：" name="area">
          <a-input v-model:value="dataCenter.formState.area" placeholder="请输入控制积水面积，Km2" />
        </a-form-item>
        <a-form-item label="站点实测流量：" name="stcd_q">
          <a-select v-model:value="dataCenter.formState.stcd_q" placeholder="请选择所属流域">
            <a-select-option v-for="(item, index) in dataCenter.basinList2" :key="index" :value="item.stcd_q + ''">{{
              item.stcd_q_name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="数值天气预报模式：" name="weather_type">
          <a-select v-model:value="dataCenter.formState.weather_type" placeholder="请选择所属流域">
            <a-select-option v-for="(item, index) in dataCenter.basinList3" :key="index" :value="item.weather_type">{{
              item.weather_name }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </div>
    <div v-show="dataCenter.current == 2">
      <div class="list1-btn">
        <a-button type="primary" @click="pushSchemeDetail">新增</a-button>
      </div>
      <div class="table1">
        <a-table bordered :data-source="dataCenter.formState.scheme_detail" :columns="dataCenter.formState.model_id==76?dataCenter.columns5:dataCenter.columns1"
          :pagination="false">
          <template #index="{ text, record, index }">
            <div>
              {{ index + 1 }}
            </div>
          </template>
          <!-- 回归参数 -->
          <template #coef="{ text, record }">
            <div>
              <a-input-number
                id="inputNumber"
                v-model:value="record['coef']"
                :min="0"
                :step="0.01"
              />
            </div>
          </template>
          <!-- 截距 -->
          <template #intercept="{ text, record }">
            <div>
              <a-input-number
                id="inputNumber"
                v-model:value="record['intercept']"
                :min="0"
                :step="0.01"
              />
            </div>
          </template>
          <template #stcd_p="{ text, record }">
            <div>
              <a-select v-model:value="record['stcd_p']" style="width: 120px">
                <a-select-option v-for="(item, index) in dataCenter.rainfall" :key="index" :value="item.stcd_q">{{
                  item.name }}</a-select-option>
              </a-select>
            </div>
          </template>
          <!-- 气象站meteorological -->
          <template #stcd_m="{ text, record }">
            <div>
              <a-select v-model:value="record['stcd_m']" style="width: 120px">
                <a-select-option v-for="(item, index) in dataCenter.meteorological" :key="index" :value="item.stcd_m">{{
                  item.name }}</a-select-option>
              </a-select>
            </div>
          </template>
          <!-- 河段数 -->
          <template #msk_num="{ text, record }">
            <div>
              <a-input-number id="inputNumber" v-model:value="record['msk_num']" :min="0" :step="1" :max="999" />
            </div>
          </template>
          <!-- 雨量站权重 -->
          <template #p_weight="{ text, record }">
            <div>
              <a-input-number id="inputNumber" v-model:value="record['p_weight']" :min="0" :step="0.01" :max="1" />
            </div>
          </template>
          <!-- 气象站权重 -->
          <template #m_weight="{ text, record }">
            <div>
              <a-input-number id="inputNumber" v-model:value="record['m_weight']" :min="0" :step="0.01" :max="1" />
            </div>
          </template>
          <!-- 上游来水站 upstream-->
          <template #stcd_inq="{ text, record }">
            <div>
              <a-select v-model:value="record['stcd_inq']" style="width: 120px">
                <a-select-option v-for="(item, index) in dataCenter.upstream" :key="index" :value="item.stcd_inq">{{
                  item.name }}</a-select-option>
              </a-select>
            </div>
          </template>
          <!-- 接入方案programme -->
          <template #stcd_inqup="{ text, record }">
            <div>
              <a-select v-model:value="record['stcd_inqup']" style="width: 120px">
                <a-select-option v-for="(item, index) in dataCenter.programme" :key="index" :value="item.stcd_inqup">{{
                  item.name }}</a-select-option>
              </a-select>
            </div>
          </template>
          <!-- 接入类型 -->
          <template #optimaze_type="{ text, record }">
            <div>
              <a-select v-model:value="record['optimaze_type']" style="width: 120px">
                <a-select-option v-for="(item, index) in dataCenter.accessType" :key="index"
                  :value="item.optimaze_type">{{ item.name }}</a-select-option>
              </a-select>
            </div>
          </template>
          <!-- 删除 -->
          <template #operation="{ text, record, index }">
            <a-popconfirm title="确定是否删除?" @confirm="onDelete(index)">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </a-table>
      </div>
    </div>
    <div v-show="dataCenter.current == 3">
      <div class="table1">
        <a-table bordered :data-source="dataCenter.formState.init_paramCopy" :columns="dataCenter.columns2"
          :pagination="false">
          <!-- 接入类型 -->
          <template #min_max_value="{ text, record }">
            <div> {{ record.min_value }}~{{ record.max_value }} </div>
          </template>
          <template #value="{ text, record }">
            <div>
              <a-input-number id="inputNumber" v-model:value="record['value']" :min="record.min_value"
                :max="record.max_value" />
            </div>
          </template>
        </a-table>
      </div>
    </div>
    <div v-show="dataCenter.current == 4">
      <div class="table1 table-flex">
        <div>
          <p class="table-title">产流中间变量配置</p>
          <a-table bordered :data-source="dataCenter.formState.yield_paramCopy" :columns="dataCenter.columns3"
            :pagination="false">
            <template #value="{ text, record }">
              <div>
                <a-input-number id="inputNumber" v-model:value="record['value']" />
              </div>
            </template>
          </a-table>
        </div>
        <div>
          <p class="table-title">汇流中间变量配置
            <a-button class="btn-righe" type="primary" @click="pushRouteParam">新增</a-button>
          </p>
          <a-table bordered :data-source="dataCenter.formState.route_paramCopy" :columns="dataCenter.columns4"
            :pagination="false">
            <template #value="{ text, record }">
              <div>
                <a-input-number id="inputNumber" v-model:value="record['value']" />
              </div>
            </template>
          </a-table>
        </div>
      </div>
    </div>
    <div class="steps-action">
      <a-button style="margin-left: 8px" v-if="dataCenter.current > 0" @click="prev">上一步</a-button>
      <a-button style="margin-left: 8px" v-if="dataCenter.current < dataCenter.steps.length - 1" type="primary"
        @click="next">下一步</a-button>
      <a-button v-if="dataCenter.current == dataCenter.steps.length - 1" style="margin-left: 8px" type="primary"
        @click="complete">
        完成
      </a-button>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import {
  getSponner,
  subSchemeAddPid,
  getSchemeSpinner,
  initParamAddShow,
  addForecastFlood,
  postForecastScheme,
  schemeAddSpinner,
  postForecastSchemeAdd
} from '/@/api/swHome/index';
import { useMessage } from '/@/hooks/web/useMessage';
import { object } from 'vue-types';
const { createMessage } = useMessage();
const emits = defineEmits(['success']); //这里暴露父组件自定义的方法
let dataCenter = reactive({
  formState: {
    pid: '',
    pid_name: '',
    scheme_name: '',
    area: '',
    stcd_q: '',
    weather_type: '',
    model_id: '',
    scheme_detail: [],
    init_paramCopy: [],
    route_paramCopy: [],
    route_param: [],
    yield_param: [],
    init_param: [],
    yield_paramCopy: [
      {
        name: 'S',
        value: '',
      },
      {
        name: 'WU',
        value: '',
      },
      {
        name: 'WL',
        value: '',
      },
      {
        name: 'WD',
        value: '',
      },
      {
        name: 'RS',
        value: '',
      },
      {
        name: 'RI',
        value: '',
      },
      {
        name: 'RG',
        value: '',
      },
      {
        name: 'QS',
        value: '',
      },
      {
        name: 'QI',
        value: '',
      },
      {
        name: 'QI',
        value: '',
      },
    ],
  },
  basinList: [],
  basinList2: [],
  basinList3: [],
  basinList4: [],
  rainfall: [],
  meteorological: [],
  upstream: [],
  programme: [],
  accessType: [],
  columns1: [
    {
      title: '序号',
      width: 70,
      slots: { customRender: 'index' },
    },
    {
      title: '雨量站',
      dataIndex: 'stcd_p',
      key: 'stcd_p',
      slots: { customRender: 'stcd_p' },
    },
    {
      title: '气象预报站',
      dataIndex: 'stcd_m',
      key: 'stcd_m',
      slots: { customRender: 'stcd_m' },
    },
    {
      title: '马斯京根河段数',
      dataIndex: 'msk_num',
      key: 'msk_num',
      slots: { customRender: 'msk_num' },
    },
    {
      title: '雨量站权重',
      dataIndex: 'p_weight',
      key: 'p_weight',
      slots: { customRender: 'p_weight' },
    },
    {
      title: '气象站权重',
      dataIndex: 'm_weight',
      key: 'm_weight',
      slots: { customRender: 'm_weight' },
    },
    {
      title: '上游来水站',
      dataIndex: 'stcd_inq',
      key: 'stcd_inq',
      slots: { customRender: 'stcd_inq' },
    },
    {
      title: '上游预报方案接入',
      dataIndex: 'stcd_inqup',
      key: 'stcd_inqup',
      slots: { customRender: 'stcd_inqup' },
    },
    {
      title: '接入类型',
      dataIndex: 'optimaze_type',
      key: 'optimaze_type',
      slots: { customRender: 'optimaze_type' },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      slots: { customRender: 'operation' },
    },
  ],
  columns2: [
    {
      title: '参数名',
      dataIndex: 'param_mark',
      key: 'param_mark',
    },
    {
      title: '描述',
      dataIndex: 'param_name',
      key: 'param_name',
    },
    {
      title: '取值范围',
      dataIndex: 'min_max_value',
      key: 'min_max_value',
      slots: { customRender: 'min_max_value' },
    },
    {
      title: '数值',
      dataIndex: 'value',
      key: 'value',
      slots: { customRender: 'value' },
    },
  ],
  columns3: [
    {
      title: '参数名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '参数值',
      dataIndex: 'value',
      key: 'value',
      slots: { customRender: 'value' },
    },
  ],
  columns4: [
    {
      title: '河段数',
      dataIndex: 'index',
      key: 'index',
    },
    {
      title: '参数值',
      dataIndex: 'value',
      key: 'value',
      slots: { customRender: 'value' },
    },
  ],
  columns5: [
    {
      title: '序号',
      width: 70,
      slots: { customRender: 'index' },
    },
    {
      title: '回归参数',
      dataIndex: 'coef',
      key: 'coef',
      slots: { customRender: 'coef' },
    },
    {
      title: '截距',
      dataIndex: 'intercept',
      key: 'intercept',
      slots: { customRender: 'intercept' },
    },
    {
      title: '上游来水站',
      dataIndex: 'stcd_inq',
      key: 'stcd_inq',
      slots: { customRender: 'stcd_inq' },
    },
    {
      title: '上游预报方案接入',
      dataIndex: 'stcd_inqup',
      key: 'stcd_inqup',
      slots: { customRender: 'stcd_inqup' },
    },
    {
      title: '接入类型',
      dataIndex: 'optimaze_type',
      key: 'optimaze_type',
      slots: { customRender: 'optimaze_type' },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      slots: { customRender: 'operation' },
    },
  ],
  current: 0,
  steps: [
    {
      title: '模型选择',
    },
    {
      title: '方案基础信息配置',
    },
    {
      title: '方案内容配置',
    },
    {
      title: '模型参数配置',
    },
    {
      title: '中间变量配置',
    },
  ],
});
const formRef = ref();
const formRef1 = ref();
const rules = {
  pid: [{ required: true, message: '请选择断面名称', trigger: 'blur' }],
  scheme_name: [{ required: true, message: '请输入断面名称', trigger: 'blur' }],
  area: [{ required: true, message: '请输入控制积水面积', trigger: 'blur' }],
  stcd_q: [{ required: true, message: '请选择站点实测流量', trigger: 'blur' }],
  weather_type: [{ required: true, message: '请选择数值天气预报模式', trigger: 'blur' }],
};
const rules1 = {
  model_id: [{ required: true, message: '请选择预报模型', trigger: 'blur' }],
};
onMounted(() => {
  getBasinList();
});
const getInitParamAddShow = () => {
  initParamAddShow({ model_id: dataCenter.formState.model_id }).then((res) => {
    dataCenter.formState.init_paramCopy = res.data;
  });
};
const pushSchemeDetail = () => {
  dataCenter.formState.scheme_detail.push({
    stcd_p: '',
    stcd_m: '',
    msk_num: '',
    p_weight: '',
    m_weight: '',
    stcd_inq: '',
    stcd_inqup: '',
    optimaze_type: '',
  });
};
const duanmianChange = (name, item) => {
  dataCenter.formState.pid_name = item.children[0].children;
};
const pushRouteParam = () => {
  dataCenter.formState.route_paramCopy.push({
    value: '',
    index: dataCenter.formState.route_paramCopy.length + 1,
  });
};
const modelChange = (value, e) => {
  // 判断模型id == 76的时候
  if (value == 76) {
    dataCenter.steps = [{
      title: '模型选择',
    },
    {
      title: '方案基础信息配置',
    },
    {
      title: '方案内容配置',
    }]
  } else {
    dataCenter.steps = [
      {
        title: '模型选择',
      },
      {
        title: '方案基础信息配置',
      },
      {
        title: '方案内容配置',
      },
      {
        title: '模型参数配置',
      },
      {
        title: '中间变量配置',
      },
    ]
  }
}
const next = () => {
  if (dataCenter.current == 0) {
    formRef1.value.validate().then(() => {
      console.log(dataCenter.formState);
      dataCenter.current++;
      return;
    });
  }
  if (dataCenter.current == 1) {
    formRef.value.validate().then(() => {
      console.log(dataCenter.formState);
      dataCenter.current++;
      return;
    });
  }
  if (dataCenter.current == 2) {
    // dataCenter.current++;
    // 判断是否填完
    if (dataCenter.formState.scheme_detail.length == 0) {
      createMessage.warning('请新增方案内容配置');
      return false;
    }
    // 判断是否填写数值
    let type = mapValue();
    if (!type) {
      createMessage.warning('请完善方案内容配置参数');
      return false;
    }
    dataCenter.current++;
    getInitParamAddShow();
    return;
  }
  if (dataCenter.current == 3) {
    let type2 = mapInitParam();
    if (!type2) {
      createMessage.warning('请完善模型参数配置参数');
      return false;
    }
    dataCenter.current++;
    // 查询中间变量配置默认值
    postForecastSchemeData()
    return;
  }
};
const postForecastSchemeData = () => {
  postForecastScheme({ model_id: dataCenter.formState.model_id }).then(res => {
    console.log(res.data.yield_param)
    res.data.yield_param.forEach((element, index) => {
      dataCenter.formState.yield_paramCopy[index].value = element
    });

  })
}
const complete = () => {
  let modelData = JSON.parse(JSON.stringify(dataCenter.formState))
  // 当模型等于76的时候
  if(dataCenter.formState.model_id == 76){
    if (dataCenter.formState.scheme_detail.length == 0) {
      createMessage.warning('请新增方案内容配置');
      return false;
    }
    delete modelData.init_param
    delete modelData.init_paramCopy
    delete modelData.route_param
    delete modelData.route_paramCopy
    delete modelData.yield_param
    delete modelData.yield_paramCopy
    modelData.scheme_detail.forEach((element,index) => {
      element.ordern = index+1
      delete element.m_weight
      delete element.msk_num
      delete element.p_weight
      delete element.stcd_m
      delete element.stcd_p
    });
    postForecastSchemeAdd(modelData).then(res => {
      if (res.code == 200) {
        createMessage.success(res.msg);
        closeModal();
      } else {
        createMessage.warning(res.msg);
      }
    })
    return
  }
  let type3 = mapYieldParam();
  if (!type3) {
    createMessage.warning('请完善产流中间变量配置参数');
    return false;
  }
  let type4 = mapRouteParam();
  if (type4) {
    dataCenter.formState.scheme_detail.forEach((element, index) => {
      element.ordern = index + 1;
    });
    let init_paramCopy = JSON.parse(JSON.stringify(dataCenter.formState.init_paramCopy));
    init_paramCopy.forEach((element) => {
      dataCenter.formState.init_param.push({
        param: element.param_mark,
        value: element.value,
      });
    });
    let yield_paramCopy = JSON.parse(JSON.stringify(dataCenter.formState.yield_paramCopy));
    yield_paramCopy.forEach((element) => {
      dataCenter.formState.yield_param.push(element.value);
    });
    let route_paramCopy = JSON.parse(JSON.stringify(dataCenter.formState.route_paramCopy));
    route_paramCopy.forEach((element) => {
      dataCenter.formState.route_param.push(element.value);
    });
    addForecastFlood(dataCenter.formState).then((res) => {
      if (res.code == 200) {
        createMessage.success(res.msg);
        closeModal();
      } else {
        createMessage.warning(res.msg);
      }
    });
  }
};
const mapRouteParam = () => {
  if (dataCenter.formState.route_paramCopy.length == 0) {
    createMessage.warning('请新增汇流中间变量配置');
    return false;
  }
  for (let index = 0; index < dataCenter.formState.route_paramCopy.length; index++) {
    const element = dataCenter.formState.route_paramCopy[index];
    if (
      (typeof element.value == 'undefined' || element.value === '' || element.value === null) &&
      element.value !== 0
    ) {
      createMessage.warning('请完善汇流中间变量配置参数');
      return false;
    }
  }
  return true;
};
const mapYieldParam = () => {
  for (let index = 0; index < dataCenter.formState.yield_paramCopy.length; index++) {
    const element = dataCenter.formState.yield_paramCopy[index];
    if (
      (typeof element.value == 'undefined' || element.value === '' || element.value === null) &&
      element.value !== 0
    ) {
      return false;
    }
  }
  return true;
};
const mapInitParam = () => {
  for (let index = 0; index < dataCenter.formState.init_paramCopy.length; index++) {
    const element = dataCenter.formState.init_paramCopy[index];
    if (element.value === '' || element.value === null) {
      return false;
    }
  }
  return true;
};
const mapValue = () => {
  for (let index = 0; index < dataCenter.formState.scheme_detail.length; index++) {
    const element = dataCenter.formState.scheme_detail[index];
    let arr = Object.values(element);
    for (let index1 = 0; index1 < arr.length; index1++) {
      const item = arr[index1];
      if (item === '' || item === null) {
        return false;
      }
    }
  }
  return true;
};
const prev = () => {
  dataCenter.current--;
};
const onDelete = (index) => {
  dataCenter.formState.scheme_detail.splice(index, 1);
  console.log(dataCenter.formState.scheme_detail);
};
const [registerModal, { closeModal, setModalProps }] = useModalInner(async () => {
  dataCenter.current = 0;
  dataCenter.formState = {
    pid: '',
    pid_name: '',
    scheme_name: '',
    area: '',
    stcd_q: '',
    weather_type: '',
    model_id: '',
    scheme_detail: [],
    init_paramCopy: [],
    route_paramCopy: [],
    route_param: [],
    yield_param: [],
    init_param: [],
    yield_paramCopy: [
      {
        name: 'S',
        value: '',
      },
      {
        name: 'WU',
        value: '',
      },
      {
        name: 'WL',
        value: '',
      },
      {
        name: 'WD',
        value: '',
      },
      {
        name: 'RS',
        value: '',
      },
      {
        name: 'RI',
        value: '',
      },
      {
        name: 'RG',
        value: '',
      },
      {
        name: 'QS',
        value: '',
      },
      {
        name: 'QI',
        value: '',
      },
      {
        name: 'QI',
        value: '',
      },
    ],
  };
});
// 获取流域点号
function getBasinList() {
  // 查询断面
  getSponner({ colume_id: 'transect' }).then((res) => {
    console.log(res);
    dataCenter.basinList = res.data;
  });
  // 查询站点实测流量
  getSponner({ colume_id: 'stcd_real' }).then((res) => {
    dataCenter.basinList2 = res.data;
  });
  // 数值天气预报
  getSponner({ colume_id: 'weather_type' }).then((res) => {
    dataCenter.basinList3 = res.data;
  });
  // 模型ID
  getSponner({ colume_id: 'model_id' }).then((res) => {
    dataCenter.basinList4 = res.data;
  });
  // 雨量站
  getSchemeSpinner({ colume_id: 'stcd_p' }).then((res) => {
    dataCenter.rainfall = res.data;
  });
  // 气象站
  schemeAddSpinner({ colume_id: 'stcd_m' }).then((res) => {
    dataCenter.meteorological = res.data;
  });
  // 上游来水站
  getSchemeSpinner({ colume_id: 'stcd_inq' }).then((res) => {
    dataCenter.upstream = res.data;
  });
  // 上游预报方案
  getSchemeSpinner({ colume_id: 'stcd_inqup' }).then((res) => {
    dataCenter.programme = res.data;
  });
  // 接入类型
  getSchemeSpinner({ colume_id: 'optimaze_type' }).then((res) => {
    dataCenter.accessType = res.data;
  });
}
// 点击确定
async function handleSubmit() {
  console.log('点击了确定');
}
</script>
<style scoped lang="less">
.form-box {
  width: 500px;
  // margin-top: 20px;
  margin: 30px auto;
}

.steps-action {
  text-align: center;
}

::v-deep .ant-modal-footer {
  padding: 0 !important;
}

.list1-btn {
  text-align: right;
  margin: 10px;
}

.table1 {
  margin-bottom: 10px;
  margin-top: 10px;
}

.table-flex {
  display: flex;

  &>div {
    width: 47%;
  }

  &>div:nth-child(1) {
    margin-right: 6%;
  }

  &>div:nth-child(2) {
    position: relative;

    .btn-righe {
      position: absolute;
      right: 0px;
      top: 0px;
    }
  }
}

.table-title {
  font-size: 16px;
  margin: 10px 0;
}
</style>