<template>
  <el-dialog
    v-dialogDrag
    title="退料操作"
    :visible.sync="open"
    width="1200px"
    append-to-body
    @open="dialogOpen"
    @close="dialogClose"
  >
    <!-- 操作区 -->
    <el-form
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="88px"
      :rules="rules"
    >
      <QueryFormWrapper>
        <el-col :span="8">
          <el-form-item label="退料id" prop="wmsReturnWorkOrderPreId">
            <el-input
              v-model="queryParams.wmsReturnWorkOrderPreId"
              placeholder="请输入退料id"
              clearable
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="退料类型" prop="returnType">
            <el-select
              v-model="queryParams.returnType"
              placeholder="请选择退料类型"
              clearable
              size="small"
              :disabled="returnDis"
            >
              <el-option
                v-for="dict in getDictDatas(DICT_TYPE.WMS_MATERIAL_RETURN_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="退料原因" prop="remark">
            <el-input
              v-model="queryParams.remark"
              :disabled="returnDis"
              placeholder="请输入退料原因"
              clearable
            />
          </el-form-item>
        </el-col>
        <div slot="right">
          <el-form-item label-width="0" class="text-right" style="word">
            <EasyAdvancedQuery class="mr10" label-width="98px" @advQuery="advQuery">
              <template #default="{model}">
                <el-row :gutter="10" type="flex">
                  <el-col :span="12">
                    <el-form-item label="物料编码" prop="materialNo">
                      <el-input
                        v-model="model.materialNo"
                        placeholder="请输入物料编码"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物料名称" prop="materialName">
                      <el-input
                        v-model="model.materialName"
                        placeholder="请输入物料名称"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </EasyAdvancedQuery>
            <el-button
              v-show="auditStatus === null || auditStatus === -1"
              v-hasPermi="['wms:return-work-order-pre:create']"
              type="primary"
              icon="el-icon-turn-off"
              :loading="saveLoading"
              @click="handleSave"
            >保存</el-button>
            <el-button
              v-show="auditStatus === null || auditStatus === -1"
              v-hasPermi="['wms:return-work-order-pre:update']"
              type="primary"
              icon="el-icon-finished"
              :loading="saveLoading"
              @click="handleCommit"
            >提交</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </div>
      </QueryFormWrapper>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-show="auditStatus === -1 || auditStatus === null"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>

    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      border
      size="mini"
      :summary-method="getSummaries"
      show-summary
    >
      <el-table-column
        label="退料单号"
        align="center"
        prop="returnOrderNo"
        width="130"
      />
      <el-table-column
        label="领料单号"
        align="center"
        prop="receiveOrderNo"
        width="130"
      />
      <el-table-column
        label="发料单号"
        align="center"
        prop="sendOrderNo"
        width="130"
      />
      <el-table-column
        label="物料编号"
        align="center"
        prop="materialNo"
        width="130"
      />
      <el-table-column
        label="物料条码"
        align="center"
        prop="qrCode"
        width="150"
      />
      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="物料批次" align="center" prop="materialLots" />
      <el-table-column label="生产订单" align="center" prop="workOrderNo" />
      <el-table-column label="采购单号" align="center" prop="purchaseOrderNo" />
      <el-table-column
        label="供应商编号"
        align="center"
        prop="supplierCode"
        width="120"
      />
      <el-table-column label="发料数量" align="center" prop="sendQty" />
      <el-table-column label="退料数量" align="center" prop="returnQty" />
      <el-table-column label="长度" align="center" prop="length" />
      <el-table-column label="宽度" align="center" prop="width" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="100"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            class="text-danger"
            icon="el-icon-delete"
            :disabled="deleteMaterialDis"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 退料 -->
    <MaterialReturn ref="materialReturn" @updateList="refreshList" />
  </el-dialog>
</template>

<script>
import { getReturnWorkOrderPreDetailPage, saveMaterialsReturnPre, commitMaterialsReturnPre } from '@/api/wms/output/materialReturn'
import MaterialReturn from './MaterialReturn.vue'

