<template>
  <div>
    <a-col>
      <pro-query v-if="visible" :searchParam="searchParam" @on-search="search"></pro-query>
    </a-col>
    <pro-table 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> -->
    <addCheckDetail :visible="state.visibleSave" @close="closeSave"  @save="createCheckDetailsMethod" :record="state.currentCheck"></addCheckDetail>
    <edit :visible="state.visibleEdit" @close="closeEdit" :record="state.recordEdit"></edit>
    <viewPick :visible="state.visibleInfo" @close="closeInfo" :record="state.recordInfo"></viewPick>
  </div>
</template>
<script>
  import addCheckDetail from '../addCheckDetail/addCheckDetail.vue';
  // import save from './checkDetail/save.vue';
  import edit from './checkDetail/edit.vue';
  import {
    message,
    Modal as modal
  } from '@hwork/ant-design-vue';
  import {
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import {
    page,
    remove,
    removeBatch,
    createCheckBill,
    createCheckDetails
  } from "@/api/wms/checkDetail";

  import viewPick from '../checkPlt/checkPlt.vue';
  import {
    reactive,
    createVNode,
    watch,
    ref,
    toRaw,
  } from 'vue';


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


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

    setup(props) {

      watch(props, (props) => {
        console.log("watch props",props)
        console.log("watch112222",props.record.invoiceCode)
        state.param.invoiceCode = props.record.invoiceCode;
        // formState.invoiceCode = props.record.invoiceCode
        // state.check = props.record; //主表信息
        // console.log("子表watch" + JSON.stringify(props))
        // console.log("state.check" + JSON.stringify(state.check))

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

      const cancel = (e) => {
        // formRef.value.resetFields();
        // context.emit("close", false);
      };

      const checkStatus = ref([{
          value: 'New',
          label: '新增',
        },
        {
          value: 'Doing',
          label: '执行中',
        },
        {
          value: 'Pause',
          label: '暂停',
        },
        {
          value: 'Cancel',
          label: '取消',
        },
        {
          value: 'Over',
          label: '执行完成',
        },
        {
          value: 'Closed',
          label: '关闭',
        },
      ]);


      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: "skuCode",
          key: "skuCode",
          title: "物料编号",
          width: 100,
        },
        {
          dataIndex: "skuName",
          key: "skuName",
          title: "物料描述",
          width: 200,
        },
        {
          dataIndex: "batch",
          key: "batch",
          title: "批次号",
          width: 100,
        },
        {
          dataIndex: "spInv",
          key: "spInv",
          title: "特殊库存",
          width: 100,
        },
        {
          dataIndex: "invType",
          key: "invType",
          title: "库存类型",
          width: 100,
        },

        {
          dataIndex: "skuQty",
          key: "skuQty",
          title: "物料数量",
          width: 100,
        },
        // {
        //   dataIndex: "actQty",
        //   key: "actQty",
        //   title: "实际数量",
        //   width: 100,
        // },
        {
          dataIndex: "baseUnit",
          key: "baseUnit",
          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
                })
              }
            })
          }
        });
      }

      const createCheckDetailsMethod = (record) => {
        createCheckDetails(toRaw(formState)).then((response) => {
          if (response.success) {
            message.success({
              content: '保存成功',
              key: addCheckDetail,
              duration: 1
            }).then(() => {
              cancel();
            });
          } else {
            message.error({
              content: response.msg,
              key: addCheckDetail,
              duration: 1
            }).then(() => {
              // cancel();
            });
          }
        });
      }



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

      /// 行操作
      const operate = [{
          label: "查看盘点托盘",
          code: "wms:checkDetail:look",
          event: function(record) {
            state.visibleInfo = true, state.recordInfo = record
          }
        },
        {
          label: "修改",
          code: "wms:checkDetail:edit",
          event: function(record) {
            state.visibleEdit = true, state.recordEdit = record
          }
        },
        {
          label: "删除",
          code: "wms:checkDetail: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: {},
        visibleEdit: false,
        visibleSave: false,
        recordEdit: {},
        recordSave: {},
        currentCheck: {},
      });

      const searchParam = [{
          key: "invoiceCode",
          type: "input",
          label: "单据号"
        },
        {},
      ]
      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,
        cancel,
        fetch,
        checkStatus,
        formState,
        toolbar,
        columns,
        operate,
        pagination,
        onSelectChange,
        closeSave,
        closeEdit,
        closeInfo,
        search,
        searchParam,

        tableChilrenRef
      };
    },
  };
</script>
