<template>
  <a-modal :open="visible" title="创建盘点单" cancelText="取消" okText="提交" @ok="submit" @cancel="cancel" :width='2000'
    wrapClassName="full-modal">
    <a-form ref="formRef" :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <div>
        <page-layout>
          <a-row :gutter="[0, 0]">
            <a-col :span="24">
              <a-card>
                <a-row>
                  <a-col :span="6">
                    <a-form-item label="单据状态" name="status">
                      <a-select v-model:value="formState.status" :options="checkStatus" placeholder="请选择单据状态"  :disabled="!formState.canEdite" >
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="10">
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="6"></a-col>
                </a-row>
              </a-card>
              <a-card>
                <!-- <pro-query :searchParam="searchParam" @on-search="search"></pro-query> -->
                <pro-table  visible="visible" ref="tableRef" rowKey="id" :fetch="fetch"
                  :columns="columns" :operate="operate" :toolbar="toolbar" :param="state.param" :pagination="pagination"
                  :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }">

                  <template #operation="{ record }">
                    <div class="editable-row-operations">
                      <span v-if="editableData[record.id]">
                        <!--  <a @click="saveEdit(record.id)">保存</a>
                        <a-popconfirm title="取消编辑?" @confirm="cancelEdit(record.id)">
                          <a>取消编辑</a>
                        </a-popconfirm> -->
                        <a-popconfirm title="是否删除选中的行?" @confirm="deleteAdd(record.id)">
                          <a>删除</a>
                        </a-popconfirm>
                      </span>
                      <span v-else>
                        <!-- <a @click="edit(record.id)">编辑</a> -->
                        <a-popconfirm title="是否删除选中的行?" @confirm="deleteAdd(record.id)">
                          <a>删除</a>
                        </a-popconfirm>
                      </span>
                    </div>
                  </template>
                </pro-table>
              </a-card>
            </a-col>
          </a-row>
        </page-layout>
        <save :visible="state.visibleSave" @close="closeSave" @addMaterial="addMaterial" :record="state.recordSave">
        </save>
        <edit :visible="state.visibleEdit" @close="closeEdit" :record="state.recordEdit"></edit>
      </div>
    </a-form>
  </a-modal>
