<template>
  <div>
    <div style="padding: 10px; margin-bottom: 80px">
      <el-form ref="form" :model="form" :rules="rules" label-width="85px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="出库时间" prop="outTime">
              <el-date-picker clearable
                              v-model="form.outTime"
                              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="6">
            <el-form-item label="报修单" prop="repairNumber">
              <el-input v-model="form.repairNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库单号" prop="outNumber">
              <el-input v-model="form.outNumber" disabled placeholder="自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" disabled  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="供应商" prop="vendorId">
              <el-select v-model="form.vendorId" placeHolder="请选择供应商" filterable @change="vendorIdChange" style="width: 100%">
                <el-option v-for="item in materialVendorOpt" :key="item.id" :value="item.id" :label="item.vendorName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车牌号" prop="plateNumber">
              <el-input v-model="form.plateNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="repairerDeptName">
              <el-input v-model="form.repairerDeptName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="班组" prop="repairerGroupName">
              <el-input v-model="form.repairerGroupName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="出库金额" prop="outMoney">
              <el-input v-model="form.outMoney" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </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="openMaterialModel">新增</el-button>
        </el-col>
      </el-row>
      <el-table :data="form.pickingInfoList">
<!--        <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
<!--        <el-table-column label="货位类型" align="center" prop="warehouseLocationType" />-->
        <el-table-column label="仓库" align="center" prop="warehouseName" />
        <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="referencePrice" />
        <el-table-column label="销售价" align="center" prop="sellingPrice" />
        <el-table-column label="库存" align="center" prop="inventory" />
        <el-table-column label="领料数量" align="center" prop="collectNumber" width="120px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.collectNumber" @change="collectNumberChange" controls-position="right" size="mini" :min="0.01" :precision="2" :max="parseFloat(scope.row.inventory)" style="width: 100%" placeholder="数量"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="销售单价" align="center" prop="price" width="120px">-->
<!--          <template slot-scope="scope">-->
<!--            <el-input-number v-model="scope.row.price" disabled controls-position="right" size="mini" :min="1" :precision="2" style="width: 100%" placeholder="单价"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="领料金额" align="center" prop="money" width="120px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.money" disabled controls-position="right" size="mini" :precision="2" style="width: 100%" placeholder="金额"/>
          </template>
        </el-table-column>
        <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-delete" @click="handleRowDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer-container">
      <el-button v-loading="buttonLoading" type="primary" size="medium"  @click="submitForm(1)">保 存</el-button>
      <el-button v-loading="buttonLoading" type="primary" size="medium"  @click="submitForm(2)">提 交</el-button>
      <el-button v-loading="buttonLoading" type="info" plain size="medium" @click="cancel">取消</el-button>
    </div>

    <!-- 物料列表对话框 -->
    <el-dialog title="物料列表" :visible.sync="open1" width="65%" append-to-body>
      <el-form :model="queryMaterialParams" ref="queryMaterialForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="供应商" prop="vendorId">
          <el-select v-model="queryMaterialParams.vendorId" filterable disabled placeholder="请选择供应商" style="width: 100%">
            <el-option v-for="item in materialVendorOpt" :key="item.id" :value="item.id" :label="item.vendorName" />
          </el-select>
        </el-form-item>
        <el-form-item label="物资编码" prop="materialCode">
          <el-input
              v-model="queryMaterialParams.materialCode"
              placeholder="请输入物资编码"
              clearable
              @keyup.enter.native="handleMaterialQuery"
          />
        </el-form-item>
        <el-form-item label="物资名称" prop="materialName">
          <el-input
              v-model="queryMaterialParams.materialName"
              placeholder="请输入物资名称"
              clearable
              @keyup.enter.native="handleMaterialQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMaterialQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMaterialQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="materialLoading" :data="materialList" ref="selectionTable" max-height="450" @selection-change="handleMaterialSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
