<template>
  <div class="mainContentBox">
    <avue-crud
        ref="crudRef"
        v-model:search="search"
        v-model="form"
        :data="data"
        :option="option"
        v-model:page="page"
        @row-save="createRow"
        @row-update="updateRow"
        @row-del="deleteRow"
        @search-change="searchChange"
        @search-reset="resetChange"
        @size-change="dataList"
        @current-change="dataList"
        @selection-change="selectionChange"
    >
      <template #menu-left="{ size }">
        <el-button
            type="primary"
            icon="el-icon-plus"
            :size="size"
            @click="showDialog"
        >新增</el-button>
      </template>
      <template #menu="{ row, index }">
        <el-button text
                   type="info"
                   v-if="row.state === 1"
                   :icon="'el-icon-info'"
                   @click="showDialog(2,row.returnCode)">
          详情
        </el-button>
        <el-button text
                   type="primary"
                   v-if="row.state === 0"
                   :icon="'el-icon-info'"
                   @click="sendToWms(row.returnCode)">
          发送WMS
        </el-button>
        <el-button text
                   type="primary"
                   v-if="row.state === 0"
                   :icon="'el-icon-edit'"
                   @click="showDialog(1,row.returnCode)">
          编辑
        </el-button>
        <el-button text
                   type="danger"
                   v-if="row.state === 0"
                   :icon="'el-icon-del'"
                   @click="rowDelObj(row)">
          删除
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="950px"
        @close="dialog.visible = false"
    >
      <el-input
          v-if="dialog.type !== 2"
          placeholder="扫码回车添加"
          v-model="scanInput"
          @keyup.enter="searchCode"
          clearable>
      </el-input>
      <avue-crud :data="materialData" :option="materialOption" @selection-change="crudSelect">
        <template #menu="{ row, index }">
          <el-button text
                     v-if="dialog.type !== 2"
                     type="danger"
                     :icon="'el-icon-del'"
                     @click="avueRowDel(row, index)">
           删除
          </el-button>
        </template>
      </avue-crud>
      <template #footer>
        <div class="dialog-footer" v-if="dialog.type !== 2">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="dialog.visible=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import {addReturnMaterial,scanItem,queryList,del,sendWms} from "@/api/returnMaterial";
import { useCommonStoreHook } from "@/store";
import {ElMessage} from "element-plus";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const loading = ref(false); //  加载状态
const dialog = reactive({
  title: "物料选择",
  type: 0,
  visible: false,
});
const sendToWms = (returnCode) => {
  ElMessageBox.confirm("确定要发送记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false,
  }).then(() => {
    sendWms({returnCode: returnCode}).then((res)=>{
      ElMessage.success("操作成功");
      dataList()
    })
  });
};
const showDialog = (type,returnCode) => {
  currentCode.value = ''
  dialog.visible = true
  if(type){
    dialog.type = type
  }
  materialData.value = []
  if(type === 1 || type == 2){
    currentCode.value = returnCode
    queryList({"returnCode": returnCode}).then((res)=>{
      if(type === 1){
        res.data.forEach(item=>{
          item.$cellEdit = true
        })
      }else{
        res.data.forEach(item=>{
          item.$cellEdit = false
        })
      }
      materialData.value = res.data
    })
  }
};
const currentCode = ref()
const handleSubmit = () => {
  if(materialData.value.length === 0 ){
    ElMessage.error("请先扫码添加物料");
    return
  }
  addReturnMaterial(materialData.value).then(()=>{
    dialog.visible = false
    dataList();
    ElMessage.success("操作成功");
  })
};
const avueRowDel = (row,index) =>{
  materialData.value.splice(index,1)
}
const rowDelObj = (row) =>{
  ElMessageBox.confirm("确定要删除记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false,
  }).then(() => {
    del({returnCode: row.returnCode}).then((res)=>{
      ElMessage.success("操作成功");
      dataList()
    })
  });
}
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
    useCrud({
      src: "/api/v1/ReturnDetails",
    });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } = Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const crud = ref(null)
const crudSelect = (row) => {
  alert(JSON.stringify(JSON.stringify(row)))
}
const searchCode = ()=>{
  let params = {"code": scanInput.value}
  let exists = false;
  if(materialData.value){
    materialData.value.forEach(item=>{
      if(item.batchCode == scanInput.value){
        exists = true;
      }
    })
  }
  if(exists){
    scanInput.value = ''
    return;
  }
  scanItem(params).then((data)=>{
    if(data.data){
      let obj = data.data;
      materialData.value.push(
          {"returnCode":currentCode.value,"materialCode": obj.materialCode,"materialName": obj.materialName,"batchCode" : scanInput.value,"num": 1,'materialModel': obj.spec,$cellEdit: true}
      )
      scanInput.value = ''
    }
  })
}

const scanInput = ref()
const materialData = ref([

]);
const materialOption = ref({
  addBtn: false,
  saveBtn: false,
  cancelBtn: false,
  cellBtn: true,
  editBtn: false,
  delBtn: false,
  column: [
    { label: '物料编码', prop: 'materialCode', fixed: true },
    { label: '物料名称', prop: 'materialName' },
    { label: '物料型号', prop: 'materialModel',},
    { label: '二维码', prop: 'batchCode' },
    { label: '退回数量', prop: 'num' ,cell: true,
      rules: [
        { required: true, trigger: 'blur' }
      ]
    },
  ]
});
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: false,
  addBtn: false,
  viewBtn: false,
  editBtn: false,
  selection: false,
  column: [
    {
      label: "退料单号",
      prop: "returnCode",
      overHidden: true,
    },
    {
      label: "发送WMS",
      type: 'select',
      dicData: [{"label": "未发送","value": 0},{"label": "已发送","value": 1}],
      prop: "state",
      addDisplay: false,
      editDisplay: false,
    },
    {
      label: "创建时间",
      prop: "created",
      overHidden: true,
      display: false,
      type: "datetime",
      valueFormat: "yyyy-MM-dd HH:mm:ss",
    },
    {
      label: "创建人",
      prop: "creator",
      display: false,
      overHidden: true,
    },
  ],
});

onMounted(() => {
  // console.log("crudRef", crudRef)
  dataList();
});
</script>
