<template>
  <CustomCard>
    <div>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-tree
            style="max-width: 600px"
            :data="treeData"
            node-key="id"
            :default-expanded-keys="[selectTreeNode.id]"
            :props="{ value: 'id' }"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <template #default="{ data }">
              <div class="tree_node_" :class="{ nodeActive: data.id == selectTreeNode.id || data.id == selectTreeNode.pId }">
                {{ data.label }}
              </div>
            </template>
          </el-tree>
        </el-col>
        <el-col :span="20">
          <avue-crud
            ref="crudRef"
            v-model="state.form"
            v-model:search="state.query"
            v-model:page="state.pageData"
            :table-loading="state.loading"
            :data="state.data"
            :option="state.options"
            @refresh-change="refreshChange"
            @search-reset="searchChange"
            @search-change="searchChange"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            @row-del="rowDel"
            @row-save="rowSave"
            @row-update="rowUpdate"
          >
            <template #menu-left>
              <el-button type="primary" icon="Plus" @click="onAdd">新增</el-button>
              <el-button type="success" icon="download" @click="onExport">导出</el-button>
            </template>

            <template #menu="scope">
              <custom-table-operate :actions="state.options.actions" :data="scope" />
            </template>
          </avue-crud>
        </el-col>
      </el-row>
    </div>
  </CustomCard>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import CustomCard from '@/components/CustomCard.vue';
import { getLandTypeTree, landTypeSave, getLandType, exportLandType, delLandType, editLandType } from '@/apis/baseInfo';
import { ElMessage } from 'element-plus';

const { VITE_APP_BASE_API } = import.meta.env;
const app = useApp();

/* --------------- data --------------- */
// #region
const selectTreeNode = ref({
  id: '',
  label: '',
  pId: '',
  pName: '',
  level: 0,
});
const landTypesDic = ref([]);
const crudRef = ref(null);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '',
    addBtn: false,
    dialogWidth: 680,
    selection: false,
    refreshBtn: false,
    column: [
      { label: '编号', prop: 'id', addDisplay: false, editDisplay: false },
      {
        label: '用地分类',
        prop: 'landType',
        dicData: landTypesDic,
        // type: 'select',
        multiple: true,
        span: 23,
        props: {
          value: 'id',
          label: 'childLandCategory',
        },
        rules: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
          },
        ],
        render: ({ row }) => {
          return row.landType;
        },
      },
      {
        label: '土地类别',
        prop: 'landCategory',
        addDisplay: false,
        rules: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
          },
        ],
        render: ({ row }) => {
          return row.landCategory;
        },
      },
      {
        label: '状态',
        prop: 'status',
        render: ({ row }) => {
          return row.status == '1' ? '启用' : '禁用';
        },
        addDisplay: false,
        editDisplay: false,
      },
    ],
    actions: [
      {
        name: ({ row }) => `${row.status == '0' ? '启' : '禁'}用`,
        icon: 'edit',
        event: ({ row }) => rowStatus(row),
      },
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});

const treeData = ref([]);

// #endregion

