<template>
  <page-layout>
    <a-row :gutter="[5, 10]">
      <!-- 货位树 -->
      <a-col :span="5">
        <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="19">
        <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, selectedRows: state.selectedRows, onChange: onSelectChange }">
          </pro-table>
        </a-card>
      </a-col>
    </a-row>
    <save :visible="state.visibleSave" @close="closeSave" :record="selectedKeys"></save>
    <edit :visible="state.visibleEdit" @close="closeEdit" :record="state.recordEdit"></edit>
  </page-layout>
</template>

<script>
  import save from './modal/save';
  import edit from './modal/edit';
  import {
    message,
    modal
  } from 'ant-design-vue';
  import {
    ExclamationCircleOutlined,
    CarryOutOutlined
  } from '@ant-design/icons-vue';
  import {
    page,
    remove,
    removeBatch,
    wmsLocDict,
    generateLoc
  } from "@/api/wms/warehouse";
  import {
    reactive,
    createVNode,
    watch,
    ref,
    toRaw
  } from 'vue';

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

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

      const tableRef = ref();

      /// 列配置
      const columns = [{
          dataIndex: "treeCode",
          key: "treeCode",
          title: "父节点",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "code",
          key: "code",
          title: "当前节点",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "nodeDesc",
          key: "nodeDesc",
          title: "节点描述",
          showSearch:true,
          width: 150,
        },
        {
          dataIndex: "houseCode",
          key: "houseCode",
          title: "仓库号",
          width: 100,
        },
        {
          dataIndex: "houseName",
          key: "houseName",
          title: "仓库名称",
          width: 200,
        },
        {
          dataIndex: "houseType",
          key: "houseType",
          title: "仓库类型",
          width: 100,
          dictionary: {
            type: 'tag',
            code: 'WarehouseTypes'
          }
        },
        {
          dataIndex: "nodeType",
          key: "nodeType",
          title: "节点类型",
          showSearch:true,
          width: 120,
        },
        {
          dataIndex: "minRow",
          key: "minRow",
          title: "最小排",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "maxRow",
          key: "maxRow",
          title: "最大排",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "relationRow",
          key: "relationRow",
          title: "关联排",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "minColumn",
          key: "minColumn",
          title: "最小列",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "maxColumn",
          key: "maxColumn",
          title: "最大列",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "minLayer",
          key: "minLayer",
          title: "最小层",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "maxLayer",
          key: "maxLayer",
          title: "最大层",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "relationTrack",
          key: "relationTrack",
          title: "关联巷道",
          width: 100,
        },
        {
          dataIndex: "locDirection",
          key: "locDirection",
          title: "货位方向",
          width: 100,
        },
        {
          dataIndex: "currentRow",
          key: "currentRow",
          title: "当前排",
          showSearch:true,
          width: 100,
        },
        {
          dataIndex: "createBy",
          key: "createBy",
          title: "录入人",
          width: 120,
        },
        {
          dataIndex: "createTime",
          key: "createTime",
          title: "录入时间",
          width: 200,
        },
        {
          dataIndex: "updateBy",
          key: "updateBy",
          title: "修改人",
          width: 120,
        },
        {
          dataIndex: "updateTime",
          key: "updateTime",
          title: "修改时间",
          width: 200,
        },
        {
          dataIndex: "remark",
          key: "remark",
          title: "备注",
          width: 100,
        },
      ];

      /// 数据来源 [模拟]
      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 generateLocKey = "generateLoc";

      const generateLocMethod = (record) => {
        if (record.remark === 'OK') {
          message.error({
            content: "当前行已经生成过，无需重复操作",
            key: generateLocKey,
            duration: 1
          })
          return;
        }
        message.loading({
          content: '生成中...',
          key: generateLocKey
        });
        generateLoc(toRaw(record)).then((response) => {
          console.log("response", response)
          if (response.success) {
            message.success({
              content: "成功生成货位",
              key: generateLocKey,
              duration: 1
            })
            tableRef.value.reload()
          } else {
            message.error({
              content: response.msg,
              key: generateLocKey,
              duration: 1
            })
          }
        })
      };

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

      /// 行操作
      const operate = [{
          label: "修改",
          code: 'wms:locGenerator:edit',
          event: function(record) {
            state.visibleEdit = true, state.recordEdit = record
          }
        },
        {
          label: "删除",
          code: 'wms:locGenerator:delete',
          isDel: true,
          delEvent: function() {
            removeMethod()
          }
        },
        {
          label: "生成货位",
          code: 'wms:locGenerator:generate',
          event: function(record) {
            console.log("record", record)
            if (record.nodeType == null) {
              message.error("当前节点类型为null，无法生成货位")
            } else generateLocMethod(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: [],
        selectedRows: [],
        param: {},
        treeData: [],
        visibleSave: false,
        visibleEdit: false,
        recordEdit: {},
      })

      const searchParam = [{
          key: "houseCode",
          type: "input",
          label: "仓库号"
        },
        {
          key: "houseType",
          type: "select",
          label: "仓库类型",
          options: [{
            value: 'StackerWarehouse',
            text: '堆垛机库',
          }, {
            value: 'DenseWarehouse',
            text: '密集库',
          }, {
            value: 'HorizontalWarehouse',
            text: '平库',
          }, {
            value: 'Area',
            text: '区域',
          }]
        },
      ]

      //树相关
      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 getWmsLocDict = async () => {
        var response = await wmsLocDict();
        state.treeData = response.data.children;
        console.log("树节点数据", response.data.children)
      };
      //页面加载时自动调用加载树的方法
      getWmsLocDict();

      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 selectedCode = selectedKeys.value[0].split("_");
        console.log("selectedCode",selectedCode)
        let treeCode = selectedCode[0];
        let currentRow = null;
        if(selectedCode[1] === "0"){
          //堆垛机库 code的第二为位代表排
          currentRow = selectedCode[2];
          console.log("currentRow",currentRow)
        }else{
          //密集库：code的第3位代表层
          currentRow = selectedCode[1];
        }
        search({ //fetch改为search
          treeCode: treeCode,
          pageNum: 1,
          pageSize: 10
        })
      }

      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, selectedRows) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        console.log('selectedRows changed: ', selectedRows);
        state.selectedRowKeys = selectedRowKeys;
        state.selectedRows = selectedRows;
      };

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

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

        search,
        searchParam, // 查询参数

        closeSave,
        closeEdit,

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