<template>
  <div class="app-container" style="padding: 0;">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="isDelivery == 1"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            :type="isTrue ? 'info' : 'success'"
            plain
            icon="el-icon-finished"
            size="mini"
            :disabled="isTrue || isDelivery == 1"
            @click="handleConfirm"
        >出库</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialPickingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库单号" align="center" prop="outNumber" />
      <el-table-column label="报修单号" align="center" prop="repairNumber" />
      <!--      <el-table-column label="退料单号" align="center" prop="returnNumber" />-->
      <el-table-column label="车牌号" align="center" prop="plateNumber" />
      <el-table-column label="出库金额" align="center" prop="outMoney" />
      <el-table-column label="领料人" align="center" prop="receiveUserName" />
      <el-table-column label="领料时间" align="center" prop="receiveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.picking_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="出库时间" align="center" prop="outTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outTime, '{y}-{m}-{d}') }}</span>
        </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-document"
              @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              :disabled="scope.row.state === 2 || isDelivery == 1"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:materialPicking:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              :disabled="scope.row.state === 2 || isDelivery == 1"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:materialPicking:remove']"
          >删除</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-finished"
              v-if="scope.row.state === 1 && isDelivery == 0"
              @click="handleConfirm(scope.row)"
              v-hasPermi="['business:materialPicking:confirm']"
          >出库</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>
      <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="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="1" :precision="0" 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" :min="1" 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 slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm(1)">保 存</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm(2)">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 物料列表对话框 -->
    <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="vendorName">
          <el-input
              v-model="queryMaterialParams.vendorName"
              placeholder="请输入供应商名称"
              clearable
              @keyup.enter.native="handleMaterialQuery"
          />
        </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="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="isEnable">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_is_enable" :value="scope.row.isEnable"/>
          </template>
        </el-table-column>
      </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>

    <!-- 物料详情 -->
    <el-dialog title="物料出库详情" :visible.sync="open2" width="80%" append-to-body>
      <span style="font-weight: bold; font-size: 18px">出库信息</span>
      <el-divider />
      <el-descriptions border :column="3">
        <el-descriptions-item label="出库单号">{{form.outNumber}}</el-descriptions-item>
        <el-descriptions-item label="出库时间">{{form.outTime}}</el-descriptions-item>
        <el-descriptions-item label="出库金额">{{form.outMoney}}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{form.clientName}}</el-descriptions-item>
        <el-descriptions-item label="报修单">{{form.repairNumber}}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{form.plateNumber}}</el-descriptions-item>
        <el-descriptions-item label="部门">{{form.repairerDeptName}}</el-descriptions-item>
        <el-descriptions-item label="班组">{{form.repairerGroupName}}</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-weight: bold; font-size: 18px">出库明细</span>
      <el-divider />
      <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="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="collectNumber" width="120px" />
<!--        <el-table-column label="销售单价" align="center" prop="price" width="120px" />-->
        <el-table-column label="领料金额" align="center" prop="money" width="120px" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMaterialPicking,
  confirmMaterialPicking,
  delMaterialPicking,
  getMaterialPicking,
  listMaterialPicking,
  updateMaterialPicking
} from '@/api/business/materialPicking'
import { getRepairForm } from '@/api/business/repairForm'
import { listMaterial } from '@/api/business/material'
import {listMaterialVendorAll} from "@/api/business/materialVendor";
import {formatDate} from "@/utils";

