import { ref, onMounted} from "vue";
import { ElMessage ,ElMessageBox} from 'element-plus'
export default function pageManager({tableOptions,modelType,loading,isInit,ids,tableResult,rowResult,controlResult,pageKeys}) {
  let searchParams = {};
  const doFilter = (params) => {
    searchParams = params;
    getTableData();
  };
  const pageChange = () => {
    getTableData();
  };

  function getProp(obj, prop) {
    return prop.split('.').reduce((o, p) => o && o[p], obj);
  }
  let tableData = ref([]);
  const getTableData = () => {
    loading.value = true;
    tableOptions.getTableFn({...tableOptions.baseQuery,...searchParams,[pageKeys?.value?.page||'page']: tableOptions.pageInfo.base.current,[pageKeys?.value?.start||'start']: ((tableOptions.pageInfo.base.current - 1 ) *  tableOptions.pageInfo.base.limit),[pageKeys?.value?.limit||'limit']: tableOptions.pageInfo.base.limit}).then((res) => {
      loading.value = false;
      if (getProp(res,tableResult.value.codePath) == tableResult.value.successCode) {
        let resData = getProp(res,tableResult.value.dataPath);
        tableData.value = tableOptions.tableDataFormatter?tableOptions.tableDataFormatter(resData,res):(resData);
        tableOptions.pageInfo.total = getProp(res,tableResult.value.totalPath);
      }else{
        ElMessage.error(res.data.msg)
      }
    });
  };

  const showModel = ref(false);
  let editId = null;
  const editTableData = (data,callback) => {
    if (editId) {
      data[tableOptions.primaryKey] = editId;
      let params = {...tableOptions.baseUpdate,...data};
      if(tableOptions.beforeSubmit){
        params = tableOptions.beforeSubmit(params) || params;
      }
      tableOptions.editFn(params).then((res) => {
        if (getProp(res,controlResult.value.codePath) == controlResult.value.successCode) {
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          if(tableOptions.afterSubmit){
            let returnValue = tableOptions.afterSubmit()
            if(returnValue && returnValue instanceof Promise){
              returnValue.then(()=>{
                getTableData();
              })
            }else{
              getTableData();
            }
          }else{
            getTableData();
          }
          showModel.value = false;
        } else {
          ElMessage({
            message: getProp(res,controlResult.value.messagePath),
            type: "error",
          });
        }
        callback();
      }).catch(()=>{
        callback();
      });
    } else {
      let params = {...tableOptions.baseAdd,...data};
      if(tableOptions.beforeSubmit){
        params = tableOptions.beforeSubmit(params) || params;
      }
      tableOptions.addFn(params).then((res) => {
        if (getProp(res,controlResult.value.codePath) == controlResult.value.successCode) {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          if(tableOptions.afterSubmit){
            let returnValue = tableOptions.afterSubmit()
            if(returnValue && returnValue instanceof Promise){
              returnValue.then(()=>{
                getTableData();
              })
            }else{
              getTableData();
            }
          }else{
            getTableData();
          }
          showModel.value = false;
        } else {
          ElMessage({
            message: getProp(res,controlResult.value.messagePath),
            type: "error",
          });
        }
        callback();
      }).catch(()=>{
        callback();
      });
    }
  };
  const handleAdd = () => {
    editId = null;
    tableOptions.baseModelOptions.map((item) => {
      if(item.tag == 'BaseTree'){
        return item.attribute.defaultCheckedKey = []
      }else{
        return item.value = typeof item.default === "object" ? JSON.parse(JSON.stringify(item.default)) : (item.default || '');
      }
    });
    modelType.value = "add";
    isInit.value = true;
    showModel.value = true;
  };
  const handleEdit = async (index, row) => {
    if(!row){//顶部修改按钮
      if(ids.value.length == 1){
        row = tableData.value.find(item=>item[tableOptions.primaryKey] == ids.value[0])
      }else{
        ElMessage.error('请选择一条数据')
        return;
      }
    }
    let data,res;
    if(tableOptions.detailFn){
      res = await tableOptions.detailFn({[tableOptions.primaryKey]: row[tableOptions.primaryKey]})
      if(getProp(res,rowResult.value.codePath) == rowResult.value.successCode){
        data = getProp(res,rowResult.value.dataPath);
      }else{
        ElMessage({
          message: getProp(res,rowResult.value.messagePath),
          type: "error",
        });
        return;
      }
    }else{
      data = row;
    }
    if(tableOptions.beforeShowEdit){
      data = tableOptions.beforeShowEdit(data,res)
    }
    const doShow = ()=>{
      tableOptions.baseModelOptions.map((item) => {
        if(item.tag == 'BaseTree'){
          item.attribute.defaultCheckedKey = data[item.key]
        }
        else if(item.tag == 'BaseUpload'){
          let value = data[item.aliasKey || item.key] ?? item.value;
          if(value instanceof Array){
            item.value = value.map(item1=>{
              let url = item1[item.resKey?item.resKey[urlKey]:'url']
              let name = item1[item.resKey?item.resKey[nameKey]:'name']
              return {
                name: name,
                url: item.baseUrl + url,
                status: 'success',
                uid: url,
                response: {
                  url,
                  name
                }
              }
            })
          }else if(value instanceof Object){
            let url = value[item.resKey?item.resKey[urlKey]:'url']
            let name = value[item.resKey?item.resKey[nameKey]:'name']
            item.value = [
              {
                name: name,
                url: item.baseUrl + url,
                status: 'success',
                uid: url,
                response: {
                  url,
                  name
                }
              }
            ]
          }else{
            item.value = [
              {
                name: data[item.aliasKey || item.key],
                url: item.baseUrl + data[item.aliasKey || item.key],
                status: 'success',
                uid: data[item.aliasKey || item.key],
                response: {
                  url: data[item.aliasKey || item.key],
                  name: data[item.aliasKey || item.key]
                }
              }
            ]
          }
        }
        else{
          item.value = data[item.aliasKey || item.key] ?? item.value
        }
        
      });
      editId = data[tableOptions.primaryKey];
      modelType.value = "edit";
      showModel.value = true;
      isInit.value = true;
      
    }
    if(tableOptions.beforeEdit){
      tableOptions.beforeEdit(row).then(()=>{
        doShow();
      })
    }else{
      doShow()
    }
  };
  const deleteTableData = (index, row) => {
    let data;
    if(!row){//顶部修改按钮
      if(ids.value.length > 0){
        data = ids.value;
        if(tableOptions.beforeDelete){
          data = tableOptions.beforeDelete(data)
        }
      }else{
        ElMessage({
          message: "请选择要删除的数据",
          type: "error",
        });
        return;
      }
    }else{//行内删除按钮
      data = row;
      if(tableOptions.beforeDelete){
        data = tableOptions.beforeDelete(data)
      }else{
        data = row[tableOptions.primaryKey]
        data = data instanceof Array ? data : [data]
      }
      
    }
    //确认
    ElMessageBox.confirm("确定删除吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      tableOptions.deleteFn({
        [tableOptions.deleteKey || tableOptions.primaryKey]: data
      }).then((res) => {
        if (getProp(res,controlResult.value.codePath) == controlResult.value.successCode) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          if(tableOptions.afterDelete){
            let returnValue = tableOptions.afterDelete()
            if(returnValue && returnValue instanceof Promise){
              returnValue.then(()=>{
                getTableData();
              })
            }else{
              getTableData();
            }
          }else{
            getTableData();
          }
        }else{
          ElMessage({
            message: getProp(res,controlResult.value.messagePath),
            type: "error",
          });
        }
      });
    })
  };
  
  onMounted(()=>{
    if(tableOptions.autoQuery === false || tableOptions.waitingCallback){
      tableOptions.getTableData = getTableData;
    }else{
      getTableData();
    }
    
  });

  return {
    tableData,
    showModel,
    handleAdd,
    handleEdit,
    getTableData,
    editTableData,
    deleteTableData,
    pageChange,
    doFilter,
  };
}
