<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      v-model:page="page"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!-- <template #leCode="{ row }">{{ row.stLend.leCode }}</template> -->
      <!-- <template #goodsCode="{ row }">{{ row.stLend.stRealtimeStock.coGoods.goodsCode }}</template>
            <template #goodsName="{ row }">{{ row.stLend.stRealtimeStock.coGoods.goodsName }}</template>
            <template #piNo="{ row }">{{ row.stLend.stRealtimeStock.piNo }}</template>
            <template #shName="{ row }">{{ row.stLend.stRealtimeStock.coStorehouse.shName }}</template>
            <template #location="{ row }">{{ row.stLend.stRealtimeStock.storageLocation.location }}</template>
            <template #quantity="{ row }">{{ row.stLend.quantity }}</template>
            <template #returnQty="{ row }">{{ row.stLend.returnQty }}</template>
            <template #unitName="{ row }">{{ row.stLend.stRealtimeStock.coGoods.unitName }}</template>
            <template #leDate="{ row }">{{ row.stLend.leDate }}</template>
            <template #leReturnDate="{ row }">{{ row.stLend.leReturnDate }}</template>
            <template #deptName="{ row }">{{ row.stLend.pfDepartment.deptName }}</template>
            <template #userName="{ row }">{{ row.stLend.leMan.userName }}</template>
            <template #createMan="{ row }">{{ row.createMan.userName }}</template>
            <template #curStatus="{ row }">
                {{ row.stLend.curStatus == 20 ? '已借出' : row.stLend.curStatus == 24 ?
                    '部分归还' : row.stLend.curStatus == 25 ? '已归还' : "新建" }}
            </template> -->
      <template #menu-left>
        <!-- <el-input v-model="input" style="width: 240px;  margin-right: 24px" placeholder="请扫描条形码"  @keyup.enter.native="handleEnter"/> -->
        <!-- <el-button type="primary" @click="handleAdd">新增</el-button> -->
        <el-button type="primary" @click="handleBorrow()">借用</el-button>
        <el-button type="primary" @click="handleReturn">归还</el-button>
      </template>
      <template #menu="scope">
        <el-button type="text" @click="handleEdit(scope.row)" v-if="scope.row.curStatus === 1">修改</el-button>
        <el-button type="text" @click="rowDel(scope.row)" v-if="scope.row.curStatus === 1">删除</el-button>
      </template>
    </avue-crud>

    <el-dialog title="批量归还" append-to-body v-model="returnDialog" width="80%">
      <div>
        <el-input style="width:240px;margin-right:10px;" placeholder="扫描物料条码" v-model="checkGoods" @blur="changeGoods"></el-input>
        <el-button plain type="danger" @click="remove">删除选择行</el-button>
      </div>
      <!-- <el-button type="primary" @click="handleSave">保存</el-button> -->
      <el-table :data="returnData" style="margin-top: 10px" @select="selectChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          label="物料编码"
          prop="goodsCode"
          align="center"
        ></el-table-column>
        <el-table-column
          label="物料名称"
          prop="goodsName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="借出数量"
          prop="quantity"
          align="center"
        ></el-table-column>
        <el-table-column
          label="待归还数量"
          prop="waitRtnQuantity"
          align="center"
        ></el-table-column>
        <el-table-column label="合格数量" prop="passQty" align="center">
          <template #default="scope">
            <el-input-number
              style="width:90%;"
              v-model="scope.row.passQty"
              :min="0"
              controls-position="right"
            />
          </template>
        </el-table-column>
        <el-table-column label="丢失数量" prop="loseQty" align="center">
          <template #default="scope">
            <el-input-number
              style="width:90%;"
              v-model="scope.row.loseQty"
              :min="0"
              controls-position="right"
            />
          </template>
        </el-table-column>
        <!-- 如果有报废数量，自动生成一条报废记录 然后发送给工艺员（角色）审批  待报废  已报废(审批通过) -->
        <el-table-column label="报废数量" prop="bfQty" align="center">
          <template #default="scope">
            <el-input-number
              style="width:90%;"
              v-model="scope.row.bfQty"
              :min="0"
              controls-position="right"
              @change="(val) => handleChange(val,scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="使用次数" prop="useNumber" align="center">
          <template #default="scope">
            <el-input-number
              style="width:90%;"
              v-model="scope.row.useNumber"
              :min="1"
              controls-position="right"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-alert
        v-if="scarpTitle != ''"
        style="margin-top:20px;"
        :title="scarpTitle"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="returnDialog = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 借出 -->
    <borrowDialog
      v-if="isOpen"
      :showDialog="isOpen"
      @closeDialog="closeDialog"
      :moldAddMore="moldAddMore"
    >
    </borrowDialog>
  </basic-container>
