<template>
  <div class="airportInfo">
    <div class="headerBox">
      <Minheader :is-Preser="true" :is-statuser="true" @preserForm="preserForm">
        <template #header>
          <div class="status flex-wrap">
            <div class="manageTitle">预警告警场景</div>
          </div>
        </template></Minheader
      >
      <div class="diacont">
        <el-form
          :model="tableForm"
          class="w100 fw"
          :rules="formRules"
          ref="warningEditsForm"
        >
          <!-- <div class="outersurface pd30">
            <el-form-item label="策略名称" size="default">
              <el-input v-model="tableForm.name" placeholder="请输入策略名称" />
            </el-form-item>
          </div> -->
          <div class="outersurface pd30">
            <el-form-item
              label="航司二字码"
              size="default"
              prop="IATACode"
              :rules="formRules.isNotNull"
            >
              <el-input
                v-model="tableForm.IATACode"
                placeholder="请输入航司二字码"
              />
            </el-form-item>
          </div>
          <div class="outersurface pd30">
            <el-form-item label="起飞机场" size="default">
              <el-select
                style="width: 100%"
                v-model="tableForm.departmentAirport"
                class="input-shadow"
                filterable
                default-first-option
                clearable
                placeholder="请选择起飞机场"
              >
                <el-option
                  v-for="item in tableOption"
                  :key="item.v ? item.v : item.planDepartureApt"
                  :label="item.k ? item.k : item.planDepartureApt"
                  :value="item.v ? item.v : item.planDepartureApt"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="outersurface pd30">
            <el-form-item label="降落机场" size="default">
              <el-select
                style="width: 100%"
                v-model="tableForm.landingAirport"
                class="input-shadow"
                filterable
                default-first-option
                clearable
                placeholder="请选择降落机场"
              >
                <el-option
                  v-for="item in tableOption"
                  :key="item.v ? item.v : item.planDepartureApt"
                  :label="item.k ? item.k : item.planDepartureApt"
                  :value="item.v ? item.v : item.planDepartureApt"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="outersurface">
            <el-form-item
              label="航班号"
              size="default"
              prop="flightNo"
              :rules="formRules.isNotNull"
            >
              <el-input
                v-model="tableForm.flightNo"
                placeholder="请输入航班号"
              />
            </el-form-item>
          </div>
          <div class="outersurface pd30">
            <el-form-item
              label="生效时间"
              size="default"
              prop="startDate"
              :rules="formRules.isNotNull"
            >
              <el-date-picker
                v-model="tableForm.startDate"
                :rows="1"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </div>
          <div class="outersurface pd30">
            <el-form-item
              label="失效时间"
              size="default"
              prop="endDate"
              :rules="formRules.isNotNull"
            >
              <el-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="tableForm.endDate"
                :rows="1"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div class="centerBox">
      <Minheader
        :is-auth="true"
        :is-statuser="true"
        :is-Search="false"
        powerData="add_alert_policy_button"
        @addForm="addForm"
        style="margin-top: 20px"
      >
        <template #header>
          <div class="status flex-wrap">
            <div class="manageTitle">预警告警策略</div>
          </div>
        </template></Minheader
      >
    </div>
    <div class="containers scroll-y">
      <DataTable
        :tableHeader="tableCols"
        :tableData="tableData"
        :tableBtnGroup="tableBtnGroup"
        :tableProperty="{ rowKey: 'ID' }"
        @btnClick="btnClick"
      />
    </div>
    <Dialog
      width="600px"
      :flag="flag"
      :type="type"
      :msgTitle="msgTitle"
      :delName="delName"
      @resetForm="resetForm"
      @delRest="delRest"
      @submitForm="submitForm"
      @delRemove="delRemove"
    >
      <div class="diacont">
        <el-form :model="tableForms" :rules="formRules" ref="warningEditForm">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item
                label="策略名称"
                size="default"
                prop="StrategyName"
                :rules="formRules.isNotNull"
              >
                <el-input
                  v-model="tableForms.StrategyName"
                  placeholder="请输入策略名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计算依据" size="default">
                <el-select
                  style="width: 100%"
                  v-model="tableForms.calculationBasis"
                  class="input-shadow"
                  filterable
                  default-first-option
                  clearable
                  placeholder="请选择计算依据"
                >
                  <el-option
                    v-for="item in calculationBasis"
                    :key="item.v ? item.v : item.planDepartureApt"
                    :label="item.k ? item.k : item.planDepartureApt"
                    :value="item.v ? item.v : item.planDepartureApt"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="预警时长"
                size="default"
                prop="warningDuration"
                :rules="formRules.isNotNull"
              >
                <el-input
                  v-model="tableForms.warningDuration"
                  placeholder="请输入预警时长"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="报警时长"
                size="default"
                prop="alarmDuration"
                :rules="formRules.isNotNull"
              >
                <el-input
                  v-model="tableForms.alarmDuration"
                  placeholder="请输入报警时长"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始节点" size="default">
                <el-select
                  style="width: 100%"
                  v-model="tableForms.beginNode"
                  class="input-shadow"
                  filterable
                  default-first-option
                  clearable
                  placeholder="请选择开始节点"
                  @change="changeSelect"
                >
                  <el-option
                    v-for="item in tableOptionser"
                    :key="item.v"
                    :label="item.k"
                    :value="item.v"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始位置" size="default">
                <el-select
                  style="width: 100%"
                  v-model="tableForms.beginPosition"
                  class="input-shadow"
                  filterable
                  default-first-option
                  clearable
                  placeholder="请选择开始位置"
                  @change="changebegin"
                >
                  <el-option
                    v-for="item in tableOptionbegin"
                    :key="item.v ? item.v : item.planDepartureApt"
                    :label="item.k ? item.k : item.planDepartureApt"
                    :value="item.v ? item.v : item.planDepartureApt"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束节点" size="default">
                <el-select
                  style="width: 100%"
                  v-model="tableForms.endNode"
                  class="input-shadow"
                  filterable
                  default-first-option
                  clearable
                  placeholder="请选择结束节点"
                  @change="changeSelected"
                >
                  <el-option
                    v-for="item in tableOptionend"
                    :key="item.v ? item.v : item.planDepartureApt"
                    :label="item.k ? item.k : item.planDepartureApt"
                    :value="item.v ? item.v : item.planDepartureApt"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束位置" size="default">
                <el-select
                  style="width: 100%"
                  v-model="tableForms.endPosition"
                  class="input-shadow"
                  filterable
                  default-first-option
                  clearable
                  placeholder="请选择结束位置"
                  @change="changeEndPos"
                >
                  <el-option
                    v-for="item in tableOptionendPos"
                    :key="item.v ? item.v : item.planDepartureApt"
                    :label="item.k ? item.k : item.planDepartureApt"
                    :value="item.v ? item.v : item.planDepartureApt"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import Minheader from "@/components/minheader/index.vue";
