<template>
  <div class="airportInfo scroll-y">
    <div class="wrap">
      <Minheader
        :is-auth="true"
        :is-statuser="true"
        :is-btn="true"
        :is-search="true"
        powerData="new_airport_companies_button"
        @searchForms="searchForms"
        @addForm="addForm"
        @clearForm="clearForm"
      >
        <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.companyName"
        @resetForm="resetForm"
        @delRest="delRest"
        @submitForm="submitForm"
        @delRemove="delRemove"
      >
        <div class="diacont">
          <el-form
            :model="tableForm"
            :rules="formRules"
            ref="airportCompanyForm"
          >
            <el-row :gutter="24">
              <el-col>
                <el-form-item
                  label="公司ID"
                  size="default"
                  :rules="formRules.isNotNull"
                  prop="companyID"
                >
                  <el-input
                    v-model="tableForm.companyID"
                    placeholder="请输入公司ID"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item
                  label="公司名称"
                  size="default"
                  :rules="formRules.isNotNull"
                  prop="companyName"
                >
                  <el-input
                    v-model="tableForm.companyName"
                    placeholder="请输入公司名称"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item
                  label="上级公司"
                  :rules="formRules.isNotNull"
                  prop="parentID"
                  size="default"
                >
                  <el-select
                    style="width: 100%"
                    v-model="tableForm.parentID"
                    class="input-shadow"
                    filterable
                    default-first-option
                    clearable
                    placeholder="请选择"
                  >
                    <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>
                <el-form-item
                  label="上级公司ID"
                  :rules="formRules.isNotNull"
                  size="default"
                  prop="parentID"
                >
                  <el-input
                    :disabled="tableForm.parentID == 'null'"
                    v-model="tableForm.parentID"
                    placeholder="请输入上级公司ID"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item
                  label="公司描述"
                  :rules="formRules.isNotNull"
                  size="default"
                >
                  <el-input
                    type="textarea"
                    v-model="tableForm.companyDesc"
                    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 { Query, GeneralDataReception } from "@/api/webApi";
import { useUserStore } from "@/store/user";
import * as _ from "lodash";
import { ElMessage } from "element-plus";
const router = useRouter();
const power = ref<string>("new_airlines_button"); //权限
const formRules = useElement().formRules;
const page = ref<number>(0); //分页参数
const dataContent = ref<object>({});
const noMore = ref<boolean>(false);
const asShow = 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 msgTitle = ref<string>("新增机场公司维护"); //弹窗标题
const tableOptionser = ref<any>([]); //弹窗下拉
const tableOptionCopys = ref<any>([]); //弹窗下拉
const tableColsCopys = reactive([]); //弹窗
const conditon = ref("");
const tableForm = reactive<any>({
  companyName: "",
  parentID: "",
  companyDesc: "",
  companyID: "",
  event: "",
}); //弹窗内容
const tableBtnGroup = ref([
  {
    name: "编辑",
    className: "editBtn",
    param: 2,
    is: "airport_company_editor_button",
  },
  {
    name: "删除",
    className: "delBtn",
    param: 3,
    is: "airport_company_deletion_button",
  },
]);
//列表
const tableData = ref<any>([]);
//表头
const state = reactive({
  list: [
    { label: "公司名称", key: "name" },
    { label: "公司描述", key: "china" },
    { label: "上级公司", key: "englin" },
  ],
  listLoading: true,
});
const searchForms = (val) => {
  gueryRoles();
  getQuery(val);
};

const clearForm = () => {
  gueryRoles();
};
//新增
const addForm = () => {
  msgTitle.value = "新增机场公司维护";
  flag.value = true;
  type.value = "";
  for (const key in tableForm) {
    tableForm[key] = "";
  }
  tableForm.event = 1;
  asShow.value = false;
  asShow.value = true;
};
//取消
const resetForm = () => {
  airportCompanyForm.value?.resetFields();
  flag.value = false;
  // tableForm.companyName = "";
  // tableForm.parentID = "";
  // tableForm.companyDesc = "";
  // tableForm.companyID = "";
};
//编辑-删除
const btnClick = (row, index, param) => {
  if (param === 2) {
    msgTitle.value = "编辑机场公司维护";
    flag.value = true;
    type.value = "";
    console.log(index);
    tableForm.event = 2;
    tableForm.companyName = index.companyName;
    tableForm.parentID = index.parentID == null ? "null" : index.parentID;
    tableForm.companyDesc = index.companyDesc;
    tableForm.companyID = index.companyID;
    tableOptionser.value = [];
    tableOptionCopys.value.forEach((element) => {
      if (element.k !== index.companyName) {
        tableOptionser.value.push(element);
      }
    });
  } else if (param === 3) {
    msgTitle.value = "删除机场公司维护";
    flag.value = true;
    type.value = "del";
    tableForm.event = 3;
    tableForm.companyName = index.companyName;
    tableForm.parentID = index.parentID;
    tableForm.companyDesc = index.companyDesc;
    tableForm.companyID = index.companyID;
  } else if (param === 4) {
  }
};
//删除
const delRest = () => {
  flag.value = false;
};
//获取弹框-下拉数据
const getSelectData = async (id?, name?) => {
  const { code, returnData } = await Query({
    id,
    dataContent: name ? [name] : name === null ? [null] : [],
  });
  if (code == 0 && returnData.listValues.length) {
    const nomarlObj = _.cloneDeep(returnData.listValues[0]);
    nomarlObj.k = "无";
    nomarlObj.v = "null";
    returnData.listValues.push(nomarlObj);
    tableOptionser.value = returnData.listValues;
    tableOptionCopys.value = _.cloneDeep(returnData.listValues);
  } else {
    tableOptionser.value = [];
  }
};
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;
  getQuery();
};
//获取表格数据
const getQuery = async (val = "") => {
  try {
    const { code, returnData } = await Query({
      id: DATACONTENT_ID.airportTreeId,
      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;
      }
      tableData.value = [...returnData.listValues];
      returnData.columnSet.forEach((item) => {
        if (item.listqueryTemplateID && item.columnName === "parentID") {
          getSelectData(item.listqueryTemplateID);
        }
      });
      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;
      });
      serviceId.value = returnData.submitID;
    } else {
      page.value--;
    }
  } catch (error) {
    page.value--;
  }
};
const changeSelect = (data, name) => {
  if (tableForm[data].value === "") {
    tableForm[data].value = null;
  }
};
const resetTable = () => {
  page.value = 0;
  noMore.value = false;
  tableData.value = [];
};

const btnAuthMap = [
  ,
  "new_airport_companies_button",
  "airport_company_editor_button",
  "airport_company_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();
  }
};
//确认提交
const airportCompanyForm: any = ref(null);
const submitForm = () => {
  airportCompanyForm.value.validate((valid: any) => {
    if (valid) {
      if (tableForm.parentID == "null") {
        tableForm.parentID = null;
      }
      generalDataReception(tableForm);
    } else {
      return false;
    }
  });
};
const delRemove = () => {
  tableForm.event = 3;
  generalDataReception(tableForm);
};
gueryRoles();
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__label {
  width: 100px;
}
</style>