</template>
<script>
import borrowDialog from "./components/borrowDialog.vue";
import {getList,getReturnData,addReturn,batchScrapOut } from "@/api/storeManagement/leveragingManagement.js"
export default {
  components: {
    borrowDialog,
  },
  data() {
    return {
      scarpTitle:"",
      loading: false,
      data: [],
      form: {},
      query:{},
      checkGoods:'',
      returnDialog: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      returnData: [],
      option: {
        height: "auto",
        calcHeight: 32,
        tip: false,
        // size: "medium",
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        editBtnText: "修改",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        viewBtnText: "详情",
        labelWidth: 150,
        menuWidth: 120,
        dialogWidth: 1500,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        columnSort: true,
        excelBtn: true,
        columnSort: true,
        index: false,
        showOverflowTooltip: true,
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "left",
        gridBtn: false,
        searchMenuPosition: "right",
        align: "center",
        menu:false,
        column: [
          {
            label: "单据号",
            prop: "leCode",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            order: 12,
            search: true,
            searchOrder: 20,
            rules: [
              {
                required: true,
                message: "请输入单据号",
                trigger: "click",
              },
            ],
          },
          {
            label: "物料编号",
            prop: "goodsCode",
            addDisplay: true,
            editDisplay: false,
            order: 11,
            span: 6,
            width: 200,
            search: true,
            searchOrder: 18,
            rules: [
              {
                required: true,
                message: "请输入物料编号",
                trigger: "click",
              },
            ],
          },
          {
            label: "物料名称",
            prop: "goodsName",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            order: 8,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入物料名称",
                trigger: "click",
              },
            ],
          },
          {
            label: "库房",
            prop: "shName",
            addDisplay: false,
            editDisplay: false,
            span: 6,
            width: 200,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入库房号",
                trigger: "click",
              },
            ],
          },
          {
            label: "库位",
            prop: "location",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入库位号",
                trigger: "click",
              },
            ],
          },
           {
            label: "型号/牌号",
            prop: "materialModel",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入型号/牌号",
                trigger: "click",
              },
            ],
          },
          {
            label: "批次号",
            prop: "piNo",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            order: 6,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入批号",
                trigger: "click",
              },
            ],
          },
          {
            label: "借出数量",
            prop: "quantity",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            order: 10,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入借出数量",
                trigger: "click",
              },
            ],
          },
          {
            label: "计量单位",
            prop: "unitName",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            order: 2,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入单位",
                trigger: "click",
              },
            ],
          },
          {
            label: "借用部门",
            prop: "deptName",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            order: 14,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入借用部门",
                trigger: "click",
              },
            ],
          },
            {
            label: "借用人",
            prop: "leManName",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            order: 13,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入借用人",
                trigger: "click",
              },
            ],
          },
           {
            label: "借出时间",
            prop: "leDate",
            addDisplay: true,
            editDisplay: false,
            type: "date",
            searchRange: true,
            startPlaceholder: "开始日期",
            endPlaceholder: "结束日期",
            format:"YYYY-MM-DD",
            valueFormat:"YYYY-MM-DD",

            span: 6,
            width: 200,
            order: 16,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入借出时间",
                trigger: "click",
              },
            ],
          },
          {
            label: "计划归还时间",
            prop: "leReturnDate",
            order: 9,
            type: "date",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入计划归还",
                trigger: "click",
              },
            ],
          },
          
        
          {
            label: "归还合格数量",
            prop: "returnPassTotal",
            addDisplay: false,
            editDisplay: false,
            span: 6,
            width: 200,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入本次归还合格数量",
                trigger: "click",
              },
            ],
          },
          {
            label: "归还丢失数量",
            prop: "returnLoseTotal",
            addDisplay: false,
            editDisplay: false,
            span: 6,
            width: 200,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入本次归还丢失数",
                trigger: "click",
              },
            ],
          },
          {
            label: "归还报废数量",
            prop: "returnBfTotal",
            addDisplay: false,
            editDisplay: false,
            span: 6,
            width: 200,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入本次归还报废数",
                trigger: "click",
              },
            ],
          },
          
          // {
          //   label: "库存量",
          //   prop: "stockNum",
          //   addDisplay: true,
          //   addDisabled: true,
          //   editDisplay: false,
          //   span: 6,
          //   width: 200,
          //   search: false,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入库存量",
          //       trigger: "click",
          //     },
          //   ],
          // },
          // {
          //   label: "可用库存",
          //   prop: "useQuantity",
          //   addDisplay: true,
          //   addDisabled: true,
          //   editDisplay: false,
          //   span: 6,
          //   width: 200,
          //   search: false,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入可用库存",
          //       trigger: "click",
          //     },
          //   ],
          // },
         
          // {
          //   label: "退库数量",
          //   prop: "returnQty",
          //   addDisplay: false,
          //   editDisplay: false,
          //   span: 6,
          //   width: 200,
          //   search: false,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入退库数量",
          //       trigger: "click",
          //     },
          //   ],
          // },
         
         
          // {
          //   label: "借出仓库",
          //   prop: "shId",
          //   type: "select",
          //   addDisplay: true,
          //   editDisplay: false,
          //   span: 6,
          //   width: 200,
          //   order: 15,
          //   search: false,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入借出仓库",
          //       trigger: "click",
          //     },
          //   ],
          //   dicData: [
          //     { label: "仓库一", value: "001" },
          //     { label: "仓库二", value: "002" },
          //   ],
          // },
          
          // {
          //     label: '本次归还续借数',
          //     prop: 'renewQty',
          //     addDisplay: false,
          //     editDisplay: false,
          //     span: 6,
          //     width: 200,
          //     search: false,
          //     rules: [
          //         {
          //             required: true,
          //             message: '请输入本次归还续借数',
          //             trigger: 'click',
          //         },
          //     ],
          // },
          // {
          //   label: "本次归还人",
          //   prop: "createMan",
          //   addDisplay: false,
          //   editDisplay: false,
          //   span: 6,
          //   width: 200,
          //   search: true,
          //   searchLabelWidth: 90,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入本次归还人",
          //       trigger: "click",
          //     },
          //   ],
          // },
          // {
          //   label: "本次使用次数",
          //   prop: "useNumber",
          //   addDisplay: false,
          //   editDisplay: false,
          //   span: 6,
          //   width: 200,
          //   search: false,

          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入本次使用次数",
          //       trigger: "click",
          //     },
          //   ],
          // },
          // {
          //   label: "本次归还时间",
          //   prop: "createTime",
          //   addDisplay: false,
          //   editDisplay: false,
          //   span: 6,
          //   width: 200,
          //   type: "date",
          //   searchRange: true,
          //   startPlaceholder: "开始日期",
          //   endPlaceholder: "结束日期",
          //   search: true,
          //   searchLabelWidth: 100,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入本次归还时间",
          //       trigger: "click",
          //     },
          //   ],
          // },
          {
            label: "是否报废",
            prop: "isScrap",
            addDisplay: false,
            editDisplay: false,
            span: 6,
            width: 200,
            search: false,
            type: "select",
            searchOrder: 17,
            dicData: [
              {
                label: "是",
                value: 1,
              },
              {
                label: "否",
                value: 0,
              },
            ],
            rules: [
              {
                required: true,
                message: "请输入是否报废",
                trigger: "click",
              },
            ],
          },
          {
            label: "状态",
            prop: "curStatus",
            addDisplay: false,
            editDisplay: false,
            span: 6,
            width: 200,
            search: true,
            type: "select",
            searchOrder: 18,
            // 状态1：新建；20：已借出；24：部分归还；25：已归还；
            dicData: [
              {
                label: "新建",
                value: 1,
              },
              {
                label: "已借出",
                value: 20,
              },
              {
                label: "部分归还",
                value: 24,
              },
              {
                label: "已归还",
                value: 25,
              },
            ],
            rules: [
              {
                required: true,
                message: "请输入状态",
                trigger: "click",
              },
            ],
          },
          {
            label: "备注",
            prop: "memo",
            type: "textarea",
            addDisplay: true,
            editDisplay: false,
            span: 6,
            width: 200,
            order: 1,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入备注",
                trigger: "click",
              },
            ],
          },

        ],
      },
      isOpen: false,
      moldAddMore: false,
    };
  },
  mounted() {},
  methods: {
    changeGoods(e){
      if(this.checkGoods == "") return
      getReturnData({
        barCode:this.checkGoods
      }).then(res =>{
        console.log('res---------',res)
        res.data.data.map(item =>{
          item._select = false
        })
        this.returnData = [...res.data.data,...this.returnData]
      })
    },
    handleChange(val,index){
      console.log('val--------',val)
      console.log('index---------',index)
      let tmp = this.returnData.filter(item => item.bfQty > 0)
      let nameArr = tmp.map(item => item.goodsName)
      let nameData = [...new Set(nameArr)]
      this.scarpTitle = `【${nameData.join(',')}】物料报废需工艺员审批，审批通过后可出库`
    },
    selectChange(list, row){
      row._select = !row._select
    },
    remove(){
      let tmp = this.returnData.find(item => item._select)
      if(!tmp){
        this.$message.error('请至少选择一条数据！')
        return
      }
      this.$confirm('确定删除数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.returnData = this.returnData.filter(row => !row._select);
      })
    },
    submit(){
      if(this.returnData.length == 0) return
      this.returnData.map(item =>{
        item.leId = item.id
      })
      console.log('data==========',this.returnData)
      addReturn(this.returnData).then(res =>{
        if(res.data.code == 200){
          this.$message.success('归还成功')
          this.returnDialog = false

          // let tmp = this.returnData.filter(item => item.bfQty > 0)
          // if(tmp && tmp.length > 0){
          //   console.log('tmp------------',tmp)
          //   let data = []
          //   tmp.map(item =>{
          //     data.push({
          //       rlsId:item.rlsId,
          //       outQty:item.bfQty,
          //       bfType:1
          //     })
          //   })
          //   batchScrapOut(data).then(res =>{
          //     if(res.data.code == 200){
          //       this.$message.success('归还成功')
          //       this.returnDialog = false
          //     }
          //   })
          // }else{
          
          // }
        }
        
      })
      
    },
    handleEdit() {
      this.isOpen = true;
      this.moldAddMore = false;
    },
    // 借用
    handleAdd() {
      this.isOpen = true;
      this.moldAddMore = true;
    },
    closeDialog(val) {
      this.isOpen = false;
      if(val){
        this.onLoad()
      }
    },
    handleBorrow(){
      this.isOpen = true
    },
    handleReturn() {
      this.checkGoods = ""
      this.scarpTitle = ""
      this.returnData = []
      this.returnDialog = true;
    },
    searchChange(params, done){
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad();
      done();
    },
    searchReset(){
      this.query = {};
      this.onLoad();
    },
    currentChange(currentPage){
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize;
    },
    refreshChange(){
      this.onLoad()
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // deleteLeveraging(row.id).then(() => {
        //   this.$message.success('删除成功');
        //   this.onLoad();
        // }).catch(() => {
        //   this.$message.error('删除失败');

      }).catch(() => {});
    },
    handleEnter() {
      this.$confirm("确定借出?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        callback();
      });
    },
    onLoad() {
      this.loading = true
      let params = {
        ...this.query,
        startLeDate:this.query.leDate && this.query.leDate.length > 0 && this.query.leDate[0],
        endLeDate:this.query.leDate && this.query.leDate.length > 0 && this.query.leDate[1],
      }
      const {leDate,...searchParams} = params
      console.log('sezrch------------',searchParams)
      getList({
        current:this.page.currentPage,
        size:this.page.pageSize,
        ...searchParams
      }).then(res =>{
        this.data = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      })
    },
  },
};
</script>

<style></style>