</template>
<script>
  import save from './model/save.vue';
  import {
    message,
    Modal as modal,
  } from '@hwork/ant-design-vue';
  import {
    CheckOutlined,
    EditOutlined
  } from '@ant-design/icons-vue';

  import {
    debounce,
    cloneDeep,
  } from 'lodash-es';

  import {
    computed,
    defineComponent,
    reactive,
    ref,
    toRaw,
    watch,
    createVNode
  } from "vue";

  import {
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';

  import {
    remove,
    removeactQty,
    page
  } from "@/api/wms/palletDetail";
  import {
    createCheckBill
  } from "@/api/wms/check";
  import {
    createCheckDetails
  } from "@/api/wms/checkDetail";
  const removeKey = "remove";
  const removeactQtyKey = "removeactQty";


  export default defineComponent({
    props: {
      visible: {
        type: Boolean,

      },
      record: {
        type: Object,
      }
    },
    components: {
      save,
    },

    emit: ["close","createCheckDetailsMethod"],
    setup(props, context) {
      const tableRef = ref()

      const formRef = ref(

      );

      const formState = reactive({
       canEdite: false,
      });



      watch(props, (props) => {
        console.log("主表", props.record)
        console.log("watch11111", props)
        if (props.record !== undefined && props.record.invoiceCode !== undefined) {
          //主表数据赋初始值并且设置为不可编辑
          formState.status = props.record.status;
          formState.invoiceCode = props.record.invoiceCode
          console.log("formState.status", formState.status)
          // console.log("canEditcanEdit", canEdit.value)
         formState.canEdite = false;
        }
        else {
          // 主表数据赋初始值空并且设置为可编辑
         // formState.status = props.record.status;
          formState.status = "";
          formState.canEdite = true;
        }
      })



      const columns = [{
        dataIndex: "index",
        key: "index",
        title: "序号",
        width: 60,
        fixed: 'left',
        align: 'center'
      },
      {
          dataIndex: "skuCode",
          key: "skuCode",
          title: "物料编号",
          width: 100,
        },
        {
          dataIndex: "skuName",
          key: "skuName",
          title: "物料名称",
          width: 100,
        },
        {
          dataIndex: "batch",
          key: "batch",
          title: "批次号",
          width: 100,
        },
        {
          dataIndex: "spInv",
          key: "spInv",
          title: "特殊库存",
          width: 100,
          dictionary: {
            type: 'tag',
            code: 'spInv'
          },
        },
        {
          dataIndex: "invType",
          key: "invType",
          title: "库存类型",
          width: 100,
        },
        {
          dataIndex: "skuQty",
          key: "skuQty",
          title: "物料数量",
          width: 100,
        },
        {
          dataIndex: "baseUnit",
          key: "baseUnit",
          title: "物流单位",
          width: 100,
        },
        {
          dataIndex: 'operation',
          title: '操作',
          width: 120,
          slots: {
            customRender: 'operation',
          },
          fixed: "right",
        },
      ];





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



      const editableData = reactive({});



      /// 数据来源 [模拟]
      const fetch = async (param) => {
        // console.log("数据来源 [模拟]", param)
        // var response = await inBillSkuPage(param);
        // return {
        //   total: response.data.total,
        //   data: response.data.record,
        // };

        //var response = await inBillSkuPage(param);
        return {
          total: param.total,
          data: param.data,
        };
      };

      const cancel = (e) => {
        formState.details = []
        formState.status = "";
        console.log("addMaterial cancel", e)
        // formRef.value.resetFields();
        context.emit("close", false);
      };

      /// 数据来源 [模拟]
      const addMaterial = function(e) {
        console.log("addMaterial", e)
        console.log("materials", e)
        let submitArray = [...e]
        // var oldArray = [...state.param.data];
        console.log("submitArray", submitArray)
        submitArray.forEach(newItem => {
          console.log("当前", newItem)
          console.log("当前 state.param.data", state.param.data)
          let oldData = state.param.data.filter(item => item.id === newItem.id)[0];
          if (oldData === undefined) {
            console.log("当前oldData", oldData)
            state.param.data.push(newItem)
          }
        })
        state.param.total = state.param.data.length;
        fetch(state.param)
      }

      const deleteAdd = key => {
        console.log("KEY", key)
        console.log("tableRef.value.datasource", tableRef.value.datasource)
        const itemToRemove = tableRef.value.datasource.filter(item => key === item.id)[0];
        console.log("A", key)

        if (itemToRemove) {
          tableRef.value.datasource.splice(itemToRemove, 1);
          updateTableData();
        }
      };

      const updateTableData = () => {
        // Update tableRef.value.datasource with the latest data
      };

      const fetchData = () => {
        // Fetch the latest data and update the state
      };


      //删除
      const removeMethod = (id) => {
        modal.confirm({
          title: '您是否确定要删除此条数据?',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({
              content: "提交中...",
              key: removeKey
            });
            remove({
              "id": id
            }).then((response) => {
              if (response.success) {
                message.success({
                  content: "删除成功",
                  key: removeKey,
                  duration: 1
                }).then(() => {
                  tableRef.value.reload()
                })
              } else {
                message.error({
                  content: response.msg,
                  key: removeKey,
                  duration: 1
                })
              }
            })
          }
        });
      }



      //批量删除
      const removeactQtyMethod = (ids) => {
        modal.confirm({
          title: '您是否确定要删除选择数据?',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({
              content: "提交中...",
              key: removeactQtyKey
            });
            removeactQty({
              "ids": ids
            }).then((response) => {
              if (response.success) {
                message.success({
                  content: "删除成功",
                  key: removeactQtyKey,
                  duration: 1
                }).then(() => {
                  tableRef.value.reload()
                })
              } else {
                message.error({
                  content: "删除失败",
                  key: removeactQtyKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      // 工具栏
      const toolbar = [{
          label: "选择托盘",
          event: function() {
            state.visibleSave = true, state.recordSave = props.record
          }
        },
        {
          label: "删除",
          event: function() {
            removeactQtyMethod(state.selectedRowKeys)
          }
        },
        {
          label: "重置",
          event: function() {
            state.param.data = [];
            state.param.total = 0;
            fetch(state.param)
          }
        },
      ];

      const pagination = {
        pageNum: 1,
        pageSize: 20,
        showSizeChanger: true, // 显示可改变每页条数
        pageSizeOptions: ["5", "10", "50", "100", "200"], // 每页条数选项设置
        showTotal: total => `共 ${total} 条记录`, // 显示总条数
        showSizeChange: (current, pageSize) => (this.pageSize = pageSize) // 改变每页条数时更新显示
      };

      let lastFetchId = 0;

      const state = reactive({
        selectedRowKeys: [], //table选中的行主键
        selectedRows: [], //table选中的行数据
        param: {
          data: [],
        },
        value: [],
        fetching: false,


        // addMaterial,
        visibleEdit: false,
        visibleSave: false,
        recordEdit: {},
        recordSave: {},

      });

      /* const searchParam = [{
        key: "skuCode",
        type: "input",
        label: "物料编号"
      }, ]
 */
      const search = function(value) {
        console.log("主表查询" + JSON.stringify(value))
        console.log(value)
        state.param = value
        //tableRef.value.reload()
      }

      const formRules = {
        status: [{
          required: true,
          message: '请输入单据状态',
          trigger: 'blur'
        }, ],
      };

      // const editKey = "add";
      const submit = (e) => {
        console.log("提交", e)
        console.log("提交formState", formState)
        //对table中的数据进行校验
        // console.log("formState.formState", formState.formState)
        formState.details = state.param.data
        console.log("formState.details", formState.details)
        formRef.value
        .validate()
        .then(() => {
            message.loading({
              content: '提交中...',
              key: save
            });
            // console.log("formState.canEdite", formState.canEdite)
            // if (formState.canEdite) {
            //   console.log("1")
            //单据和主表一起新增 方法1
            createCheckBill(toRaw(formState)).then((response) => {
              if (response.success) {
                message.success({
                  content: '保存成功',
                  key: save,
                  duration: 1
                }).then(() => {
                  cancel();
                });
              } else {
                message.error({
                  content: response.msg,
                  key: save,
                  duration: 1
                }).then(() => {
                  // cancel();
                });
              }
            })
            // }
            // else(canEdit.value){ //只新增明细 方法2
            //   console.log("2", createCheckDetails)
            //   createCheckDetails(toRaw(formState)).then((response) => {
            //     if (response.success) {
            //       message.success({
            //         content: '保存成功',
            //         key: save,
            //         duration: 1
            //       }).then(() => {
            //         cancel();
            //       });
            //     } else {
            //       message.error({
            //         content: response.msg,
            //         key: save,
            //         duration: 1
            //       }).then(() => {
            //         //cancel();
            //       });
            //     }
            //   });
            // }
          })
          .catch(error => {
            console.log('error', error);
          });
      };

      const onSelectChange = (selectedRowKeys, selectedRows) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        console.log('selectedRows changed: ', selectedRows);
        state.selectedRowKeys = selectedRowKeys;
      };
      const closeSave = function() {
        state.visibleSave = false
        tableRef.value.reload()
      }

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


      const closeInfo = function() {
        state.visibleInfo = false
        tableRef.value.reload()
      }

      return {


        submit,
        cancel,
        formRef,
        formState,
        formRules,
        state,
        fetch,
        toolbar,
        columns,
        pagination,
        onSelectChange,
        search,
        closeSave,
        closeEdit,
        tableRef,
        // searchParam,
        checkStatus,
        editableData,
        // edit,
        // saveEdit,
        // cancelEdit,
        deleteAdd,
        //filterOption,
        // qualityFlagRef,
        // qualityFlagHandleChange,

        // customerRef, //从后端获取的customer信息
        //fetchCustomer,
        // customerHandleChange,
        // masterRef,
        // masterHandleChange,
        //fetchMaster,
        // producerRef,
        // producerHandleChange,
        addMaterial,







        labelCol: {
          span: 8,

        },
        wrapperCol: {
          span: 12,
        },
      };
    },

  });
</script>
<style scoped>
  .full-modal {
    .ant-modal {
      max-width: 80%;
      max-height: 70%;
      box-align: center;
      /* top: 0; */
      /* padding-bottom: 0; */
      /* margin: 0; */
    }

    .ant-modal-content {
      display: flex;
      flex-direction: column;
      height: calc(89vh);
    }

    .ant-modal-body {
      flex: 1;
    }
  }

  .editable-row-operations a {
    margin-right: 8px;
  }
</style> */
