<template>
  <el-dialog
    v-model="isShowTable"
    :title="tableTitle"
    width="1200"
    :before-close="handleClose"
    :append-to-body="true"
  >
    <avue-crud
      ref="crudRef"
      v-model:search="search"
      v-model="form"
      :data="data"
      :option="option"
      v-model:page="page"
      :row-class-name="rowStyle"
      @row-click="rowClick"
      @row-save="createRow"
      @row-update="updateRow"
      @row-del="deleteRow"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
      @selection-change="selectionChange"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="onSelected"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import { tableConfig } from "./configs/tableConfig";

const props = defineProps({
  tableTitle: {
    default: "",
    type: String,
  },
  tableType: {
    default: "",
    type: String,
  },
  multiple: {
    default: false,
    type: Boolean,
  },
  // 用于多选的返回值
  multipleKey: {
    default: "id",
    type: String,
  },
  multipleRow: {
    default: false,
    type: Boolean,
  },
});
const rowStyle = ({row}) => {
   if(row.isSelected){
     return "row-color";
   }
}
const isShowTable = ref(false);
const startSelect = async (param) => {
  if (param) {
    commonConfig.value.params = param;
  }
  dataList();
  isShowTable.value = true;
};

/**
 * propName 要跟字典配置的key一致
 * dictData 字典数据, 注意props的value和label
 * */
const refreshDictData = (propName, dictData, keyName = "value") => {
  nextTick(() => {
    if (dictData && dictData.length > 0 && crudRef.value) {
      crudRef.value.updateDic(propName, dictData);
      search.value[propName] = dictData[0][keyName];
    }
  });
};

/**
 * op 对象的字段要跟option实际字段一直 才能进行合并操作
 */
const mergeOption = (op) => {
  for (const key of Object.keys(op)) {
    option.value[key] = op[key];
  }
};

// 传入一个url，后面不带/
const {
  url,
  form,
  data,
  option,
  search,
  page,
  toDeleteIds,
  selectedRows,
  Methords,
  Utils,
  commonConfig,
} = useCrud({
  src: tableConfig[props.tableType].url,
  multipleSelectKey: props.multipleKey,
});
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件

const crudRef = ref(null); //crudRef.value 获取avue-crud对象

const commonTableEmits = defineEmits(["selectedSure", "selectMultipleSure"]);

const calculateColumnWidth = (column) => {
  if (!column.label) {
    return column.minWidth;
  }
  // 字宽度
  const fontSize = 17;
  let width = fontSize * (column.label.length + 2);
  // 如果开启过滤
  if (column.filters) {
    width += 12;
  }
  // 如果开启排序
  if (column.sortable) {
    width += 24;
  }
  return width;
};

onMounted(() => {
  if (props.tableType == "ROUTE_COMMON") {
    search.value.enabled = "0";
  }
  url.value = tableConfig[props.tableType].url;
  option.value = Object.assign(option.value, {
    searchEnter: true,
    menu: false,
    highlightCurrentRow: true,
    selection: props.multiple,
    addBtn: false,
    height: "500",
    overHidden: true,
    indexWidth: "120px",
    searchLabelWidth: "120px",
    column: tableConfig[props.tableType].column,
    selectable: function (row, index) {
      if (row&&!row.isSelected) {
        return true;
      }
    },
  });
  // 列处理
  if (option.value.column) {
    for (let col of option.value.column) {
      col.minWidth = calculateColumnWidth(col);
    }
  }
  // dataList();
});
watch(
  () => props.tableType,
  () => {
    url.value = tableConfig[props.tableType].url;
    option.value = Object.assign(option.value, {
      searchEnter: true,
      menu: false,
      highlightCurrentRow: true,
      selection: props.multiple,
      addBtn: false,
      height: "500",
      overHidden: true,
      searchLabelWidth: "120px",
      column: tableConfig[props.tableType].column,
      selectable: function (row, index) {
        if (row&&!row.isSelected) {
          return true;
        }
      },
    });
    // 列处理
    if (option.value.column) {
      for (let col of option.value.column) {
        col.minWidth = calculateColumnWidth(col);
      }
    }
    //dataList();
  }
);

const selectRowValue = ref({});
const rowClick = (row) => {
  selectRowValue.value = row;
};

const handleClose = () => {
  // 在这里可以清空打开的commonTable的搜索条件
  search.value.bomMaterialCode = "";

  crudRef.value.clearSelection();
  toDeleteIds.value = [];
  selectedRows.value = [];
  selectRowValue.value = {};
  isShowTable.value = false;

  console.log(
    "关闭弹窗",
    toDeleteIds.value,
    selectedRows.value,
    selectRowValue.value
  );
};

const onSelected = () => {
  if (props.multiple) {
    if (toDeleteIds.value.length < 1) {
      ElMessage.warning("未选择任何数据");
      return;
    }
    commonTableEmits("selectMultipleSure", toDeleteIds.value);
  } else {
    if (props.multipleRow) {
      console.log(selectedRows);
      commonTableEmits("selectedSure", selectedRows.value);
    } else {
      commonTableEmits("selectedSure", selectRowValue.value);
    }
  }

  handleClose();
};

defineExpose({ startSelect, refreshDictData, mergeOption });
</script>
<style>
   .row-color{
       background-color: #d3d3d3 !important;
       pointer-events: none;
   }
</style>
