<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="退货单号" prop="returnsNumber">
        <el-input
          v-model="queryParams.returnsNumber"
          placeholder="请输入退货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库单号" prop="putawayCode">
        <el-input
          v-model="queryParams.putawayCode"
          placeholder="请输入入库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="到货单号" prop="arrivalNumber">
        <el-input
          v-model="queryParams.arrivalNumber"
          placeholder="请输入到货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:materialReturns:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['business:materialReturns:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['business:materialReturns:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:materialReturns:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialReturnsList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="退货单号" align="center" prop="returnsCode" width="160px"/>
      <el-table-column label="入库单号" align="center" prop="putawayCode" width="160px" />
      <el-table-column label="到货单号" align="center" prop="arrivalNumber" />
      <el-table-column label="订单单号" align="center" prop="orderNumber" />
      <el-table-column label="退货金额" align="center" prop="returnsMoney" />
      <el-table-column label="退货时间" align="center" prop="returnsTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnsTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="150px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['business:materialReturns:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
          >详情</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['business:materialReturns:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料退货对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <span style="font-weight: bold; font-size: 18px">退货信息</span>
      <el-divider />
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库单号" prop="putawayId">
              <el-select v-model="form.putawayId" filterable placeholder="请选择入库单" @change="putawayChange" style="width:100%">
                <el-option v-for="(item,index) of materialPutawayOpt" :key="index" :label="item.putawayCode" :value="item.id">{{item.putawayCode}}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="form.warehouseName" disabled placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="入库类型" prop="warehouseName">-->
<!--              <el-input v-model="form.warehouseName" disabled placeholder="请选择入库类型" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="入库时间" prop="putawayTime">
              <el-date-picker clearable
                              v-model="form.putawayTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              disabled
                              style="width: 100%"
                              placeholder="请选择入库时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货单号" prop="returnsNumber">
              <el-input v-model="form.returnsNumber" disabled placeholder="自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单单号" prop="orderNumber">
              <el-input v-model="form.orderNumber" disabled placeholder="请输入订单单号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到货单号" prop="arrivalNumber">
              <el-input v-model="form.arrivalNumber" disabled placeholder="请输入到货单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货时间" prop="returnsTime">
              <el-date-picker clearable
                              v-model="form.returnsTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              style="width: 100%"
                              placeholder="请选择退货时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库金额" prop="putawayMoney">
              <el-input v-model="form.putawayMoney" disabled placeholder="请输入入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货金额" prop="returnsMoney">
              <el-input-number v-model="form.returnsMoney" :min="0" :precision="2" disabled style="width: 100%" placeholder="请输入退货金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="操作人" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入操作人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作时间" prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" style="width: 100%" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择操作时间" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span style="font-weight: bold; font-size: 18px">物料信息</span>
      <el-divider />
      <el-table :data="materialList" ref="selectionTable" max-height="450">
<!--        <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
<!--        <el-table-column label="货位类型" align="center" prop="warehouseLocationType" />-->
        <el-table-column label="供应商" align="center" prop="vendorName" fixed="left" show-overflow-tooltip width="200"/>
        <el-table-column label="物资编码" align="center" prop="materialCode" show-overflow-tooltip fixed="left" width="130" />
        <el-table-column label="物资名称" align="center" prop="materialName" show-overflow-tooltip fixed="left" width="130" />
        <el-table-column label="物资规格" align="center" prop="materialSpecifications" fixed="left" />
        <el-table-column label="物资单位" align="center" prop="materialUnit" fixed="left">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.material_unit" :value="scope.row.materialUnit" />
          </template>
        </el-table-column>
        <el-table-column label="质保期" align="center" prop="materialWarrantyPeriod" />
        <el-table-column label="入库数量" align="center" prop="putawayNumber" />
        <el-table-column label="入库单价" align="center" prop="putawayPrice" />
        <el-table-column label="入库金额" align="center" prop="putawayMoney" />
        <el-table-column label="已退数量" align="center" prop="returnedNumber" />
        <el-table-column label="已出数量" align="center" prop="issuedNumber" />
        <el-table-column label="可退数量" align="center" prop="canBackNumber">
          <template slot-scope="scope">
            <span>{{scope.row.putawayNumber - scope.row.returnedNumber - scope.row.issuedNumber}}</span>
          </template>
        </el-table-column>
        <el-table-column label="退货数量" align="center" prop="returnsNumber" width="120px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.returnsNumber" @change="returnsNumberChange" controls-position="right" size="mini" :min="0" :precision="2" :max="parseFloat(scope.row.putawayNumber) - parseFloat(scope.row.returnedNumber) - parseFloat(scope.row.issuedNumber)"  style="width: 100%" placeholder="数量"/>
          </template>
        </el-table-column>
        <el-table-column label="退货单价" align="center" prop="returnsPrice" width="160px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.returnsPrice" disabled controls-position="right" size="mini" :precision="2" style="width: 100%" placeholder="单价"/>
          </template>
        </el-table-column>
        <el-table-column label="退货金额" align="center" prop="returnsMoney" width="160px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.returnsMoney" disabled controls-position="right" size="mini" :precision="2" style="width: 100%" placeholder="金额"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRowDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 退货单详情 -->
    <el-dialog :title="title" :visible.sync="open1" width="80%" append-to-body>
      <span style="font-size: 16px; font-weight: bold; margin-bottom: 20px">退货信息</span>
      <el-descriptions class="margin-top" :column="3" border>
        <el-descriptions-item label="入库单号">{{form.putawayCode}}</el-descriptions-item>
        <el-descriptions-item label="仓库名称">{{form.warehouseName}}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{form.putawayTime}}</el-descriptions-item>
        <el-descriptions-item label="订单单号">{{form.orderNumber}}</el-descriptions-item>
        <el-descriptions-item label="到货单号">{{form.arrivalNumber}}</el-descriptions-item>
        <el-descriptions-item label="入库类型">
          <dict-tag :options="dict.type.putaway_type" :value="form.putawayType"/>
        </el-descriptions-item>
        <el-descriptions-item label="入库金额">{{form.putawayMoney}}</el-descriptions-item>
        <el-descriptions-item label="退货单号">{{form.returnsCode}}</el-descriptions-item>
        <el-descriptions-item label="退货金额">{{form.returnsMoney}}</el-descriptions-item>
        <el-descriptions-item label="退货时间">{{form.returnsTime}}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{form.createBy}}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{form.createTime}}</el-descriptions-item>
      </el-descriptions>
      <span style="font-size: 16px; font-weight: bold; margin-bottom: 20px">退货明细</span>
      <el-table :data="form.returnsInfoList">
