<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 ref="extCode" label="外部单据号" name="extCode">
                      <a-input v-model:value="formState.extCode" placeholder="请输入外部单据号"
                        :disabled="!state.canEdite" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="6">
                    <a-form-item label="优先级" name="priority">
                      <a-select v-model:value="formState.priority" :options="outBillPriority" placeholder="请选择优先级"
                        :disabled="!state.canEdite">
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <!-- <a-col :span="6">
                    <a-form-item ref="businessType" label="业务类型" name="businessType">
                      <a-input v-model:value="formState.businessType" placeholder="请输入业务类型"
                        :disabled="!formState.canEdite" />
                    </a-form-item>
                  </a-col> -->
                  <!-- <a-col :span="6">
                    <a-form-item ref="deliver" label="搬运类型" name="deliver">
                      <a-select v-model:value="formState.deliver" show-search placeholder="请选择搬运类型"
                        :disabled="!formState.canEdite" style="width: 100%" :default-active-first-option="false"
                        :show-arrow="false" :filter-option="false" :not-found-content="null" :options="deliverRef.data"
                        @search="fetchDeliver" @change="deliverHandleChange">
                        <template v-if="deliverRef.fetching" #notFoundContent>
                          <a-spin size="small" />
                        </template>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row> -->
                  <a-col :span="6">
                    <a-form-item ref="businessType" label="业务类型" name="businessType">
                      <a-select v-model:value="formState.businessType" placeholder="请选择业务单据类型">
                        <a-select-option v-for="d in outOrderTypes" :key="d" :value="d.value">{{
                          d.label
                        }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="6">
                    <a-form-item ref="platform" label="卸货站台" name="platform">
                      <a-input v-model:value="formState.platform" placeholder="请输入卸货站台"
                        :disabled="!state.canEdite" />
                    </a-form-item>
                  </a-col>
                  <!-- <a-col :span="6">
                    <a-form-item ref="customer" label="客户" name="customer">
                      <a-input v-model:value="formState.formState.customer" placeholder="请输入客户"
                        :disabled="!formState.canEdite" />
                    </a-form-item>
                  </a-col> -->
                  <!-- <a-col :span="6">
                    <a-form-item label="单据状态" name="status">
                      <a-select v-model:value="formState.status" :options="outBillStatus" placeholder="请选择单据状态"
                        :disabled="!formState.canEdite">
                      </a-select>
                    </a-form-item>
                  </a-col> -->
                  <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 v-for="col in ['planQty', 'batch', 'master','customer', 'producer', 'qualityStatus']"
                    #[col]="{  record }" :key="col">
                    <div>
                      <template v-if="editableData[record.id]">
                        <template v-if="col==='customer'">
                          <a-select v-model:value="editableData[record.id][col]" show-search style="width: 130px"
                            :default-active-first-option="false" :show-arrow="false" :filter-option="false"
                            :not-found-content="null" :options="customerRef.data" @search="fetchCustomer"
                            @change="customerHandleChange">
                            <template v-if="customerRef.fetching" #notFoundContent>
                              <a-spin size="small" />
                            </template>
                          </a-select>
                        </template>
                        <template v-else-if="col==='master'">
                          <a-select v-model:value="editableData[record.id][col]" show-search style="width: 130px"
                            :default-active-first-option="false" :show-arrow="false" :filter-option="false"
                            :not-found-content="null" :options="masterRef.data" @search="fetchMaster"
                            @change="masterHandleChange">
                            <template v-if="masterRef.fetching" #notFoundContent>
                              <a-spin size="small" />
                            </template>
                          </a-select>
                        </template>
                        <template v-else-if="col==='producer'">
                          <a-select v-model:value="editableData[record.id][col]" show-search style="width: 130px"
                            :default-active-first-option="false" :show-arrow="false" :filter-option="false"
                            :not-found-content="null" :options="producerRef.data" @search="fetchProducer"
                            @change="producerHandleChange">
                            <template v-if="producerRef.fetching" #notFoundContent>
                              <a-spin size="small" />
                            </template>
                          </a-select>
                        </template>
                        <template v-else-if="col==='qualityStatus'">
                          <a-select v-model:value="editableData[record.id][col]" show-search style="width: 100px"
                            :options="qualityStatusRef" @focus="handleFocus" @blur="handleBlur"
                            @change="qualityStatusHandleChange">
                          </a-select>
                        </template>
                        <template v-else>
                          <a-input v-model:value="editableData[record.id][col]" style="margin: -5px 0" />
                        </template>
                      </template>
                      <template v-else>
                        {{record[col] }}
                      </template>
                    </div>
                  </template>
                  <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>
                      </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 :open="state.visibleSave" @close="closeSave" @addMaterial="addMaterial" :record="state.recordSave">
        </save>
        <edit :open="state.visibleEdit" @close="closeEdit" :record="state.recordEdit"></edit>
      </div>
    </a-form>
  </a-modal>
</template>
<script>
  import save from './modal/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,
    removeBatch,
    inBillSkuPage
  } from "@/api/wms/sku";
  import {
    createOutBill
  } from "@/api/wms/outBill";
  import {
    createOutBillDetails
  } from "@/api/wms/outBillDetail";
  import {
    getCustomerListByCode,
  } from "@/api/wms/customer";
  import {
    getDeliverTypeListByCode,
  } from "@/api/wms/deliverType";
  import {
    list
  } from "@/api/module/dictData";


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


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

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

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

      const formRef = ref(

      );
      //存放入库当局类型
      const outOrderTypes = ref();
      //获取入库单业务类型
      list({
        code: "outOrderTypes"
      }).then((response) => {
        outOrderTypes.value = response.data;
      });

      const formState = reactive({
          details: [],
          extCode: "",
          businessType: "",
          priority: "",
          deliver: "",
          platform: "",
          customer: "",
          status: "",
          invoiceCode: "",

      });

      watch(props, (props) => {
        console.log("addOutBill666", props)
        console.log("主表", props.record)
        if (props.record !== undefined && props.record.invoiceCode !== undefined) {
          console.log("主表传值了", props.record)
          //主表数据赋初始值
          formState.businessType = props.record.businessType;
          formState.extCode = props.record.extCode;
          formState.priority = props.record.priority;
          formState.invoiceCode = props.record.invoiceCode;
          formState.deliver = props.record.deliver;
          formState.platform = props.record.platform;
          formState.status = props.record.status;
          state.canEdite = false;
          console.log("赋值后监听", formState)
        } else {
          //主表数据设置为不可编辑
          formState.extCode = "";
          formState.businessType = "";
          formState.priority = "";
          formState.invoiceCode = "";
          formState.deliver = "";
          formState.platform = "";
          formState.status = "";
          state.canEdite = true;
        }
      })

      const columns = [{
        dataIndex: "index",
        key: "index",
        title: "序号",
        width: 60,
        fixed: 'left',
        align: 'center'
      },
      {
          dataIndex: "skuCode",
          key: "skuCode",
          type: "select",
          title: "SKU编号",
          width: 150,
          defaultSortOrder: 'ascend',
          sorter: (a, b) => a.skuCode - b.skuCode,
        },
        {
          dataIndex: "skuName",
          key: "skuName",
          title: "SKU名称",
          width: 100,
        },

        {
          dataIndex: "categoryName",
          key: "categoryName",
          title: "种类名称",
          width: 100,
        },
        {
          dataIndex: "baseUnit",
          key: "baseUnit",
          title: "库存单位",
          width: 100,
        },
        {
          dataIndex: "primaryUnit",
          key: "primaryUnit",
          title: "换算单位",
          width: 100,
        },
        {
          dataIndex: "rate",
          key: "rate",
          title: "换算率",
          type: "number",
          width: 100,
          defaultSortOrder: 'ascend',
          sorter: (a, b) => a.rate - b.rate,
        },
        {
          dataIndex: "stackType",
          key: "stackType",
          title: "垛形",
          type: "number",
          width: 100,
        },

        {
          dataIndex: "expire",
          key: "expire",
          title: "有效期",
          width: 100,
          defaultSortOrder: 'ascend',
          sorter: (a, b) => a.expire - b.expire,
        },
        {
          dataIndex: "planQty",
          key: "planQty",
          title: "计划数量",
          width: 120,
          slots: {
            customRender: 'planQty',
          },
        },
        {
          dataIndex: "batch",
          key: "batch",
          title: "批次",
          width: 120,
          slots: {
            customRender: 'batch',
          },
        },
        {
          dataIndex: "master",
          key: "master",
          title: "货主",
          width: 160,
          slots: {
            customRender: 'master',
          },
        },
        {
          dataIndex: "customer",
          key: "customer",
          title: "客户",

          width: 160,
          slots: {
            customRender: 'customer',
          },
        },
        {
          dataIndex: "producer",
          key: "producer",

          title: "厂商",
          width: 160,
          slots: {
            customRender: 'producer',
          },
        },
        {
          dataIndex: "qualityStatus",
          key: "qualityStatus",
          title: "质量状态",
          width: 120,
          slots: {
            customRender: 'qualityStatus',
          },
          dictionary: {
            type: 'tag',
            code: 'qualityStatus'
          },
        },
        {
          dataIndex: 'operation',
          title: '操作',
          width: 120,
          slots: {
            customRender: 'operation',
          },
          fixed: "right",
        },
      ];

      const qualityStatusHandleChange = qualityStatus => {
        console.log(`selected ${qualityStatus}`);
      };

      const customerHandleChange = val => {
        console.log("customerHandleChange", val);
        customerRef.value.value = val;
      };

      const masterHandleChange = val => {
        console.log("masterHandleChange", val);

        masterRef.value.value = val;
      };
      const producerHandleChange = val => {
        console.log("producerHandleChange", val);
        producerRef.value.value = val;
      };

      const deliverHandleChange = val => {
        console.log("deliverHandleChange", val);
        deliverRef.value.value = val;
      };

      const outBillPriority = ref([{
          value: '2',
          label: '高',
        }, {
          value: '1',
          label: '中',
        },
        {
          value: '0',
          label: '低',
        }
      ]);

      const qualityStatusRef = ref([{
          value: 'Q',
          label: '合格',
        },
        {
          value: 'N',
          label: '不合格',
        },
        {
          value: 'W',
          label: '待检',
        },
        {
          value: 'E',
          label: '免检',
        },
        {
          value: 'T',
          label: '试验料',
        },
        {
          value: 'S',
          label: '待确定',
        },
        {
          value: 'C',
          label: '待验',
        },
        {
          value: 'D',
          label: '冻结',
        },
      ]);

      const customerRef = ref({
        data: [],
        value: "",
        fetching: false
      });
      const masterRef = ref({
        data: [],
        value: "",
        fetching: false
      });
      const producerRef = ref({
        data: [],
        value: "",
        fetching: false
      });
      const deliverRef = ref({
        data: [],
        value: "",
        fetching: false
      });

      //根据输入项进行筛选质量标志
      const filterOption = (input, option) => {
        return option.qualityStatus.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      };

      const fetchCustomer = debounce(value => {
        console.log('fetching customer', value);
        lastFetchId += 1;
        const fetchId = lastFetchId;
        console.log("customerRef.value", customerRef.value)
        customerRef.value.data = [];
        customerRef.value.fetching = true;
        getCustomerListByCode({
          "customerCode": value
        }).then(
          response => {
            console.log("response", response)
            if (response.success === true && response.data.length > 0) {
              if (fetchId !== lastFetchId) {
                return;
              }
              let data = response.data.map(customer => ({
                label: `${customer.customerCode}-${customer.customerName}`,
                value: customer.customerCode,
              }));

              customerRef.value.data = data;
              customerRef.value.fetching = false;
            } else {
              //失败，弹窗提示没找到
              message.error({
                content: "没有找到相关数据"
              })
            }
            console.log("customerRef.value.data", customerRef.value.data)
          }
        )
      }, 300);

      const fetchMaster = debounce(value => {
        console.log('fetching master', value);
        lastFetchId += 1;
        const fetchId = lastFetchId;
        console.log("masterRef.value", masterRef.value)
        masterRef.value.data = [];
        masterRef.value.fetching = true;
        getCustomerListByCode({
          "customerCode": value
        }).then(
          response => {
            console.log("response", response)
            if (response.success === true && response.data.length > 0) {
              if (fetchId !== lastFetchId) {
                return;
              }
              let data = response.data.map(master => ({
                label: `${master.customerCode}-${master.customerName}`,
                value: master.customerCode,
              }));

              masterRef.value.data = data;
              masterRef.value.fetching = false;
            } else {
              //失败，弹窗提示没找到
              message.error({
                content: "没有找到相关数据"
              })
            }
            console.log("masterRef.value.data", masterRef.value.data)
          }
        )
      }, 300);

      const fetchProducer = debounce(value => {
        console.log('fetching producer', value);
        lastFetchId += 1;
        const fetchId = lastFetchId;
        producerRef.value.data = [];
        producerRef.value.fetching = true;
        getCustomerListByCode({
          "customerCode": value
        }).then(
          response => {
            console.log("response", response)
            if (response.success === true && response.data.length > 0) {
              if (fetchId !== lastFetchId) {
                return;
              }
              let data = response.data.map(customer => ({
                label: `${customer.customerCode}-${customer.customerName}`,
                value: customer.customerCode,
              }));
              producerRef.value.data = data;
              producerRef.value.fetching = false;
            } else {
              //失败，弹窗提示没找到
              message.error({
                content: "没有找到相关数据"
              })
            }

          }
        )
      }, 300);

      const fetchDeliver = debounce(value => {
        console.log('fetching deliver', value);
        lastFetchId += 1;
        const fetchId = lastFetchId;
        console.log("deliverRef.value", deliverRef.value)
        deliverRef.value.data = [];
        deliverRef.value.fetching = true;
        getDeliverTypeListByCode({
          "categoryCode": value
        }).then(
          response => {
            console.log("response", response)
            if (response.success === true && response.data.length > 0) {
              if (fetchId !== lastFetchId) {
                return;
              }
              let data = response.data.map(deliverType => ({
                label: `${deliverType.deliver}`,
                value: deliverType.deliver,
              }));

              deliverRef.value.data = data;
              deliverRef.value.fetching = false;
            } else {
              //失败，弹窗提示没找到
              message.error({
                content: "没有找到相关数据"
              })
            }
            console.log("deliverRef.value.data", deliverRef.value.data)
          }
        )
      }, 300);

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



      const editableData = reactive({});

      const edit = key => {
        console.log("edit")
        console.log("key", key)
        console.log(tableRef)
        console.log(JSON.stringify(tableRef))
        console.log(tableRef.value.dataSource.value)
        console.log(tableRef.value.dataSource)
        var a = tableRef.value.datasource.filter(item => key === item.id)[0];
        console.log(a)
        editableData[key] = cloneDeep(tableRef.value.datasource.filter(item => key === item.id)[0]);
        //触发客户信息下拉值的加载

      };

      const saveEdit = key => {
        console.log("key", key)
        var a = tableRef.value.datasource.filter(item => key === item.id)[0];
        console.log("找到需要编辑的数据", a)
        console.log("编辑后的数据", editableData[key])
        Object.assign(tableRef.value.datasource.filter(item => key === item.id)[0], editableData[key]);
        delete editableData[key];

      };

      const cancelEdit = key => {
        Object.assign(tableRef.value.datasource.filter(item => key === item.id)[0], editableData[key]);
        delete editableData[key];

      };


      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 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.extCode = "";
        formState.businessType = "";
        formState.priority = "";
        formState.deliver = "";
        formState.platform = "";
        formState.customer = "";
        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)
          let oldData = state.param.data.filter(item => item.id === newItem.id)[0];
          console.log("当前", newItem)
          if (oldData === undefined) {
            console.log("当前oldData", oldData)
            state.param.data.push(newItem)
          }
        })
        state.param.total = state.param.data.length;
        fetch(state.param)
      }
      //删除
      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 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(() => {
                  tableRef.value.reload()
                })
              } else {
                message.error({
                  content: "删除失败",
                  key: removeBatchKey,
                  duration: 1
                })
              }
            })
          }
        });
      }

      // 工具栏
      const toolbar = [{

          label: "选择物料",
          event: function() {
            state.visibleSave = true, state.recordSave = props.record
          }
        },
        // {
        //   label: "删除",
        //   event: function() {
        //     removeBatchMethod(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选中的行数据
        canEdite: false,
        param: {
          skuCode: "",
          skuName: "",
          barCode: "",
          abc: "",
          categoryCode: "",
          categoryName: "",
          baseUnit: "",
          primaryNuit: "",
          rete: "0",
          stackType: "0",
          stockHeight: "0",
          stockLow: "0",
          fullQty: "",
          expire: "0",
          planQty: "0",
          batch: "0",
          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 = {
        extCode: [{
          required: true,
          message: '请输入外部单据号',
          trigger: 'blur'
        }, ],
        businessType: [{
          required: true,
          message: '请输入业务类型',
          trigger: 'blur'
        }, ],
        priority: [{
          required: true,
          message: '请输入单据优先级',
          trigger: 'blur'
        }, ],
        deliver: [{
          required: true,
          message: '请输入搬运类型',
          trigger: 'blur'
        }, ],
        platform: [{
          required: true,
          message: '请输入卸货站台',
          trigger: 'blur'
        }, ],
        customer: [{
          required: true,
          message: '请输入客户名称',
          trigger: 'blur'
        }, ],
        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.details = state.param.data
        console.log("formState.details", formState.details)
        // let a = toRaw(formState);
        // let JsonString = JSON.stringify(formState);
        // console.log("formState 之后", a)
        // console.log("aJsonString 之后", a)
        formRef.value
        .validate()
        .then(() => {
            message.loading({
              content: '提交中...',
              key: save
            });
            console.log("state.canEdite", state.canEdite)
            if (state.canEdite) {
              //单据和主表一起新增 方法1
              createOutBill(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 {
              //只新增明细 方法2
              createOutBillDetails(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,
        outBillStatus,
        outBillPriority,
        editableData,
        edit,
        saveEdit,
        cancelEdit,
        deleteAdd,
        filterOption,
        qualityStatusRef,
        qualityStatusHandleChange,

        customerRef, //从后端获取的customer信息
        fetchCustomer,
        customerHandleChange,
        masterRef,
        masterHandleChange,
        fetchMaster,
        producerRef,
        producerHandleChange,
        fetchProducer,
        addMaterial,
        deliverRef,
        deliverHandleChange,
        fetchDeliver,
        outOrderTypes,
        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> */
