<template>
  <div class="airportInfo scroll-y">
    <div class="wrap">
      <Minheader
        :is-auth="true"
        :is-statuser="true"
        powerData="new_airlines_button"
        @addForm="addForm"
      >
        <template #header>
          <div class="status flex-wrap">
            <div class="manageTitle">屏蔽航司维护</div>
          </div>
        </template>
      </Minheader>
      <div class="app-containers">
        <DataTable
          :tableHeader="tableColst"
          :tableData="tableData"
          :tableBtnGroup="tableBtnGroup"
          :tableProperty="{ rowKey: 'ID' }"
          @btnClick="btnClick"
        />
      </div>
      <Dialog
        :flag="flag"
        :type="type"
        :msgTitle="msgTitle"
        :delName="tableForm.code"
        @resetForm="resetForm"
        @delRest="delRest"
        @submitForm="submitForm"
        @delRemove="delRemove"
      >
        <div class="diacont">
          <el-form
            :model="tableForm"
            :rules="formRules"
            ref="airlineCompanyForm"
          >
            <el-row :gutter="24">
              <el-col>
                <el-form-item
                  label="航司二字码"
                  prop="code"
                  size="default"
                  :rules="formRules.isNotNull"
                >
                  <el-input
                    v-model="tableForm.code"
                    placeholder="请输入航司二字码"
                  />
                </el-form-item>
                <el-form-item label="进港" prop="in_type" size="default">
                  <el-checkbox
                    v-model="tableForm.in_type"
                    :true-label="1"
                    :false-label="0"
                    size="default"
                  />
                </el-form-item>
                <el-form-item label="出港" prop="out_type" size="default">
                  <el-checkbox
                    v-model="tableForm.out_type"
                    :true-label="1"
                    :false-label="0"
                    size="default"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </Dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
