<template>
  <a-list-layout>

    <a-tree showLine :tree-data="state.treeData" v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys"
      :replace-fields="replaceFields" @select="onSelect">
    </a-tree>

    <!-- 查询表单 -->
    <template #search>
      <pro-query :searchParam="searchParam" @on-search="search" ref='queryModalRef'></pro-query>
    </template>
    <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>

    <save :visible="state.visibleSave" @close="closeSave"></save>
    <edit :visible="state.visibleEdit" @close="closeEdit" :record="state.recordEdit"></edit>
    <changeLocStatus :visible="state.visibleChangeStatus" @close="closeChangeStatus" :record="state.selectedRowKeys">
    </changeLocStatus>
    <changeLocStoreStatus :visible="state.visibleChangeStoreStatus" @close="closeChangeStoreStatus"
      :record="state.selectedRowKeys"></changeLocStoreStatus>
  </a-list-layout>
</template>

<script>
import save from './modal/save.vue';
import edit from './modal/edit.vue';
import changeLocStatus from './modal/locStatusManage.vue';
import changeLocStoreStatus from './modal/locStoreStatusManage.vue';
import {
  message,
  Modal as modal
} from '@hwork/ant-design-vue';
import {
  ExclamationCircleOutlined,
  CarryOutOutlined
} from '@ant-design/icons-vue';
import {
  page,
  remove,
  removeBatch,
  wmsLocDict
} from "@/api/wms/loc";
import {
  reactive,
  createVNode,
  watch,
  ref
} from 'vue';

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

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

    const tableRef = ref();
    const queryModalRef = ref();

    /// 列配置
    const columns = [{
      dataIndex: "index",
      key: "index",
      title: "序号",
      width: 60,
      fixed: 'left',
      align: 'center'
    },
    {
      dataIndex: "locCode",
      key: "locCode",
      title: "位置编号",
      showSearch: true,
      width: 120
    },
    {
      dataIndex: "locName",
      key: "locName",
      title: "位置描述",
      showSearch: true,
      width: 220
    },
    {
      dataIndex: "houseCode",
      key: "houseCode",
      title: "仓库号",
      width: 100
    },
    {
      dataIndex: "houseName",
      key: "houseName",
      title: "仓库名称",
      width: 100
    },
    {
      dataIndex: "parentCode",
      key: "parentCode",
      title: "父编号",
      width: 100
    },
    {
      dataIndex: "locRelation",
      key: "locRelation",
      title: "关联位置",
      showSearch: true,
      width: 120
    },
    {
      dataIndex: "locWcs",
      key: "locWcs",
      title: "WCS位置编号",
      showSearch: true,
      width: 160
    },
    {
      dataIndex: "ext1",
      key: "ext1",
      title: "Mes工位号",
      showSearch: true,
      width: 140
    },
    {
      dataIndex: "locType",
      key: "locType",
      title: "位置类型",
      width: 100,
      dictionary: {
        type: 'tag',
        code: 'LocTypes'
      },
    },
    {
      dataIndex: "locHighType",
      key: "locHighType",
      title: "货位高矮类型",
      width: 120,
      dictionary: {
        type: 'tag',
        code: 'LocHighTypes'
      }
    },
    {
      dataIndex: "locSizeType",
      key: "locSizeType",
      title: "货位大小类型",
      width: 120,
      dictionary: {
        type: 'tag',
        code: 'LocSizeTypes'
      }
    },
    {
      dataIndex: "row",
      key: "row",
      title: "排",
      showSearch: true,
      width: 100,
    },
    {
      dataIndex: "col",
      key: "col",
      title: "列",
      showSearch: true,
      width: 100,
    },
    {
      dataIndex: "layer",
      key: "layer",
      title: "层",
      showSearch: true,
      width: 100,
    },
    {
      dataIndex: "trackCode",
      key: "trackCode",
      title: "巷道号",
      width: 100,
    },
    {
      dataIndex: "channelCode",
      key: "channelCode",
      title: "通道号",
      showSearch: true,
      width: 120,
    },
    {
      dataIndex: "area",
      key: "area",
      title: "位置分区",
      width: 100,
    },
    {
      dataIndex: "channelType",
      key: "channelType",
      title: "通道类型",
      showSearch: true,
      width: 120,
    },
    {
      dataIndex: "locStatus",
      key: "locStatus",
      title: "位置状态",
      width: 100,
      dictionary: {
        type: 'tag',
        code: 'LocStatus'
      }
    },
    {
      dataIndex: "storeStatus",
      key: "storeStatus",
      title: "存储状态",
      width: 100,
      dictionary: {
        type: 'tag',
        code: 'LocStoreStatus'
      }
    },
    {
      dataIndex: "priority",
      key: "priority",
      title: "优先级",
      width: 100,
      dictionary: {
        type: 'tag',
        code: 'priority'
      }
    },
    // {
    //   dataIndex: "note",
    //   key: "note",
    //   title: "备注"
    // },
    {
      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) => {
      console.log("fetch param", param)
      console.log("tableRef", tableRef)
      console.log("tableRef", tableRef.value.pagination)

      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:loc:add',
      icon: 'PlusOutlined', 
      event: function () {
        state.visibleSave = true
      }
    },
    {
      label: "删除",
      code: 'wms:loc:delete',
      event: function () {
        removeBatchMethod(state.selectedRowKeys)
      },
      icon: 'DeleteOutlined', 
      danger: true,
    },
    {
      label: "批量更改位置状态",
      code: 'wms:loc:change',
      icon: 'EditOutlined',
      event: function (record) {
        state.visibleChangeStatus = true, record = state.selectedRowKeys
        console.log("record", record)
      }
    },
    {
      label: "批量修更改存储状态",
      code: 'wms:loc:modify',
      icon: 'EditOutlined',
      event: function (record) {
        state.visibleChangeStoreStatus = true, record = state.selectedRowKeys
      }
    },
    ];

    /// 行操作
    const operate = [    {
      label: "删除",
      code: 'wms:loc:delete',
      isDel: true,
      delEvent: function (record) {
        removeMethod(record)
      }
    },{
      label: "修改",
      code: 'wms:loc:edit',
      event: function (record) {
        state.visibleEdit = true, state.recordEdit = 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,
      visibleChangeStatus: false,
      visibleChangeStoreStatus: false,
      recordEdit: {},
      recordChangeStatus: {},
      recordChangeStoreStatus: {},
    })

    const searchParam = reactive([{
      key: "locCode",
      type: "input",
      label: "位置编号",
    },
    {
      key: "locStatus",
      type: "select",
      label: "位置状态",
      options: [{
        value: 'Normal',
        text: '正常',
      }, {
        value: 'NoIn',
        text: '禁入',
      }, {
        value: 'NoOut',
        text: '禁出',
      }, {
        value: 'Freeze',
        text: '冻结',
      }]
    },
    {
      key: "storeStatus",
      type: "select",
      label: "存储状态",
      options: [{
        value: 'Free',
        text: '空闲',
      }, {
        value: 'Load',
        text: '载货',
      }, {
        value: 'DoIn',
        text: '预入',
      }, {
        value: 'DoOut',
        text: '预出',
      }, {
        value: 'Fault',
        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("onSelect queryModalRef", queryModalRef.value)
      console.log("onSelect queryModalRef", queryModalRef.value.formState)
      queryModalRef.value.setValue("locCode", "123");
      // 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 parentCode = selectedCode[0];
      if (selectedCode[2] === "0") {
        let row = selectedCode[1];
        console.log("row", row)
        search({ //fetch改为search
          parentCode: parentCode,
          row: row,
          pageNum: 1,
          pageSize: 20
        })
      } else {
        let layer = selectedCode[2];
        console.log("layer", layer)
        search({ //fetch改为search
          parentCode: parentCode,
          layer: layer,
          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 closeChangeStatus = function () {
      tableRef.value.reload();
      state.visibleChangeStatus = false
    }

    const closeChangeStoreStatus = function () {
      tableRef.value.reload();
      state.visibleChangeStoreStatus = false
    }

    const onSelectChange = (selectedRowKeys, selectedRows) => {
      state.selectedRowKeys = selectedRowKeys;
      state.selectedRows = selectedRows;
      console.log("selectedRows", selectedRows)
    };

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

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

      search,
      searchParam, // 查询参数

      closeSave,
      closeEdit,
      closeChangeStatus,
      closeChangeStoreStatus,

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