<template>
  <page-layout>
    <a-row :gutter="[5, 10]">
      <!-- 树 htxia 2023-09-20 参考“货位管理”界面-->
      <a-col :span="4">
        <a-card>
          <a-tree showLine :tree-data="state.treeData" v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys" :replace-fields="replaceFields" @select="onSelect">
          </a-tree>
        </a-card>
      </a-col>
      <!--下拉值列表 -->
      <a-col :span="20">
        <a-card>
          <!-- 查询表单 -->
          <pro-query :searchParam="searchParam" @on-search="search"></pro-query>
          <pro-table style="margin-top: 10px;" ref="tableRef" :fetch="fetch" :columns="columns" :toolbar="toolbar"
            :operate="operate" :param="state.param" :pagination="pagination"
            :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }">
          </pro-table>
        </a-card>
      </a-col>
    </a-row>
    <save :visible="state.visibleSave" @close="closeSave"></save>
    <edit :visible="state.visibleEdit" @close="closeEdit" :record="state.recordEdit"></edit>
    <!-- <info :visible="state.visibleInfo" @close="closeInfo" :record="state.recordInfo"></info> -->
  </page-layout>
</template>

<script>
  import save from './modal/save.vue';
  import edit from './modal/edit.vue';
  import {
    message,
    Modal as modal
  } from '@hwork/ant-design-vue';
  import {
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import {
    page,
    remove,
    removeBatch,
    wmsListDict //树相关
  } from "@/api/wms/list";
  import {
    reactive,
    createVNode,
    watch, //树相关
    ref
  } from 'vue';

  const removeKey = "remove";
  const removeBatchKey = "removeBatch";

  export default {
    components: {
      save,
      edit,
    },
    setup() {

      const tableRef = ref();

      /// 列配置
      const columns = [{
        dataIndex: "index",
        key: "index",
        title: "序号",
        width: 60,
        fixed: 'left',
        align: 'center'
      },
      {
          dataIndex: "item",
          key: "item",
          title: "列表项",
          showSearch:true,
          width: 150
        },
        /* {
                  dataIndex: "itemParent",
                  key: "itemParent",
                  title: "列表项的父节点",
                  width: 150
                }, */
        {
          dataIndex: "listId",
          key: "listId",
          title: "编号",
          showSearch:true,
          width: 150
        },
        {
          dataIndex: "listDesc",
          key: "listDesc",
          title: "名称",
          showSearch:true,
          width: 200
        },
        // {
        //   dataIndex: "ext1",
        //   key: "ext1",
        //   title: "扩展1"
        // },
        // {
        //   dataIndex: "ext2",
        //   key: "ext2",
        //   title: "扩展2"
        // },
        // {
        //   dataIndex: "ext3",
        //   key: "ext3",
        //   title: "扩展3"
        // },
        // {
        //   dataIndex: "ext4",
        //   key: "ext4",
        //   title: "扩展4"
        // },
        // {
        //   dataIndex: "ext5",
        //   key: "ext5",
        //   title: "扩展5"
        // },
        /* {
          dataIndex: "deleted",
          key: "deleted",
          title: "是否允许删除",
          dictionary: {
            type: 'tag',
            code: 'deleted'
          }
        }, */
        {
          dataIndex: "createBy",
          key: "createBy",
          title: "录入人",
          width: 150
        },
        {
          dataIndex: "createTime",
          key: "createTime",
          title: "录入时间",
          width: 200,
        },
        {
          dataIndex: "updateBy",
          key: "updateBy",
          title: "修改人",
          width: 150,
        },
        {
          dataIndex: "updateTime",
          key: "updateTime",
          title: "修改时间",
          width: 200,
        },
        {
          dataIndex: "remark",
          key: "remark",
          title: "备注",
          width: 150,
        },
      ];

      /// 数据来源 [模拟]
      const fetch = async (param) => {
        var response = await page(param);
        return {
          total: response.data.total,
          data: response.data.record,
        };
      };

      /// 删除配置
      const removeMethod = (record) => {
        message.loading({
          content: "提交中...",
          key: removeKey
        });
        remove({
          "id": record.id
        }).then((response) => {
          if (response.success) {
            message.success({
              content: "删除成功",
              key: removeKey,
              duration: 1
            })
            tableRef.value.reload()
          } else {
            message.error({
              content: "删除失败",
              key: removeKey,
              duration: 1
            })
          }
        })
      }

      const removeBatchMethod = (ids) => {
        modal.confirm({
          title: '您是否确定删除该数据?',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({
              content: "提交中...",
              key: removeBatchKey
            });
            removeBatch({
              "ids": ids
            }).then((response) => {
              if (response.success) {
                message.success({
                  content: "删除成功",
                  key: removeBatchKey,
                  duration: 1
                })
                tableRef.value.reload()
              } else {
                message.error({
                  content: "删除失败",
                  key: removeBatchKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      /// 工具栏
      const toolbar = [{
          label: "新增",
          code: 'wms:list:add',
          event: function() {
            state.visibleSave = true
          }
        },
        {
          label: "删除",
          code: 'wms:list:remove',
          event: function() {
            removeBatchMethod(state.selectedRowKeys)
          },
          type: 'danger'
        },
      ];

      /// 行操作
      const operate = [{
          label: "修改",
          code: 'wms:list:edit',
          event: function(record) {
            state.visibleEdit = true, state.recordEdit = record
          }
        },
        {
          label: "删除",
          code: 'wms:list:delete',
          isDel: true,
          delEvent: function(record) {
            removeMethod(record)
          }
        },
      ];

      /// 分页参数
      const pagination = {
        pageNum: 1,
        pageSize: 20,
        showSizeChanger: true, // 显示可改变每页条数
        pageSizeOptions: ["10", "20", "50", "100"], // 每页条数选项设置
        showTotal: total => `共 ${total} 条记录`, // 显示总条数
        showSizeChange: (current, pageSize) => (this.pageSize = pageSize) // 改变每页条数时更新显示
      }

      /// 外置参数 - 当参数改变时, 重新触发 fetch 函数
      const state = reactive({
        selectedRowKeys: [],
        param: {},
        visibleSave: false,
        visibleEdit: false,
        recordEdit: {},
        recordInfo: {},
      })

      //界面头部-查询框
      const searchParam = [
        /* {
                  key: "itemParent",
                  type: "input",
                  label: "列表项的父节点"
                },
                {
                  key: "item",
                  type: "input",
                  label: "列表项"
                },
                {
                  key: "listId",
                  type: "input",
                  label: "编号"
                }, */
        {
          key: "listDesc",
          type: "input",
          label: "名称"
        },
      ]

      //树相关
      const expandedKeys = ref([]);
      const selectedKeys = ref([]);
      const replaceFields = {
        // children: 'children',
        title: 'name',
      };

      watch(expandedKeys, () => {
        console.log('expandedKeys', expandedKeys);
      });
      watch(selectedKeys, () => {
        console.log('selectedKeys', selectedKeys);
      });

      //给树节点赋值
      const getWmsListDict = async () => {
        var response = await wmsListDict();
        state.treeData = response.data.children;
        console.log("树节点数据", response.data.children)
      };
      //页面加载时自动调用加载树的方法
      getWmsListDict();

      const onSelect = function(value) {
        // console.log('selected', selectedKeys, info);
        //触发表单查询事件
        // console.log("onSelect", selectedKeys)
        console.log("节点触击事件", value)
        // console.log("onSelect", selectedKeys.value)
        // console.log("onSelect", selectedKeys.value[0])
        if (selectedKeys.value.length == 0) return; //如果没有值被选中，就跳出当前方法，不做任何操作
        let item = selectedKeys.value[0]
        if (item === 'list') {
          search({
            pageNum: 1,
            pageSize: 20
          })
        } else {
          search({ //fetch改为search
            item: item,
            pageNum: 1,
            pageSize: 20
          })
        }
      }

      const search = function(value) {
        state.param = value
      }

      const closeSave = function() {
        tableRef.value.reload();
        state.visibleSave = false
      }

      const closeEdit = function() {
        tableRef.value.reload();
        state.visibleEdit = false
      }

      const onSelectChange = selectedRowKeys => {
        state.selectedRowKeys = selectedRowKeys;
      };

      return {
        state, // 状态共享
        fetch, // 数据回调
        toolbar, // 工具栏
        columns, // 列配置
        operate, // 行操作
        pagination, // 分页配置

        //树相关
        onSelect,
        expandedKeys,
        selectedKeys,
        replaceFields,


        search,
        searchParam, // 查询参数

        closeSave,
        closeEdit,

        onSelectChange,
        tableRef
      };
    },
  };
</script>