/* --------------- methods --------------- */
const loadData = () => {
  state.loading = true;
  getLandType({
    pid: selectTreeNode.value.id,
    ...state.query,
  })
    .then((res) => {
      if (res.code === 200) {
        const { current, size, total, records } = res.data;
        state.data = records;
        state.pageData = {
          currentPage: current || 1,
          pageSize: size || 10,
          total: total,
        };
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
      state.data = [];
    })
    .finally(() => {
      state.loading = false;
    });
};

onMounted(() => {
  getLandTree();
});

async function getLandTree() {
  let res = await getLandTypeTree();
  if (res.code == 200) {
    treeData.value = newTree(res.data, 0);
    landTypesDic.value = res.data.map((v) => {
      return {
        id: v.id,
        label: v.prentLandType,
      };
    });
    console.log('treeData', treeData.value);
  }
}
function newTree(arr, i) {
  arr.forEach((v) => {
    if (i == 0) {
      v.label = v.prentLandType;
    } else {
      v.label = v.childLandCategory;
    }
    if (v.children) v.children = newTree(v.children, i + 1);
  });
  return arr;
}
// 页数
const currentChange = (current) => {
  state.query.current = current;
  loadData();
};

// 条数
const sizeChange = (size) => {
  state.query.current = 1;
  state.query.size = size;
  loadData();
};

// 搜索
const searchChange = (params, done) => {
  if (done) done();
  state.query = params;
  state.query.current = 1;
  loadData();
};

// 刷新
const refreshChange = () => {
  loadData();
  app.$message.success('刷新成功');
};

// 选择
const selectionChange = (rows) => {
  state.selection = rows;
};

const handleNodeClick = (data, node) => {
  const { id } = data;
  if (selectTreeNode.value.id != id) {
    if (node.level < 2) {
      selectTreeNode.value = handleNodeData({ data, level: node.level });
    } else selectTreeNode.value = handleNodeData({ data: node.parent.data, level: node.level });
    loadData();
  } else {
    selectTreeNode.value = { id: '', label: '', level: 0 };
    state.data = [];
  }
  if (selectTreeNode.value.level < 1) {
    state.options.dialogWidth = 680;
    state.options.column[1].span = 23;
    state.options.column[2].addDisplay = false;
    delete state.options.column[1].addDisabled;
    delete state.options.column[1].value;
  } else {
    state.options.column[2].addDisplay = true;
    state.options.column[1].addDisabled = true;
    state.options.column[1].value = selectTreeNode.value.label;
    delete state.options.dialogWidth;
    delete state.options.column[1].type;
    delete state.options.column[1].span;
  }
};
function handleNodeData({ data, level }) {
  return {
    id: data.id,
    label: data.label,
    level,
  };
}
// 编辑状态
async function rowStatus(row) {
  console.info('操作状态', row.$index);
  const { id } = row;
  let status = row.status == '1' ? '0' : '1';
  let params = {
    id,
    status,
  };
  let res = await editLandType(params);
  if (res.code == 200) {
    ElMessage.success('操作成功');
    nextTick(() => {
      state.data[row.$index].status = status;
      loadData();
    });
  }
}

async function rowDel(row, done, loading) {
  let res = await delLandType(row.id);
  if (res.code === 200) {
    app.$message.success('已删除！');
    loadData();
    done();
  }
  loading();
}

const rowEdit = (row) => {
  crudRef.value && crudRef.value.rowEdit(row);
};

const onAdd = () => {
  crudRef.value && crudRef.value.rowAdd();
};
async function onExport() {
  console.log('test ---');
  if (selectTreeNode.value.level < 1) return ElMessage.warning('请选择用地分类');
  let res = await exportLandType({
    pid: selectTreeNode.value.id,
  });
  console.log('edxport', res);
  if (res.status == 200) {
    let a = document.createElement('a');
    let blob = new Blob([res.data]);
    let link = window.URL.createObjectURL(blob);
    a.href = link;
    a.download = '用地分类.xlsx';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(link);
  }
}
const rowSave = async (val, done, loading) => {
  console.info('新增', val);
  let data = {};
  if (selectTreeNode.value.level < 1) {
    data.landType = val.landType;
  } else {
    data = {
      pid: selectTreeNode.value.id,
      landCategory: val.landCategory,
    };
  }
  let res = await landTypeSave(data);
  if (res.code == 200) {
    ElMessage.success('创建成功');
    getLandTree();
    if (selectTreeNode.value.level > 0) loadData();
    done();
  }
  // saveOperationRecord(row)
  //   .then((res) => {
  //     if (res.code === 200) {
  //       app.$message.success('添加成功！');
  //       done();
  //       loadData();
  //     }
  //   })
  //   .catch((err) => {
  //     app.$message.error(err.msg);
  //   })
  //   .finally(() => {
  //     loading();
  //   });
  loading();
};

const rowUpdate = (row, index, done, loading) => {
  console.info('更新');
  console.log('row', row);
  editLandType({
    id: row.id,
    landCategory: row.landCategory,
  }).then((res) => {
    if (res.code === 200) {
      app.$message.success('更新成功！');
      loadData();
      done();
    }
  });
  loading();
};

// #endregion
</script>

<style lang="scss" scoped>
.tree_node_ {
  padding: 0 6px;
  display: flex;
  align-items: center;
  height: calc(100% - 4px);
  border-radius: 2px;
  user-select: none;
}
.nodeActive {
  background-color: rgb(172, 223, 243);
}
::v-deep() {
  .is-current {
    .el-tree-node__content {
      background-color: rgba($color: #000000, $alpha: 0);
    }
  }
  .el-tree-node__content {
    &:hover {
      background-color: rgba($color: #000000, $alpha: 0);
    }
  }
}
</style>
