<template>
  <div class="airportInfo scroll-y">
    <div class="wrap">
      <Minheader
        :is-auth="true"
        :is-btn="true"
        :is-search="true"
        :is-statuser="true"
        powerData="container_addition_button"
        @clearForm="clearForm"
        @searchForms="searchForms"
        @addForm="addForm"
      >
        <template #header>
          <div class="status flex-wrap">
            <div class="manageTitle">容器类型维护</div>
          </div>
        </template>
      </Minheader>
      <div class="app-containers">
        <DataTable
          :tableHeader="tableCols"
          :tableData="tableData"
          :tableBtnGroup="tableBtnGroup"
          :tableProperty="{ rowKey: 'ID' }"
          @btnClick="btnClick"
        />
      </div>
      <Dialog
        :flag="flag"
        :type="type"
        :msgTitle="msgTitle"
        :delName="tableForm.containerName"
        @resetForm="resetForm"
        @delRest="delRest"
        @submitForm="submitForm"
        @delRemove="delRemove"
      >
        <div class="diacont">
          <el-form
            :model="tableForm"
            :rules="formRules"
            ref="containerMaintenanceForm"
          >
            <el-row :gutter="24">
              <el-col>
                <el-form-item
                  label="容器类型ID"
                  size="default"
                  prop="containerID"
                  :rules="formRules.isNotNull"
                >
                  <el-input
                    v-model="tableForm.containerID"
                    placeholder="请输入容器类型ID"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item
                  label="容器类型名称"
                  size="default"
                  prop="containerName"
                  :rules="formRules.isNotNull"
                >
                  <el-input
                    v-model="tableForm.containerName"
                    placeholder="请输入容器类型名称"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item
                  label="容器类型识别码"
                  size="default"
                  prop="containerCode"
                  :rules="formRules.isNotNull"
                >
                  <el-input
                    v-model="tableForm.containerCode"
                    placeholder="请输入容器类型识别码"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item
                  label="容器单位"
                  size="default"
                  prop="containerUnit"
                  :rules="formRules.isNotNull"
                >
                  <el-input
                    v-model="tableForm.containerUnit"
                    placeholder="请输入容器单位"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="备注" size="default">
                  <el-input
                    type="textarea"
                    v-model="tableForm.containerDesc"
                    placeholder="请输入备注"
                  />
                </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 { useUserStore } from "@/store/user";
import { Query, GeneralDataReception } from "@/api/webApi";
import { ElMessage } from "element-plus";
const formRules = useElement().formRules;
const page = ref<number>(0); //分页参数
const router = useRouter();
const dataContent = ref<object>({});
const noMore = ref<boolean>(false);
const rowTitle = ref<string>("");
const tableCols = ref<any>([]); //表头数据
const serviceId = ref<any>("");
const tableObj = ref({}); //增删改数据缓存
const flag = ref<boolean>(false); //弹窗开关
const type = ref<string>(""); //判断是否删除
const conditon = ref("");
const conditonLisy = ref<any>([]);
const tableDatacp = ref<any[]>([]);
const msgTitle = ref<string>("新增容器维护"); //弹窗标题
const tableColsCopys = reactive<Object>({}); //弹窗
const tableForm = reactive<any>({
  containerID: "",
  containerName: "",
  containerCode: "",
  containerDesc: "",
  containerUnit: "",
  event: "",
}); //弹窗内容
//列表
const tableData = ref<any>([]);
//表头
const state = reactive({
  list: [
    { label: "容器名称", key: "name" },
    { label: "容器标识符", key: "china" },
    { label: "容器描述", key: "englin" },
  ],
  listLoading: true,
});
const tableBtnGroup = ref([
  {
    name: "编辑",
    className: "editBtn",
    param: 2,
    is: "container_edit_button",
  },
  {
    name: "删除",
    className: "delBtn",
    param: 3,
    is: "container_deletion_button",
  },
]);
const searchForms = (val) => {
  getQuery(val);
};

const clearForm = () => {
  getQuery();
};
//新增
const addForm = () => {
  msgTitle.value = "新增类型维护";
  flag.value = true;
  type.value = "";
  for (const key in tableForm) {
    tableForm[key] = "";
  }
  tableForm.event = 1;
};
//取消
const resetForm = () => {
  containerMaintenanceForm.value?.resetFields();
  flag.value = false;
  // tableForm.containerID = "";
  // tableForm.containerName = "";
  // tableForm.containerCode = "";
  // tableForm.containerDesc = "";
  // tableForm.containerUnit = "";
};
//编辑
const editDialog = (data) => {
  msgTitle.value = "编辑容器类型维护";
  flag.value = true;
  type.value = "";
  tableForm.name = data.name;
  tableForm.china = data.china;
  tableForm.englin = data.englin;
};
//删除
const eleDialog = () => {
  msgTitle.value = "删除容器类型维护";
  flag.value = true;
  type.value = "del";
};
const delRemove = () => {
  const obj = {
    containerID: tableForm.containerID,
    event: 3,
  };
  generalDataReception(obj);
};
//删除
const delRest = () => {
  flag.value = false;
};
//编辑-删除
const btnClick = (row, index, param) => {
  if (param === 2) {
    msgTitle.value = "编辑容器类型维护";
    flag.value = true;
    type.value = "";
    tableForm.event = 2;
    tableForm.containerID = index.containerID;
    tableForm.containerName = index.containerName;
    tableForm.containerCode = index.containerCode;
    tableForm.containerDesc = index.containerDesc;
    tableForm.containerUnit = index.containerUnit;
  } else if (param === 3) {
    msgTitle.value = "删除容器类型维护";
    flag.value = true;
    type.value = "del";
    tableForm.event = 3;
    tableForm.containerID = index.containerID;
    tableForm.containerName = index.containerName;
    tableForm.containerCode = index.containerCode;
    tableForm.containerDesc = index.containerDesc;
  } else if (param === 4) {
  }
};
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,
    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;
  getQuery();
};
//获取表格数据
const getQuery = async (val = "") => {
  try {
    const { code, returnData } = await Query({
      id: DATACONTENT_ID.containerNodeId,
      needPage: ++page.value,
      dataContent: [val],
    });
    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;
      }
      tableDatacp.value = [...returnData.listValues];
      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;
          });
        });
      }
      tableCols.value = [];
      if (conditon.value == null) {
        tableCols.value = returnData.columnSet;
      } else {
        tableCols.value = [];
        conditon.value.split(",").forEach((element) => {
          returnData.columnSet.forEach((res) => {
            if (element === res.columnName) {
              tableCols.value.push(res);
            }
          });
        });
      }
      tableCols.value.forEach((element) => {
        element.label = element.columnLabel;
        element.key = element.columnName;
        // if (element.columnName === "queryTemplate") {
        //   element.width = "300px";
        // }
      });
      serviceId.value = returnData.submitID;
    } else {
      page.value--;
    }
  } catch (error) {
    page.value--;
  }
};
//确认提交
const containerMaintenanceForm: any = ref(null);
const submitForm = () => {
  containerMaintenanceForm.value.validate((valid: any) => {
    if (valid) {
      generalDataReception(tableForm);
    } else {
      return false;
    }
  });
};
const resetTable = () => {
  page.value = 0;
  noMore.value = false;
  tableData.value = [];
};

const btnAuthMap = [
  ,
  "container_addition_button",
  "container_edit_button",
  "container_deletion_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();
      gueryRoles();
      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();
  }
};
gueryRoles();
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__label {
  width: 130px;
}
</style>