<!--        <el-table-column label="货位类型" align="center" prop="warehouseLocationType" />-->
        <el-table-column label="仓库" align="center" prop="warehouseName" />
        <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="referencePrice" />
        <el-table-column label="销售价" align="center" prop="sellingPrice" />
        <el-table-column label="库存" align="center" prop="inventory" />
      </el-table>
      <pagination v-show="materialTotal>0" :total="materialTotal" :page.sync="queryMaterialParams.pageNum" :limit.sync="queryMaterialParams.pageSize" @pagination="getMaterialList"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelection">确 定</el-button>
        <el-button @click="cancelMaterial">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addMaterialPicking, listMaterialPicking, updateMaterialPicking} from '@/api/business/materialPicking'
import {customListMaterial} from '@/api/business/material'
import {listWarehouseAll} from "@/api/business/siteWarehouse";
import {listMaterialVendorAll} from "@/api/business/materialVendor";
import {formatDate} from "@/utils";

export default {
  name: "MaterialPickingAdd",
  dicts: ['sys_is_enable', 'picking_state', 'material_unit'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非登记状态禁用
      isTrue: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料出库表格数据
      materialPickingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        repairFormId: undefined,
        repairNumber: undefined,
        outNumber: undefined,
        returnNumber: undefined,
        carId: undefined,
        plateNumber: undefined,
        outMoney: undefined,
        receiveUserId: undefined,
        receiveUserName: undefined,
        receiveTime: undefined,
        state: undefined,
        stateList: [1, 2],
        outTime: undefined,
      },
      // 表单参数
      form: {
        pickingInfoList: [],
        outTime: formatDate(new Date().getTime())
      },
      open1: false,
      open2: false,
      materialLoading: false,
      tempSelection: [],
      // 物料列表
      materialList: [],
      materialTotal: 0,
      // 仓库列表
      warehouseOpt: [],
      // 供应商
      materialVendorOpt: [],
      // 查询参数
      queryMaterialParams: {
        pageNum: 1,
        pageSize: 10,
        vendorName: undefined,
        warehouseId: undefined,
        warehouseIdList: [],
        materialCode: undefined,
        materialName: undefined,
        inventory: 0,
      },
      // 表单校验
      rules: {
        repairFormId: [
          { required: true, message: "报修单不能为空", trigger: "blur" }
        ],
        outTime: [
          { required: true, message: "出库时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.form = {...this.$route.query, outMoney: undefined}
    this.getWarehouseList(this.form.repairerDeptId)
    this.getVendorList()
  },
  methods: {
    /** 查询仓库列表 */
    getWarehouseList(deptId) {
      listWarehouseAll({deptId}).then(response => {
        this.warehouseOpt = response.data;
        this.queryMaterialParams.warehouseIdList = response.data.map(item => item.id);
      });
    },
    /** 查询物资供应商列表 */
    getVendorList() {
      listMaterialVendorAll().then(response => {
        this.materialVendorOpt = response.data;
      });
    },
    /** 查询物料出库列表 */
    getList() {
      this.loading = true;
      listMaterialPicking({ ...this.queryParams, repairFormId: this.repairFormId  }).then(response => {
        this.materialPickingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 供应商改变 */
    vendorIdChange(vendorId) {
      if (vendorId) {
        this.queryMaterialParams.vendorId = vendorId;
      }
      this.form.pickingInfoList = []
    },
    /** 打开物料列表 */
    openMaterialModel() {
      if (!this.form.repairerDeptId) {
        this.$modal.msgError("请选择报修单");
        return
      }
      if (!this.form.vendorId) {
        this.$modal.msgError("请先选择供应商");
        return
      }
      this.open1 = true
      this.getMaterialList()
    },
    /** 搜索按钮操作 */
    handleMaterialQuery() {
      this.queryMaterialParams.pageNum = 1;
      this.queryMaterialParams.warehouseIdList = this.warehouseOpt.map(item => item.id);
      this.getMaterialList();
    },
    /** 重置按钮操作 */
    resetMaterialQuery() {
      this.resetForm("queryMaterialForm");
      this.handleMaterialQuery();
    },
    /** 查询物资列表 */
    getMaterialList() {
      this.materialLoading = true;
      customListMaterial({ ...this.queryMaterialParams }).then(response => {
        this.materialList = response.rows;
        this.materialTotal = response.total;
        this.materialLoading = false;
      }).then(() =>{
        this.$nextTick(() => {
          // 清空临时勾选
          this.tempSelection = [];
          // 手动设置勾选（匹配外部已选数据）
          this.materialList.forEach(row => {
            const isSelected = this.form.pickingInfoList.some(item => item.recordId === row.recordId);
            this.$refs.selectionTable.toggleRowSelection(row, isSelected);
          });
        });
      })
    },
    // 入库明细删除
    handleRowDelete(row) {
      this.form.pickingInfoList = this.form.pickingInfoList.filter(item =>
        !(item.materialId === row.materialId && item.warehouseId === row.warehouseId)
      );
      this.$forceUpdate();
    },
    // 入库数量变动
    collectNumberChange() {
      this.form.outMoney = this.form.pickingInfoList.reduce((sum, item) => {
        item.money = item.collectNumber * item.sellingPrice
        return sum + (item.collectNumber * item.sellingPrice);
      }, 0)
      console.log('outMoney', this.form.outMoney)
    },
    // 多选框选中数据
    handleMaterialSelectionChange(selection) {
      this.tempSelection = selection
    },
    // 将选中物料添加至入库明细列表
    confirmSelection() {
      this.form.pickingInfoList = this.tempSelection.map(item =>{
        item.price = item.sellingPrice
        return item
      })
      this.open1 = false
    },
    // 取消按钮
    cancelMaterial() {
      this.open1 = false;
    },
    // 取消按钮
    cancel() {
      this.$tab.closeOpenPage({name: "repairFormEdit", query:{repairFormId: this.form.repairFormId, flag: this.form.flag, isDelivery: this.form.isDelivery}});
    },
    /** 提交按钮 */
    submitForm(state) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pickingInfoList.length < 1) {
            this.$modal.msgError('出库明细列表不能为空')
            return
          }
          let isTrue = false
          this.form.pickingInfoList.forEach(item =>{
            if (!item.collectNumber) {
              isTrue = true
            }
          })
          if (isTrue) {
            this.$modal.msgError('领料数量不能为空')
            return
          }
          this.form.materialList = this.form.pickingInfoList.map(item =>{
            return {
              recordId: item.recordId,
              infoId: item.infoId,
              warehouseId: item.warehouseId,
              warehouseName: item.warehouseName,
              vendorId: item.vendorId,
              vendorName: item.vendorName,
              materialId: item.materialId,
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialSpecifications: item.materialSpecifications,
              materialUnit: item.materialUnit,
              materialWarrantyPeriod: item.materialWarrantyPeriod,
              referencePrice: item.referencePrice,
              sellingPrice: item.sellingPrice,
              collectNumber: item.collectNumber,
              price: item.price,
              money: item.money,
            }
          })
          this.buttonLoading = true;
          this.form.state = state
          if (this.form.id != null) {
            updateMaterialPicking(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
              this.$tab.closeOpenPage({name: "repairFormEdit", query:{repairFormId: this.form.repairFormId, flag: this.form.flag, isDelivery: this.form.isDelivery}});
            });
          } else {
            addMaterialPicking(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
              this.$tab.closeOpenPage({name: "repairFormEdit", query:{repairFormId: this.form.repairFormId, flag: this.form.flag, isDelivery: this.form.isDelivery}});
            });
          }
        }
      });
    },
  }
};
</script>
<style scoped lang="scss">
.footer-container {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  padding: 16px;
  text-align: right;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}
</style>