import DataTable from "@/components/tableTemp/index.vue";
import Dialog from "@/components/dialog/index.vue";
import { Query, GeneralDataReception } from "@/api/webApi";
import { ElMessage } from "element-plus";
const formRules = useElement().formRules;
const router = useRouter();
const route = useRoute();
const page = ref<number>(0); //分页参数
const dataContent = ref<object>({});
const noMore = ref<Boolean>(false);
const rowTitle = ref<String>("");
const tableCols = ref([]); //表头数据
const serviceId = ref<String>("");
const beginPositionId = ref<String>("");
const endPositionId = ref<String>("");
const tableObj = ref({}); //增删改数据缓存
const delName = ref<String>("");
const tableForm = reactive({
  alarmSceneId: "",
  IATACode: "",
  departmentAirport: "",
  landingAirport: "",
  flightNo: "",
  startDate: "",
  endDate: "",
  event: 2,
}); //报警预警场景
const tableForms = reactive({
  alarmStrategyID: "",
  StrategyName: "",
  calculationBasis: "",
  warningDuration: "",
  alarmDuration: "",
  beginNode: "",
  beginPosition: "",
  endNode: "",
  endPosition: "",
  alarmSceneId: route.query.alarmSceneId,
  event: "",
}); //弹窗内容
const tableOption = ref<Array>([]); //下拉
const tableOptionser = ref<Array>([]); //下拉
const tableOptionbegin = ref<Array>([]); //下拉
const tableOptionend = ref<Array>([]); //下拉
const tableOptionendPos = ref<Array>([]); //下拉
const calculationBasis = ref<Array>([]); //下拉
const flag = ref<Boolean>(false); //弹窗开关
const type = ref<String>(""); //判断是否删除
const msgTitle = ref<String>("新增报警预警策略"); //弹窗标题
//列表
const tableData = ref([]);
//表头
const state = reactive({
  list: [
    { label: "名称", key: "name", width: "100px" },
    { label: "三字码", key: "china", width: "50px" },
    { label: "四字码", key: "englin", width: "50px" },
    { label: "中文简称", key: "two", width: "50px" },
    { label: "英文简称", key: "three", width: "50px" },
    { label: "全称", key: "text", width: "50px" },
    { label: "时区", key: "text1", width: "50px" },
    { label: "公司名称", key: "text2", width: "50px" },
  ],
  listLoading: true,
});
const tableBtnGroup = ref([
  {
    name: "编辑",
    className: "editBtn",
    param: 2,
    is: "edit_alert_policy_button",
  },
  {
    name: "删除",
    className: "delBtn",
    param: 3,
    is: "delete_alert_policy_button",
  },
]);
//新增
const addForm = () => {
  msgTitle.value = "新增报警预警策略";
  flag.value = true;
  type.value = "";
  tableForms.event = 1;
};
//取消
const resetForm = () => {
  flag.value = false;
  tableForms.alarmStrategyID = "";
  tableForms.StrategyName = "";
  tableForms.calculationBasis = "";
  tableForms.warningDuration = "";
  tableForms.alarmDuration = "";
  tableForms.beginNode = "";
  tableForms.beginPosition = "";
  tableForms.endNode = "";
  tableForms.endPosition = "";
  delName.value = "";
};
const delRemove = () => {
  tableForms.event = 3;

  generalDataReception(tableForms);
};
//删除
const delRest = () => {
  flag.value = false;
};
//编辑-删除
const btnClick = (row, index, param) => {
  if (param === 2) {
    msgTitle.value = "编辑报警预警策略";
    flag.value = true;
    type.value = "";
    tableForms.event = 2;
    calculationBasis.value.forEach((element) => {
      if (index.calculationBasis === element.k) {
        tableForms.calculationBasis = element.v;
      }
    });
    tableOptionser.value.forEach((element) => {
      if (index.beginNode === element.k) {
        tableForms.beginNode = element.v;
      }
    });
    tableOptionbegin.value.forEach((element) => {
      if (index.beginPosition === element.k) {
        tableForms.beginPosition = element.v;
      }
    });
    tableOptionend.value.forEach((element) => {
      if (index.endNode === element.k) {
        tableForms.endNode = element.v;
      }
    });
    tableOptionendPos.value.forEach((element) => {
      if (index.endPosition === element.k) {
        tableForms.endPosition = element.v;
      }
    });
    tableForms.alarmStrategyID = index.alarmStrategyID;
    tableForms.StrategyName = index.StrategyName;
    // tableForms.calculationBasis = index.calculationBasis;
    tableForms.warningDuration = index.warningDuration;
    tableForms.alarmDuration = index.alarmDuration;
    // tableForms.beginNode = index.beginNode;
    // tableForms.beginPosition = index.beginPosition;
    // tableForms.endNode = index.endNode;
    // tableForms.endPosition = index.endPosition;
  } else if (param === 3) {
    msgTitle.value = "删除报警预警策略";
    flag.value = true;
    type.value = "del";
    tableForms.event = 3;
    delName.value = index.StrategyName;
    tableForms.alarmStrategyID = index.alarmStrategyID;
    tableForms.StrategyName = index.StrategyName;
    tableForms.calculationBasis = index.calculationBasis;
    tableForms.warningDuration = index.warningDuration;
    tableForms.alarmDuration = index.alarmDuration;
    tableForms.beginNode = index.beginNode;
    tableForms.beginPosition = index.beginPosition;
    tableForms.endNode = index.endNode;
    tableForms.endPosition = index.endPosition;
  } else if (param === 4) {
  }
};