export default {
  name: 'ReturnMaterialList',
  components: {
    MaterialReturn
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      saveLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // wms来料退货单明细列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否禁用
      returnDis: false,
      // 是否显示弹出层
      open: false,
      auditStatus: null,
      // 已审核的禁用删除
      deleteMaterialDis: false,
      // 高级查询
      advParams: {
        materialName: null,
        materialNo: null
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        remark: null,
        returnType: null,
        wmsReturnWorkOrderPreId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        returnType: [{ required: true, message: '请选择退料类型', trigger: 'change' }],
        remark: [{ required: true, message: '退料原因不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    // this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      const params = {
        ...this.queryParams,
        ...this.advParams
      }
      getReturnWorkOrderPreDetailPage(params).then(response => {
        this.list = response.data.list
        this.refreshList()
        this.total = response.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        masterId: undefined,
        purchaseOrderNo: undefined,
        wmsIncomingReceiptId: undefined,
        materialNo: undefined,
        returnQty: undefined,
        returnStatus: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    refreshList(data) {
      if (!data) {
        return
      }
      this.list.push(...data)
      this.list = this.list.map(item => {
        const { canReturnQty, returnQty, ...rest } = item
        return {
          ...rest,
          returnQty: canReturnQty || returnQty
        }
      })
    },
    dialogOpen() {
      this.$nextTick(() => {
        this.getList()
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.advParams = {}
      this.getList()
    },
    // 保存
    handleSave() {
      this.$refs['queryForm'].validate(valid => {
        if (!valid) {
          return
        }
        this.saveLoading = true
        const { wmsReturnWorkOrderPreId, remark, returnType } = this.queryParams
        const detailList = this.list.map(item => {
          const { materialNo, materialLots, materialName, purchaseOrderNo, qrCode, returnQty, sendOrderNo, sendQty, supplierCode, receiveOrderNo } = item
          return {
            materialNo, materialLots, materialName, purchaseOrderNo, qrCode, returnQty, sendOrderNo, sendQty, supplierCode, receiveOrderNo, width: item?.width ?? 0, length: item?.canReturnLength ?? 0
          }
        })
        const params = {
          detail: detailList,
          id: wmsReturnWorkOrderPreId,
          remark,
          returnType
        }
        saveMaterialsReturnPre(params).then(res => {
          this.queryParams.wmsReturnWorkOrderPreId = res.data
          this.$modal.msgSuccess('保存成功~')
          this.saveLoading = false
          this.getList()
          this.$parent.$refs.Tosubmit[0].getList()
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    // 提交
    handleCommit() {
      this.saveLoading = true
      const { wmsReturnWorkOrderPreId } = this.queryParams
      const params = {
        id: wmsReturnWorkOrderPreId
      }
      this.$modal.confirm('您正在执行提交退料操作，是否继续？').then(() => {
        commitMaterialsReturnPre(params).then(res => {
          this.$modal.msgSuccess('提交成功~')
          this.saveLoading = false
          this.$emit('complete')
          this.open = false
        }).finally(() => {
          this.saveLoading = false
        })
      }).catch(() => {
        this.$modal.msg('您已取消操作')
        this.saveLoading = false
      })
    },
    // 新增
    handleAdd() {
      this.$refs.materialReturn.open = true
    },
    dialogClose() {
      this.reset()
      this.queryParams.returnStatus = undefined
      this.queryParams.remark = undefined
      this.queryParams.wmsReturnWorkOrderPreId = undefined
      this.queryParams.returnType = undefined
    },
    // 删除
    handleDelete(row) {
      const { id } = row
      const index = this.list.findIndex(item => item.id === id)
      if (index > -1) {
        this.list.splice(index, 1)
      }
    },
    // 高级查询
    advQuery(advQueryParams) {
      this.advParams = advQueryParams
      this.getList()
    },
    // 小数点问题处理
    getHandleTotalNumber(val) {
      return Math.round((parseFloat(val) * 100000000)) / 100000000
    },
    // 总计
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '退料总计'
          return
        }
        const values = this.list.map(item => Number(item[column.property])) || []
        if (column.property === 'returnQty') {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur)
            if (!isNaN(value)) {
              return this.getHandleTotalNumber(acc + cur)
            } else {
              return this.getHandleTotalNumber(acc)
            }
          }, 0)
          sums[index]
        }
      })
      return sums
    }
  }
}
</script>

