<template>
  <a-list-layout
    ref="pageRef"
  >
    <template #search>
      <pro-query :searchParam="searchParam" @on-search="search"></pro-query>
    </template>
    <!-- 关键字搜索 -->
    <pro-table 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>
  </a-list-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,
    taskSend,
    taskOver,
    taskCancel
  } from "@/api/wms/task";
  import {
    reactive,
    createVNode,
    ref,
    toRaw
  } from 'vue';

  const removeKey = "remove";
  const removeBatchKey = "removeBatch";
  const taskSendKey = "taskSend";
  const taskOverKey = "taskOver";
  const taskCancelKey = "taskCancel";

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

      const tableRef = ref();

      /// 列配置
      const columns = ref(
        [{
            dataIndex: "index",
            key: "index",
            title: "序号",
            width: 60,
            fixed: 'left',
            align: 'center'
          },
          {
            dataIndex: "houseCode",
            key: "houseCode",
            title: "仓库号",
            width: 120,
            showSearch: true,
            resizable: true,
          },
          {
            dataIndex: "taskCode",
            key: "taskCode",
            title: "任务号",
            width: 120,
            showSearch: true,
            sorter: (a, b) => a.taskCode - b.taskCode,
            resizable: true,
          },
          {
            dataIndex: "taskType",
            key: "taskType",
            title: "任务类型",
            width: 120,
            showSearch: true,
            dictionary: {
              type: 'tag',
              code: 'TaskTypes'
            }
          },
          {
            dataIndex: "palletCode",
            key: "palletCode",
            title: "托盘号",
            width: 120,
            showSearch: true,
            sorter: true,
          },
          {
            dataIndex: "ext1",
            key: "ext1",
            title: "MES要货令",
            width: 170,
            showSearch: true,
            sorter: true,
            ellipsis: true
          },
          {
            dataIndex: "ext2",
            key: "ext2",
            title: "AGV任务编号",
            width: 170,
            showSearch: true,
            sorter: true,
          },
          {
            dataIndex: "status",
            key: "status",
            title: "状态",
            width: 100,
            showSearch: true,
            dictionary: {
              type: 'tag',
              code: 'TaskStatus'
            },
          },
          {
            dataIndex: "sourceLoc",
            key: "sourceLoc",
            title: "起始地址",
            showSearch: true,
            width: 150,
          },
          {
            dataIndex: "targetLoc",
            key: "targetLoc",
            title: "目标位置",
            showSearch: true,
            width: 150,
          },
          {
            dataIndex: "groupCode",
            key: "groupCode",
            title: "任务组号",
            width: 130,
            showSearch: true
          },
          {
            dataIndex: "priority",
            key: "priority",
            title: "优先级",
            width: 80,
          },
          {
            dataIndex: "deliver",
            key: "deliver",
            title: "搬运类型",
            width: 100,
          },
          {
            dataIndex: "directFlag",
            key: "directFlag",
            title: "方向标志",
            width: 120,
            showSearch: true,
            dictionary: {
              type: 'tag',
              code: 'DirectFlag'
            }
          },
          {
            dataIndex: "skuCode",
            key: "skuCode",
            title: "物料编号",
            width: 150,
          },
          {
            dataIndex: "skuName",
            key: "skuName",
            title: "物料名称",
            width: 130,
          },
          {
            dataIndex: "sendType",
            key: "sendType",
            title: "任务发送类型",
            width: 120,
            dictionary: {
              type: 'tag',
              code: 'TaskSendType'
            }
          },
          {
            dataIndex: "palletType",
            key: "palletType",
            title: "托盘类型",
            width: 100,
          },
          {
            dataIndex: "sourceLocParent",
            key: "sourceLocParent",
            title: "起始地址父节点",
            width: 180,
            showSearch: true,
          },
          {
            dataIndex: "sourceLocWcs",
            key: "sourceLocWcs",
            title: "WCS起始地址",
            width: 150,
          },
          {
            dataIndex: "targetLoc",
            key: "targetLoc",
            title: "目标位置",
            width: 120,
          },
          {
            dataIndex: "targetLocParent",
            key: "targetLocParent",
            title: "目标位置父节点",
            width: 180,
            showSearch: true,
          },
          {
            dataIndex: "targetLocWcs",
            key: "targetLocWcs",
            title: "WCS目标地址",
            width: 170,
          },
          {
            dataIndex: "invoiceCode",
            key: "invoiceCode",
            title: "单据号",
            width: 180,
            showSearch: true,
          },
          {
            dataIndex: "invoiceItemCode",
            key: "invoiceItemCode",
            title: "单据明细号",
            width: 200,
            showSearch: true,
          },

          {
            dataIndex: "beginDate",
            key: "beginDate",
            title: "开始时间",
            width: 180,
          },
          {
            dataIndex: "finishDate",
            key: "finishDate",
            title: "完成时间",
            width: 180,
          },
          {
            dataIndex: "createBy",
            key: "createBy",
            title: "录入人",
            width: 120,
            showSearch: true,
          },
          {
            dataIndex: "createTime",
            key: "createTime",
            title: "录入时间",
            width: 200,
            showSearch: true,
            sorter: true,
          },
          {
            dataIndex: "updateBy",
            key: "updateBy",
            title: "修改人",
            width: 120,
            showSearch: true,
          },
          {
            dataIndex: "updateTime",
            key: "updateTime",
            title: "修改时间",
            width: 180,
            showSearch: true,
            sorter: true,
          },
          {
            dataIndex: "executeMessage",
            key: "executeMessage",
            title: "任务的执行消息",
            width: 350,
            showSearch: true,
          },
          {
            dataIndex: "remark",
            key: "remark",
            title: "备注",
            width: 200,
            ellipsis: true,
          },
        ]

      );

      /// 数据来源 [模拟]
      const fetch = async (param) => {
        var response = await page(param);
        console.log("task response", response)
        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: response.msg,
              key: removeKey,
              duration: 1
            })
            tableRef.value.reload()
          } else {
            message.error({
              content: response.msg,
              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: response.msg,
                  key: removeBatchKey,
                  duration: 1
                })
                tableRef.value.reload()
              } else {
                message.error({
                  content: response.msg,
                  key: removeBatchKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      // taskSend 任务下发
      const taskSendMethod = (e) => {
        if (state.selectedRows == undefined || state.selectedRows.length == 0) {
          message.error({
            content: "请先选择需要操作的任务信息",
            key: taskSendKey,
            duration: 1
          })
        } else if (state.selectedRows.length > 1) {
          message.error({
            content: "一次只能下发一条任务信息",
            key: taskSendKey,
            duration: 1,
          })
          return;
        }
        modal.confirm({
          title: '您是否确定下发?',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({
              content: "提交中...",
              key: taskSendKey
            });
            taskSend(toRaw(state.selectedRows[0])).then((response) => {
              if (response.success) {
                message.success({
                  content: response.msg,
                  key: taskSendKey,
                  duration: 1
                }).then(() => {
                  tableRef.value.reload()
                })
              } else {
                message.error({
                  content: response.msg,
                  key: taskSendKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      // taskOver 任务完成
      const taskOverMethod = (e) => {
        if (state.selectedRowKeys[0] == undefined || state.selectedRowKeys[0].length == 0) {
          message.error({
            content: "请先选择需要操作的任务信息",
            key: taskOverKey,
            duration: 1
          })
        } else if (state.selectedRows.length > 1) {
          message.error({
            content: "一次只能完成一条任务信息",
            key: taskOverKey,
            duration: 1,
          })
          return;
        }
        modal.confirm({
          title: '您是否确定完成?',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({
              content: "提交中...",
              key: taskOverKey
            });
            taskOver(toRaw(state.selectedRows[0])).then((response) => {
              if (response.success) {
                message.success({
                  content: response.msg,
                  key: taskOverKey,
                  duration: 1
                }).then(() => {
                  tableRef.value.reload()
                })
              } else {
                message.error({
                  content: response.msg,
                  key: taskOverKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      // taskCancel 任务取消
      const taskCancelMethod = (e) => {
        if (state.selectedRowKeys[0] == undefined || state.selectedRowKeys[0].length == 0) {
          message.error({
            content: "请先选择需要操作的任务信息",
            key: taskCancelKey,
            duration: 1
          })
        } else if (state.selectedRows.length > 1) {
          message.error({
            content: "一次只能取消一条任务信息",
            key: taskCancelKey,
            duration: 1,
          })
          return;
        }
        modal.confirm({
          title: '您是否确定取消?',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({
              content: "提交中...",
              key: taskCancelKey
            });
            taskCancel(toRaw(state.selectedRows[0])).then((response) => {
              if (response.success) {
                message.success({
                  content: response.msg,
                  key: taskCancelKey,
                  duration: 1
                }).then(() => {
                  tableRef.value.reload()
                })
              } else {
                message.error({
                  content: response.msg,
                  key: taskCancelKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      /// 工具栏
      const toolbar = [{
          label: "新增",
          code: "wms:task:add",
          icon: 'PlusOutlined',
          event: function() {
            state.visibleSave = true
          }
        },
        // {
        //   label: "删除",
        //   code: "wms:task:remove",
        //   event: function() {
        //     removeBatchMethod(state.selectedRowKeys)
        //   },
        //   type: 'danger'
        // },
        {
          label: "下发",
          code: "wms:task:taskSend",
          icon: 'SendOutlined',
          event: function() {
            taskSendMethod(state.selectedRowKeys[0])
          }
        },
        {
          label: "完成",
          code: "wms:task:taskOver",
          icon: 'CheckOutlined',
          event: function() {
            taskOverMethod(state.selectedRowKeys[0])
          }
        },
        {
          label: "取消",
          code: "wms:task:taskCancel",
          icon: 'StopOutlined',
          danger: true,
          event: function() {
            taskCancelMethod(state.selectedRowKeys[0])
          }
        },
      ];

      /// 行操作
    //   const operate = [{
    //     label: "删除",
    //     code: "wms:task:remove",
    //     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) // 改变每页条数时更新显示
      }

       const searchParam = [{
          key: "timeRange",
          type: "rangePicker",
          label: "时间范围"
        },{
          key: "invoiceCode",
          type: "input",
          label: "单据号"
        },
        {
          key: "palletCode",
          type: "input",
          label: "托盘号"
        },
        {
          key: "skuCode",
          type: "input",
          label: "物料号"
        },
        {
          key: "status",
          type: "select",
          label: "状态",
          options: [{
            value: 'New',
            text: '新建',
          }, {
            value: 'Doing',
            text: '执行中',
          }, {
            value: 'Doing_Picked',
            text: '已取货',
          }, {
            value: 'Cancel',
            text: '取消',
          }, {
            value: 'Over',
            text: '结束',
          }, {
            value: 'Error',
            text: '异常',
          }]
        },
        ]
      /// 外置参数 - 当参数改变时, 重新触发 fetch 函数
      const state = reactive({
        selectedRowKeys: [],
        selectedRows: {},
        param: {},
        visibleSave: false,
        visibleEdit: false,
        recordEdit: {},
      })

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

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

        search,
        searchParam,
        closeSave,
        closeEdit,

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