export default {
  name: "MaterialPickingInfo",
  dicts: ['sys_is_enable', 'picking_state', 'material_unit'],
  props: {
    repairFormId:{},
    repairNumber:{},
    clientName:{},
    carId:{},
    plateNumber:{},
    repairerDeptId:{},
    repairerDeptName:{},
    repairerGroupName:{},
    isDelivery:{},
    flag:{},
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非登记状态禁用
      isTrue: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料出库表格数据
      materialPickingList: [],
      materialVendorOpt: [],
      // 弹出层标题
      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: {},
      open1: false,
      open2: false,
      materialLoading: false,
      tempSelection: [],
      // 物料列表
      materialList: [],
      materialTotal: 0,
      // 查询参数
      queryMaterialParams: {
        pageNum: 1,
        pageSize: 10,
        vendorName: undefined,
        materialCode: undefined,
        materialName: undefined,
      },
      // 表单校验
      rules: {
        repairFormId: [
          { required: true, message: "报修单不能为空", trigger: "blur" }
        ],
        outTime: [
          { required: true, message: "出库时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物料出库列表 */
    getList() {
      this.loading = true;
      listMaterialPicking({ ...this.queryParams, repairFormId: this.repairFormId  }).then(response => {
        this.materialPickingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询物资供应商列表 */
    getVendorList() {
      listMaterialVendorAll().then(response => {
        this.materialVendorOpt = response.data;
      });
    },
    /** 打开物料列表 */
    openMaterialModel() {
      if (!this.form.repairerDeptId) {
        this.$modal.msgError("请选择报修单");
        return
      }
      this.open1 = true
      this.getMaterialList()
    },
    /** 搜索按钮操作 */
    handleMaterialQuery() {
      this.queryMaterialParams.pageNum = 1;
      this.getMaterialList();
    },
    /** 重置按钮操作 */
    resetMaterialQuery() {
      this.resetForm("queryMaterialForm");
      this.handleMaterialQuery();
    },
    /** 查询物资列表 */
    getMaterialList() {
      this.materialLoading = true;
      listMaterial({ ...this.queryMaterialParams, deptId: this.repairerDeptId }).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.id === row.id || item.materialId === row.id);
            this.$refs.selectionTable.toggleRowSelection(row, isSelected);
          });
        });
      })
    },
    // 入库明细删除
    handleRowDelete(row) {
      this.form.pickingInfoList = this.form.pickingInfoList.filter(item => item.id !== row.id);
    },
    // 入库数量变动
    collectNumberChange() {
      this.form.outMoney = this.form.pickingInfoList.reduce((sum, item) => {
        item.money = item.collectNumber * item.sellingPrice
        return sum + (item.collectNumber * item.sellingPrice);
      }, 0)
    },
    // 多选框选中数据
    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.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        repairFormId: undefined,
        repairNumber: undefined,
        outNumber: undefined,
        returnNumber: undefined,
        carId: undefined,
        plateNumber: undefined,
        outMoney: undefined,
        receiveUserId: undefined,
        receiveUserName: undefined,
        receiveTime: undefined,
        state: undefined,
        outTime: undefined,
        pickingInfoList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let isTrue = false
      this.ids = selection.map(item => {
        if (item.state !== 1) {
          isTrue = true
        }
        return item.id
      })
      if (selection.length > 0) {
        this.isTrue = isTrue
      }else {
        this.isTrue = true
      }
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({name: "materialPickingAdd", query:{
        repairFormId: this.repairFormId,
        repairNumber : this.repairNumber,
        carId : this.carId,
        plateNumber : this.plateNumber,
        clientName : this.clientName,
        repairerDeptId : this.repairerDeptId,
        repairerDeptName : this.repairerDeptName,
        repairerGroupName : this.repairerGroupName,
        isDelivery : this.isDelivery,
        flag : this.flag,
        outTime : formatDate(new Date().getTime()),
      }});
    },
    // 详情按钮
    handleDetail(row) {
      getMaterialPicking(row.id).then(response => {
        this.form = response.data;
        getRepairForm(response.data.repairFormId).then(res =>{
          this.loading = false;
          this.form.clientName = res.data.clientName
          this.form.repairerDeptId = res.data.repairerDeptId
          this.form.repairerDeptName = res.data.repairerDeptName
          this.form.repairerGroupName = res.data.repairerGroupName
          this.form.plateNumber = res.data.car.plateNumber
          this.form.carId = res.data.carId
          this.open2 = true;
          this.title = "物料出库详情";
        })
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      this.getVendorList()
      getMaterialPicking(id).then(response => {
        this.form = response.data;
        getRepairForm(response.data.repairFormId).then(res =>{
          this.loading = false;
          this.form.clientName = res.data.clientName
          this.form.repairerDeptId = res.data.repairerDeptId
          this.form.repairerDeptName = res.data.repairerDeptName
          this.form.repairerGroupName = res.data.repairerGroupName
          this.form.plateNumber = res.data.car.plateNumber
          this.form.carId = res.data.carId
          this.open = true;
          this.title = "修改物料出库";
        })
      });
    },
    /** 提交按钮 */
    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;
            });
          } else {
            addMaterialPicking(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 出库按钮操作 */
    handleConfirm(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认物料出库？').then(() => {
        this.loading = true;
        return confirmMaterialPicking(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("出库成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料出库编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delMaterialPicking(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
  }
};
</script>