import DataTable from "@/components/tableTemp/index.vue";
import Minheader from "@/components/minheader/index.vue";
import Dialog from "@/components/dialog/index.vue";
import { Query, GeneralDataReception } from "@/api/webApi";
import { ElMessage } from "element-plus";
import { CommonTableColumn, CommonValue } from "~/common";
import { useUserStore } from "@/store/user";
const router = useRouter();
const tableColumns = [
  {
    columnLabel: "航司二字码",
    columnName: "code",
  },
  {
    columnLabel: "进港",
    columnName: "in_type_zh",
  },
  {
    columnLabel: "出港",
    columnName: "out_type_zh",
  },
].map((column) => ({
  columnDescribe: "",
  dataType: "",
  listqueryTemplateID: null,
  needCount: null,
  needFilters: null,
  needGroup: null,
  needSearch: null,
  needShow: 1,
  needSort: null,
  orderNumber: null,
  queryTemplateColumnSetID: null,
  queryTemplateID: null,
  ...column,
}));
const conditon = ref("");
const conditonLisy = ref<any>([]);
const tableDatacp = ref<any[]>([]);
const formRules = useElement().formRules;
const page = ref(0); //分页参数
const dataContent = ref<any>({});
const noMore = ref(false);
const tableCols = ref<CommonTableColumn[]>(tableColumns); //表头数据
const tableColst = ref<any[]>([]); //表头数据
const serviceId = ref<number | null>(null);
const tableObj = ref<any>({}); //增删改数据缓存
const flag = ref(false); //弹窗开关
const type = ref(""); //判断是否删除
const msgTitle = ref("新增屏蔽航司"); //弹窗标题
const tableForm = reactive({
  id: null,
  code: "",
  in_type: 1,
  out_type: 1,
  event: 0,
}); //弹窗内容
//列表
const tableData = ref<CommonValue[]>([]);
const tableBtnGroup = ref([
  {
    name: "编辑",
    className: "editBtn",
    param: 2,
    is: "airline_editor_button",
  },
  {
    name: "删除",
    className: "delBtn",
    param: 3,
    is: "airlines_delete_button",
  },
]);
//新增
const addForm = () => {
  msgTitle.value = "新增屏蔽航司";
  for (const key in tableForm) {
    tableForm[key] = "";
  }
  tableForm.event = 1;
  flag.value = true;
  type.value = "";
};
//取消
const resetForm = () => {
  airlineCompanyForm.value?.resetFields();
  flag.value = false;
  // tableForm.id = null
  // tableForm.code = ''
  // tableForm.in_type = 1
  // tableForm.out_type = 1
  // tableForm.event = 0
};
//编辑-删除
const btnClick = (index, row, param) => {
  if (param === 2) {
    msgTitle.value = "编辑屏蔽航司";
    flag.value = true;
    type.value = "";
    tableForm.event = 2;
    tableForm.id = row.id;
    tableForm.code = row.code;
    tableForm.in_type = row.in_type;
    tableForm.out_type = row.out_type;
  } else if (param === 3) {
    msgTitle.value = "删除屏蔽航司";
    flag.value = true;
    type.value = "del";
    tableForm.event = 3;
    tableForm.id = row.id;
    tableForm.code = row.code;
    tableForm.in_type = row.in_type;
    tableForm.out_type = row.out_type;
  }
};
//删除
const delRemove = () => {
  tableForm.event = 3;
  generalDataReception(tableForm);
};
//删除
const delRest = () => {
  flag.value = false;
};
const gueryRoles = async () => {
  const route = router.currentRoute;
  const authMap = useUserStore().authMap;
  const role = route.value.meta?.roles?.[0];
  const { code, returnData } = await Query({
    id: DATACONTENT_ID.allId,
    needPage: ++page.value,
    dataContent: [authMap[role], sessionStorage.getItem("User_Id")],
  });
  conditon.value = returnData.listValues[0].query_col_conditon;
  conditonLisy.value = returnData.listValues[0].query_row_condition
    ? JSON.parse(returnData.listValues[0].query_row_condition)
    : null;
  if (conditon.value == null) {
    tableColst.value = tableCols.value;
  } else {
    tableColst.value = [];
    conditon.value.split(",").forEach((element) => {
      tableCols.value.forEach((res) => {
        if (element === res.columnName) {
          tableColst.value.push(res);
        }
      });
    });
  }
};
//获取表格数据
const getQuery = async () => {
  try {
    const { code, returnData } = await Query({
      id: DATACONTENT_ID.hiddenCompany,
      needPage: ++page.value,
      dataContent: Object.values(dataContent.value),
    });
    if (code === "0") {
      if (returnData.listValues.length === 0) {
        page.value--;
        noMore.value = true;
      }
      tableDatacp.value.push(
        ...returnData.listValues.map((row) => ({
          in_type_zh: row.in_type ? "是" : "否",
          out_type_zh: row.out_type ? "是" : "否",
          ...row,
        }))
      );
      tableData.value = [];
      if (conditonLisy.value == null) {
        tableData.value = tableDatacp.value;
      } else {
        let art = [];
        let arts = [];
        let art2 = [];
        let art3 = [];
        conditonLisy.value.forEach((element) => {
          if (element.conn == "%") {
            tableDatacp.value.forEach((res) => {
              if (res[element.key] && res[element.key].includes(element.val)) {
                art.push(res);
              }
            });
          }
          if (element.conn == "=") {
            if (art.length == 0) {
              art = tableDatacp.value;
            }
            art.forEach((res) => {
              if (res[element.key] == element.val) {
                arts.push(res);
              }
            });
          }
          setTimeout(() => {
            if (element.conn == ">") {
              if (arts.length == 0) {
                arts = tableDatacp.value;
              }
              arts.forEach((res) => {
                if (Number(res[element.key]) - Number(element.val) > 0) {
                  art2.push(res);
                }
              });
            }
          });
          setTimeout(() => {
            if (element.conn == "<") {
              if (art2.length == 0) {
                art2 = tableDatacp.value;
              }
              art2.forEach((res) => {
                if (Number(res[element.key]) - Number(element.val) < 0) {
                  art3.push(res);
                }
              });
            }
            tableData.value = art3.length > 0 ? art3 : art2;
          });
        });
      }
      serviceId.value = returnData.submitID!;
    } else {
      page.value--;
    }
  } catch (error) {
    page.value--;
  }
};
//确认提交
const airlineCompanyForm: any = ref(null);
const submitForm = () => {
  airlineCompanyForm.value.validate((valid: any) => {
    if (valid) {
      generalDataReception(tableForm);
    } else {
      return false;
    }
  });
};
const resetTable = () => {
  page.value = 0;
  noMore.value = false;
  tableData.value = [];
};

const btnAuthMap = [
  ,
  "new_airlines_button",
  "airline_editor_button",
  "airlines_delete_button",
];
//新增-编辑-删除
const generalDataReception = async (data) => {
  try {
    data = {
      ...data,
    };
    const { code } = await GeneralDataReception({
      serviceId: serviceId.value,
      dataContent: JSON.stringify(data),
      btnAuth: btnAuthMap[data.event],
    });
    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();
  }
};
onMounted(() => {
  gueryRoles();
  getQuery();
});
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__label {
  width: 100px;
}
.app-containers {
  height: calc(100vh - 180px);
}
</style>
