<template>
  <div>
    <a-col>
      <pro-query v-if="visible" :searchParam="searchParam" @on-search="search"></pro-query>
    </a-col>
    <pro-table style="margin-top: 10px;" v-if="visible" ref="tableChilrenRef" rowKey="id" :fetch="fetch"
      :columns="columns" :toolbar="toolbar" :operate="operate" :param="state.param" :pagination="pagination"
      :model="formState" @cancel="cancel"
      :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }">
    </pro-table>
    <a-empty v-else />
    <!--  <save :visible="state.visibleSave" @close="closeSave" :record="state.recordSave"></save> -->
    <addOutBillDetail :visible="state.visibleSave" @close="closeSave" :record="state.currentBill"></addOutBillDetail>
    <edit :visible="state.visibleEdit" @close="closeEdit" :record="state.recordEdit"></edit>
    <viewPick :visible="state.visibleInfo" @close="closeInfo" :record="state.recordInfo"></viewPick>
  </div>
</template>
<script>
  import addOutBillDetail from '../addOutBillDetail/addOutBillDetail.vue';
  import edit from './outBillDetail/edit.vue';
  import {
    message,
    Modal as modal
  } from '@hwork/ant-design-vue';
  import {
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import {
    page,
    remove,
    removeBatch,
    detailsAllot,
  } from "@/api/wms/outBillDetail";
  import viewPick from '../pick/pick.vue';
  import {
    reactive,
    createVNode,
    watch,
    ref,
    toRaw
  } from 'vue';



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

  export default {
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      record: {
        type: Object
      }
    },
    components: {
      addOutBillDetail,
      edit,
      viewPick,
    },

    setup(props) {

      const tableChilrenRef = ref()

      watch(props, (props) => {
        console.log("watch outBill", props.record)
        state.param.invoiceCode = props.record.invoiceCode;
        // state.outBill = props.record; //主表信息
        // console.log("子表watch" + JSON.stringify(props))
        // console.log("state.outBill" + JSON.stringify(state.outBill))
      })
      const tableRef = ref()

      const formState = reactive({
        invoiceCode: ''
      });

      const cancel = (e) => {};

      const columns = [{
        dataIndex: "index",
        key: "index",
        title: "序号",
        width: 60,
        fixed: 'left',
        align: 'center'
      },
      {
          dataIndex: "invoiceCode",
          key: "invoiceCode",
          title: "单据号",
          width: 200,
        },
        {
          dataIndex: "itemCode",
          key: "itemCode",
          title: "单据明细号",
          width: 200,
        },
        {
          dataIndex: "status",
          key: "status",
          title: "明细状态",
          width: 100,
          dictionary: {
            type: 'tag',
            code: 'outBillDetailStatus'
          },
        },
        {
          dataIndex: "skuCode",
          key: "skuCode",
          title: "SKU编号",
          width: 100,
        },
        {
          dataIndex: "skuName",
          key: "skuName",
          title: "SKU名称",
          width: 100,
        },
        {
          dataIndex: "skuType",
          key: "skuType",
          title: "SKU类别",
          width: 100,
        },

        {
          dataIndex: "batch",
          key: "batch",
          title: "批次",
          width: 100,
        },
        {
          dataIndex: "master",
          key: "master",
          title: "货主",
          width: 100,
        },
        {
          dataIndex: "producer",
          key: "producer",
          title: "厂家",
          width: 100,
        },
        {
          dataIndex: "customer",
          key: "customer",
          title: "客户",
          width: 100,
        },
        {
          dataIndex: "produceDate",
          key: "produceDate",
          title: "生产日期",
          width: 200,
        },
        {
          dataIndex: "overdue",
          key: "overdue",
          title: "到期日期",
          width: 200,
        },

        {
          dataIndex: "planQty",
          key: "planQty",
          title: "计划数量",
          width: 100,
        },
        {
          dataIndex: "lockQty",
          key: "lockQty",
          title: "已分配数量",
          width: 120,
        },
        {
          dataIndex: "actQty",
          key: "actQty",
          title: "实际出库数量",
          width: 120,
        },
        {
          dataIndex: "submitQty",
          key: "submitQty",
          title: "提交出库数量",
          width: 120,
        },
        {
          dataIndex: "convertPlanQty",
          key: "convertPlanQty",
          title: "换算计划数量",
          width: 120,
        },
        {
          dataIndex: "convertLockQty",
          key: "convertLockQty",
          title: "换算锁定数量",
          width: 120,
        },
        {
          dataIndex: "convertActQty",
          key: "convertActQty",
          title: "换算实际数量",
          width: 120,
        },
        {
          dataIndex: "baseUnit",
          key: "baseUnit",
          title: "物流单位",
          width: 100,
        },
        {
          dataIndex: "primaryUnit",
          key: "primaryUnit",
          title: "换算单位",
          width: 100,
        },
        {
          dataIndex: "spInv",
          key: "spInv",
          title: "特殊库存",
          width: 100,
          dictionary: {
            type: 'tag',
            code: 'spInv'
          },
        },
        {
          dataIndex: "invType",
          key: "invType",
          title: "库存类型",
          width: 100,
        },
        {
          dataIndex: "qualityStatus",
          key: "qualityStatus",
          title: "质量状态",
          width: 100,
          dictionary: {
            type: 'tag',
            code: 'qualityStatus'
          },
        },
        {
          dataIndex: "allotStatus",
          key: "allotStatus",
          title: "单据分配状态",
          width: 130,
        },
        {
          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("子表查询" + JSON.stringify(param))
        var response = await page(param);
        console.log("子表查询response" + JSON.stringify(response))
        return {
          total: response.data.total,
          data: response.data.record,
        };
      };

      /// 删除角色
      const removeMethod = (record) => {
        modal.confirm({
          title: '您是否确定要删除此数据?',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({
              content: "提交中...",
              key: removeKey
            });
            remove({
              "id": record.id
            }).then((response) => {
              if (response.success) {
                message.success({
                  content: "删除成功",
                  key: removeKey,
                  duration: 1
                }).then(() => {
                  tableChilrenRef.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
                }).then(() => {
                  tableChilrenRef.value.reload()
                })
              } else {
                message.error({
                  content: "删除失败",
                  key: removeBatchKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      // detailsAllot 分配单据
      const detailsAllotMethod = (ids) => {
        if (ids == undefined || ids.length == 0) {
          message.error({
            content: "请先选择需要操作的单据信息",
            key: detailsAllotKey,
            duration: 1
          })
          return;
        }
        modal.confirm({
          title: '您是否确认分配?',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({
              content: "提交中...",
              key: detailsAllotKey
            });
            detailsAllot(toRaw(ids)).then((response) => {
              if (response.success) {
                message.success({
                  content: "单据明细分配成功",
                  key: detailsAllotKey,
                  duration: 1
                }).then(() => {
                  tableRef.value.reload()
                })
              } else {
                message.error({
                  content: "单据明细分配失败",
                  key: detailsAllotKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      /// 工具栏props
      const toolbar = [{
          label: "新增",
          code: "wms:outBillDetail:add",
          event: function(record) {
            state.currentBill = props.record
            state.visibleSave = true
          }
        },
        {
          label: "删除",
          code: "wms:outBillDetail:add",
          event: function() {
            removeBatchMethod(state.selectedRowKeys)
          }
        },
        {
          label: "分配",
          code: "wms:outBillDetail:allot",
          event: function() {
            detailsAllotMethod(state.selectedRowKeys)
          }
        },
      ];

      /// 行操作
      const operate = [{
          label: "查看出库拣选",
          code: "wms:outBillDetail:look",
          event: function(record) {
            state.visibleInfo = true, state.recordInfo = record
          }
        },
        {
          label: "修改",
          code: "wms:outBillDetail:edit",
          event: function(record) {
            state.visibleEdit = true, state.recordEdit = record
          }
        },
        {
          label: "删除",
          code: "wms:outBillDetail:remove",
          event: 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 state = reactive({
        selectedRowKeys: [],
        param: {
          name: "",
          code: ""
        },
        visibleEdit: false,
        visibleSave: false,
        recordEdit: {},
        recordSave: {},
        currentBill: {},
      });

      const searchParam = [{
          key: "invoiceCode",
          type: "input",
          label: "单据号"
        }, {
          key: "itemCode",
          type: "input",
          label: "单据明细号"
        },
        {
          key: "status",
          type: "select",
          label: "明细状态",
          options: [{
              value: 'New',
              text: '新增',
            },
            {
              value: 'PartAssign',
              text: '部分分配',
            },
            {
              value: 'Assigned',
              text: '分配完成',
            }, {
              value: 'Doing',
              text: '执行中',
            },
            {
              value: 'Pause',
              text: '暂停',
            },
            {
              value: 'Cancel',
              text: '取消',
            },
            {
              value: 'Over',
              text: '执行完成',
            },
            {
              value: 'Closed',
              text: '关闭',
            },
          ]
        },
      ]
      const search = function(value) {
        state.param = value
        tableChilrenRef.value.reload()
      }

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

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

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

      const closeInfo = function() {
        console.log("关闭", state.visibleInfo)
        console.log("关闭state", state)
        state.visibleInfo = false
        tableChilrenRef.value.reload()
      }

      return {
        state,
        fetch,
        toolbar,
        columns,
        operate,
        pagination,
        onSelectChange,
        closeSave,
        closeEdit,
        closeInfo,
        search,
        searchParam,

        tableChilrenRef
      };
    },
  };
</script>