//获取预警报警场景(按照ID)
const sysServiceWarn = async () => {
  try {
    let arr = [route.query.alarmSceneId];
    // arr.push(this.$route.query.id);
    const { code, returnData } = await Query({
      id: DATACONTENT_ID.sysServiceWarnId,
      dataContent: arr,
    });
    if (code === "0") {
      tableForm.alarmSceneId = returnData.listValues[0].alarmSceneId
        ? returnData.listValues[0].alarmSceneId
        : "";
      tableForm.IATACode = returnData.listValues[0].IATACode
        ? returnData.listValues[0].IATACode
        : "";
      tableForm.departmentAirport = returnData.listValues[0].departmentAirport
        ? returnData.listValues[0].departmentAirport
        : "";
      tableForm.landingAirport = returnData.listValues[0].landingAirport
        ? returnData.listValues[0].landingAirport
        : "";
      tableForm.flightNo = returnData.listValues[0].flightNo
        ? returnData.listValues[0].flightNo
        : "";
      tableForm.startDate = returnData.listValues[0].startDate
        ? returnData.listValues[0].startDate
        : "";
      tableForm.endDate = returnData.listValues[0].endDate
        ? returnData.listValues[0].endDate
        : "";
    } else {
      // this.page--;
      // this.$message.error.message;
      // this.loading = false;
    }
  } catch (error) {
    // this.page--;
    // this.loading = false;
  }
};
//飞机场-下拉数据
const getSelectDatas = async (id, name) => {
  const { code, returnData } = await Query({
    id,
    dataContent: name ? [name] : name === null ? [null] : [],
  });
  if (code == 0) {
    tableOption.value = returnData.listValues;
  } else {
    tableOption.value = [];
  }
};
//获取弹框-下拉数据
const getSelectData = async (id, name, dataNme) => {
  const { code, returnData } = await Query({
    id,
    dataContent: name ? [name] : name === null ? [null] : [],
  });
  if (code == 0) {
    // return returnData.listValues;
    if (dataNme === "calculationBasis") {
      calculationBasis.value = returnData.listValues;
    }
    if (dataNme === "beginNode") {
      tableOptionser.value = returnData.listValues;
    } else if (dataNme === "beginPosition") {
      tableOptionbegin.value = returnData.listValues;
    } else if (dataNme === "endNode") {
      tableOptionend.value = returnData.listValues;
    } else if (dataNme === "endPosition") {
      tableOptionendPos.value = returnData.listValues;
    }
  } else {
  }
};
//获取表格数据
const getQuery = async () => {
  try {
    const { code, returnData } = await Query({
      id: DATACONTENT_ID.sysServiceStrategyId,
      needPage: ++page.value,
      dataContent: [route.query.alarmSceneId],
    });
    if (code === "0") {
      if (returnData.listValues.length === 0) {
        page.value--;
        noMore.value = true;
      }
      const titleColumn = returnData.columnSet.find(
        (item) => item.needShow === 1
      );
      if (titleColumn) {
        rowTitle.value = titleColumn.columnName;
      }
      tableData.value.push(...returnData.listValues);
      tableCols.value = returnData.columnSet;
      returnData.columnSet.forEach((item) => {
        if (item.columnName === "calculationBasis") {
          getSelectData(item.listqueryTemplateID, "", "calculationBasis");
        }
        if (item.listqueryTemplateID && item.columnName === "beginNode") {
          getSelectData(item.listqueryTemplateID, "", "beginNode");
        } else if (
          item.listqueryTemplateID &&
          item.columnName === "beginPosition"
        ) {
          getSelectData(item.listqueryTemplateID, null, "beginPosition");
          beginPositionId.value = item.listqueryTemplateID;
        } else if (item.listqueryTemplateID && item.columnName === "endNode") {
          getSelectData(item.listqueryTemplateID, "", "endNode");
        } else if (
          item.listqueryTemplateID &&
          item.columnName === "endPosition"
        ) {
          getSelectData(item.listqueryTemplateID, null, "endPosition");
          endPositionId.value = item.listqueryTemplateID;
        }
      });
      tableCols.value.forEach((element) => {
        element.label = element.columnLabel;
        element.key = element.columnName;
      });
      serviceId.value = returnData.submitID;
    } else {
      page.value--;
    }
  } catch (error) {
    page.value--;
  }
};
//开始节点
const changeSelect = (value) => {
  console.log(value);
  // tableOptionbegin.value = getSelectData(beginPositionId, value,'beginPosition');
  tableForms.beginPosition = "";
};
//开始位置
const changebegin = (value) => {};
//结束节点
const changeSelected = (value) => {
  // tableOptionendPos.value = getSelectData(endPositionId, value);
  tableForms.endPosition = "";
};
//结束位置
const changeEndPos = (value) => {};
//确认提交
const warningEditForm: any = ref(null);
const submitForm = () => {
  warningEditForm.value.validate((valid: any) => {
    if (valid) {
      generalDataReception(tableForms);
    } else {
      return false;
    }
  });
};
const resetTable = () => {
  page.value = 0;
  noMore.value = false;
  tableData.value = [];
};
//新增-编辑-删除
const generalDataReception = async (data) => {
  try {
    let obj = {
      alarmSceneId: route.query.alarmSceneId,
    };
    data = {
      ...data,
      ...obj,
    };
    const { code } = await GeneralDataReception({
      serviceId: serviceId.value,
      dataContent: JSON.stringify(data),
    });
    if (code == 0) {
      ElMessage.success(`操作成功`);
      // this.$message.success("操作成功");
      resetTable();
      getQuery();
      resetForm();
      flag.value = false;
      // rmFlag.value = false;
      tableObj.value = {};
      // this.$router.go(0);
    } else {
      ElMessage.error(`操作失败`);
      // this.$message.error("操作失败");
      // this.flag = false;
      // this.rmFlag = false;
      tableObj.value = {};
      resetForm();
    }
  } catch (error) {
    flag.value = false;
    //  rmFlag.value = false;
    tableObj.value = {};
    resetForm();
  }
};
//编辑数据
const warningEditsForm: any = ref(null);
const preserForm = async () => {
  warningEditsForm.value.validate((valid: any) => {
    if (valid) {
      generalDataReceptions(tableForm);
    } else {
      return false;
    }
  });
};
//表格-增/删/改
const generalDataReceptions = async (data) => {
  try {
    data = {
      ...data,
    };
    const { code, message } = await GeneralDataReception({
      serviceId: route.query.submitID,
      dataContent: JSON.stringify(data),
    });
    if (code === "0") {
      ElMessage.success(`操作成功`);
      router.push({ path: "/systemSettings/warningSet" });
    } else {
      ElMessage.error(`操作失败`);
    }
  } catch (error) {}
};
sysServiceWarn();
getQuery();
getSelectDatas(route.query.listqueryTemplateID);
</script>

<style lang="scss" scoped>
.airportInfo {
  .headerBox {
    width: 100%;
    min-height: 200px;
    background: #ffffff;
    border-radius: 4px;
    padding: 24px;
    .diacont {
      width: 100%;
      padding: 0;
      .w100 {
        width: 100%;
      }
      .fw {
        display: flex;
        flex-wrap: wrap;
      }
      .outersurface {
        width: 20%;
      }
      .pd30 {
        padding: 0 30px 0 0;
      }
      .outertwowid {
        width: 40%;
      }
      .outerthreewid {
        width: 60%;
      }
    }
  }
  .centerBox {
    padding: 0 24px;
  }
  .containers {
    height: 540px;
  }
}
::v-deep .el-form-item__label {
  width: 100px;
}
</style>
