<template>
  <div class="manual-classify">
    <h2>手册分类</h2>
    <InputSearch
      v-model:value="searchValue"
      placeholder="请输入搜索内容"
      enter-button
      @search="handleSearch"
    />
    <div class="classify-toolbar">
      <Button type="primary" size="small" shape="circle" ghost @click="addClassify">
        <PlusOutlined />
      </Button>
      <template v-if="selectedKeys && selectedKeys.length > 0">
        <Button type="primary" size="small" shape="circle" ghost @click="editClassify">
          <EditOutlined />
        </Button>
        <Button size="small" shape="circle" ghost danger @click="deleteClassify">
          <DeleteOutlined />
        </Button>
      </template>
    </div>
    <div class="classify-tree">
      <Tree
        v-model:selectedKeys="selectedKeys"
        :tree-data="treeData"
        @select="selectClassify"
        :fieldNames="{
          title: 'name',
          key: 'id',
        }"
      />
    </div>

    <Modal v-model:visible="visible" :title="modalTitle" @ok="handleOk">
      <Form>
        <FormItem label="" v-bind="validateInfos.name">
          <Input v-model:value="modelRef.name" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script lang="ts">
import { createVNode, PropType, toRefs } from "vue";
import { defineComponent, ref, reactive, onMounted, toRaw } from 'vue';
import { Button, Divider, Input, InputSearch, Tree, Modal, Form, FormItem, message } from 'ant-design-vue';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import type { TreeProps } from 'ant-design-vue';
import { getManualClassifyListApi, addManualClassifyApi, editManualClassifyApi, deleteManualClassifyApi } from '@/apis/manual';
import { listToTree } from "@/utils";

export default defineComponent({
  name: 'manual-classify',
  components: { Button, Divider, Input, InputSearch, Tree, Modal, Form, FormItem, PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined },
  emits: ['change'],
  setup(_, { emit }) {
    const router = useRouter();
    const searchValue = ref<string>('');
    const listData = ref<any>([]);
    const treeData = ref<TreeProps['treeData']>([]);
    const selectedKeys = ref<number[]>([]);
    const modalTitle = ref('');
    const visible = ref<boolean>(false);
    let modelRef = reactive({
      id: undefined,
      name: '',
      pid: 0
    });
    const rulesRef = reactive({
      name: [{required: true, message: '请输入分类名称'}]
    });
    const { resetFields, validate, validateInfos } = Form.useForm(modelRef, rulesRef, {
      onValidate: (...args) => console.log(...args),
    });

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

    const getManualClassifyList = async () => {
      const data = await getManualClassifyListApi();
      listData.value = data;
      treeData.value = listToTree(data);
    };

    const handleSearch = (value: string) => {
      const data = toRaw(listData.value).filter((item: any) => {
        return item.name.toLowerCase().indexOf(value.toLowerCase()) >= 0;
      });
      treeData.value = listToTree(data);
    };

    const addClassify = () => {
      modalTitle.value = '新增分类';
      const data = {
        id: undefined,
        name: '',
        pid: 0
      };
      resetFields();
      modelRef = Object.assign(modelRef, data);
      visible.value = true; 
    };

    const editClassify = () => {
      const data = listData.value.find((item: any) => {
        return selectedKeys.value[0] === item.id;
      });
      resetFields();
      modelRef = Object.assign(modelRef, {...data});
      modalTitle.value = '修改分类';
      visible.value = true;
    };
    
    const deleteClassify = () => {
      Modal.confirm({
        title: '确定删除当前手册分类吗？',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          const data = listData.value.find((item: any) => {
            return selectedKeys.value[0] === item.id;
          });
          await deleteManualClassifyApi(data.id);
          message.success('手册分类删除成功');
          selectedKeys.value = [];
          selectClassify([]);
          getManualClassifyList();
        },
      });
    };

    const handleOk = () => {
      validate()
        .then(async () => {
          const params = { ...modelRef }
          if (!params.id) {
            params.pid = selectedKeys.value && selectedKeys.value[0] ? selectedKeys.value[0] : 0
            await addManualClassifyApi(params);
            message.success('手册分类创建成功');
          } else {
            await editManualClassifyApi(params);
            message.success('手册分类修改成功');
          }
          getManualClassifyList();
          visible.value = false;
        })
        .catch(err => {
          console.log('error', err);
        });
    };

    const selectClassify = (keys: any) => {
      emit('change', keys[0]);
    };

    return { 
      searchValue,
      treeData,
      selectedKeys,
      modalTitle,
      visible,
      validateInfos,
      resetFields,
      modelRef,
      handleSearch,
      addClassify,
      editClassify,
      deleteClassify,
      selectClassify,
      handleOk
    };
  }
});
</script>
<style lang="less" scoped>
  .manual-classify {
    width: 240px;
    .classify-toolbar {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      padding: 10px 0;
      border-bottom: 1px solid #d8d8d8;
      button {
        margin-left: 10px;
      }
    }
    .classify-tree {
      width: 100%;
      height: calc(100vh - 176px);
      padding:  10px 0;
      overflow: auto;
      /deep/ .ant-tree {
        .ant-tree-treenode {
          width: 100%;
          .ant-tree-node-content-wrapper {
            flex: 1;
            white-space: nowrap;
          }
        }
      }
    }
  }
</style>