<!--        <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
<!--        <el-table-column label="货位类型" align="center" prop="warehouseLocationType" />-->
        <el-table-column label="供应商" align="center" prop="vendorName" />
        <el-table-column label="物资编码" align="center" prop="materialCode" />
        <el-table-column label="物资名称" align="center" prop="materialName" />
        <el-table-column label="物资规格" align="center" prop="materialSpecifications" />
        <el-table-column label="物资单位" align="center" prop="materialUnit">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.material_unit" :value="scope.row.materialUnit" />
          </template>
        </el-table-column>
        <el-table-column label="质保期" align="center" prop="materialWarrantyPeriod" />
        <el-table-column label="退货数量" align="center" prop="returnsNumber" />
        <el-table-column label="退货单价" align="center" prop="returnsPrice" />
        <el-table-column label="退货金额" align="center" prop="returnsMoney" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterialReturns, getMaterialReturns, delMaterialReturns, addMaterialReturns, updateMaterialReturns } from "@/api/business/materialReturns";
import { getMaterialPutaway, listMaterialPutaway, listMaterialPutawayAll } from '@/api/business/materialPutaway'
import { formatDate } from '@/utils'

export default {
  name: "MaterialReturns",
  dicts:['sys_is_enable', 'putaway_type','material_unit'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料入库单下拉
      materialPutawayOpt: [],
      // 物料退货表格数据
      materialReturnsList: [],
      materialList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        returnsNumber: undefined,
        returnsMoney: undefined,
        returnsTime: undefined,
        putawayId: undefined,
        putawayNumber: undefined,
        orderNumber: undefined,
        arrivalNumber: undefined,
        putawayType: undefined,
        putawayTime: undefined,
        putawayMoney: undefined,
        warehouseId: undefined,
        warehouseName: undefined,
        vendorId: undefined,
        vendorName: undefined,
        createDeptId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // returnsMoney: [
        //   { required: true, message: "退货金额不能为空", trigger: "blur" }
        // ],
        returnsTime: [
          { required: true, message: "退货时间不能为空", trigger: "blur" }
        ],
        putawayId: [
          { required: true, message: "入库ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物料退货列表 */
    getList() {
      this.loading = true;
      listMaterialReturns(this.queryParams).then(response => {
        this.materialReturnsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询物料入库列表 */
    getPutawayList() {
      listMaterialPutawayAll({ state: 2, putawayType: 1 }).then(response => {
        this.materialPutawayOpt = response.data;
      });
    },
    // 退货数量更改
    returnsNumberChange() {
      this.form.returnsMoney = this.materialList.reduce((sum, item) => {
        item.returnsMoney = parseFloat(item.returnsNumber) * parseFloat(item.returnsPrice)
        return sum + (parseFloat(item.returnsNumber) * parseFloat(item.returnsPrice));
      }, 0)
    },
    // 入库明细删除
    handleRowDelete(row) {
      this.materialList = this.materialList.filter(item => item.id !== row.id);
      this.form.returnsMoney = this.materialList.reduce((sum, item) => {
        return sum + (parseFloat(item.returnsNumber) * parseFloat(item.returnsPrice));
      }, 0)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        returnsCode: undefined,
        returnsMoney: undefined,
        returnsTime: formatDate(new Date().getTime()),
        putawayId: undefined,
        putawayNumber: undefined,
        orderNumber: undefined,
        arrivalNumber: undefined,
        putawayType: undefined,
        putawayTime: undefined,
        putawayMoney: undefined,
        warehouseId: undefined,
        warehouseName: undefined,
        vendorId: undefined,
        vendorName: undefined,
        createBy: this.$store.state.user.userInfo.userName,
        createTime: formatDate(new Date().getTime()),
        updateBy: undefined,
        updateTime: undefined,
        createDeptId: undefined
      };
      this.materialList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 入库单更改
    putawayChange(id) {
      getMaterialPutaway(id).then(response => {
        this.form.warehouseName = response.data.warehouseName;
        this.form.putawayType = response.data.putawayType;
        this.form.orderNumber = response.data.orderNumber;
        this.form.arrivalNumber = response.data.arrivalNumber;
        this.form.putawayTime = response.data.putawayTime;
        this.form.putawayMoney = response.data.putawayMoney;
        this.materialList = response.data.putawayInfoList.map(item =>{
          item.putawayInfoId = item.id
          item.returnsPrice = item.putawayPrice
          return item
        })
      })
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const id = row.id
      getMaterialReturns(id).then(response => {
        this.form = response.data;
        this.open1 = true;
        this.title = "物料退货详情";
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料退货";
      this.getPutawayList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMaterialReturns(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.materialList = response.data.returnsInfoList
        this.open = true;
        this.title = "修改物料退货";
        this.getPutawayList()
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.returnsInfoBoList = this.materialList
          let isTrue = false;
          this.form.returnsInfoBoList.forEach(item => {
            if (item.returnsNumber < 0.01) {
              isTrue = true;
            }
          })
          if (isTrue) {
            this.$modal.msgError('退货数量不能小于0.01')
            this.buttonLoading = false;
            return
          }
          if (this.form.id != null) {
            updateMaterialReturns(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterialReturns(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料退货单？').then(() => {
        this.loading = true;
        return delMaterialReturns(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/materialReturns/export', {
        ...this.queryParams
      }, `物料退货单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
