<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="报修单号" prop="repairNumber">
        <el-input
          v-model="queryParams.repairNumber"
          placeholder="请输入报修单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库单号" prop="outNumber">
        <el-input
          v-model="queryParams.outNumber"
          placeholder="请输入出库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="plateNumber">
        <el-input
          v-model="queryParams.plateNumber"
          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"
          :disabled="multiple"
          @click="handleSettle"
          v-hasPermi="['business:settlementMaterial:add']"
        >结算</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</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="expand">
        <template slot-scope="props">
          <el-table :data="props.row.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="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>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库单号" align="center" prop="outNumber" width="150"/>
      <el-table-column label="报修单号" align="center" prop="repairNumber" />
      <el-table-column label="车牌号" align="center" prop="plateNumber" />
      <el-table-column label="供应商" align="center" prop="vendorName" show-overflow-tooltip/>
      <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="120">
        <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="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.repair_form_settlement_state" :value="scope.row.settlementState" />
        </template>
      </el-table-column>
      <el-table-column label="出库时间" align="center" prop="outTime" width="120">
        <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"
                     @click="handleSettlement(scope.row)" v-hasPermi="['business:settlementMaterial:add']">结算</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-scrollbar style="height: 75vh;">
        <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="6">
              <el-form-item label="结算方式" prop="settlementType">
                <el-select v-model="form.settlementType" style="width: 100%" placeholder="请选择结算方式">
                  <el-option v-for="item in dict.type.settlement_material_type" :key="item.value" :value="item.value" :label="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结算时间" prop="settlementTime">
                <el-date-picker clearable
                                v-model="form.settlementTime"
                                style="width: 100%"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="请选择结算时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结算单号" prop="settlementNumber">
                <el-input v-model="form.settlementNumber" disabled placeholder="自动生成" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商" prop="vendorId">
                <el-select v-model="form.vendorId" placeholder="请选择供应商" disabled 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-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="结算名称" prop="settlementName">
                <el-input v-model="form.settlementName" placeholder="请输入结算名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结算金额" prop="settlementMoney">
                <el-input-number v-model="form.settlementMoney" disabled :min="0" placeholder="请输入结算金额" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="操作人" prop="createBy">
                <el-input v-model="form.createBy" placeholder="请输入操作人" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <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-col :span="6">-->
<!--              <el-form-item label="状态" prop="state">-->
<!--                <el-input v-model="form.state" :min="0" placeholder="请选择状态" style="width: 100%" />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
          </el-row>
        </el-form>
        <span style="font-weight: bold; font-size: 18px">结算明细</span>
        <el-divider />
        <el-table :data="pickingSelection" :default-expand-all="true">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table :data="props.row.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="settlementNumber" width="120px" />
                <el-table-column label="单价" align="center" prop="settlementPrice" width="120px">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.settlementPrice" filterable allow-create @change="settlementPriceChange(scope.row)">
                      <el-option v-for="item in scope.row.priceList" :key="item" :value="item" :label="item" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="金额" align="center" prop="settlementMoney" width="120px" />
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="出库单号" align="center" prop="outNumber" />
          <el-table-column label="报修单号" align="center" prop="repairNumber" />
          <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="120">
            <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="120">
            <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-delete" @click="handleRowDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <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="物料出库详情" :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.vendorName}}</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" width="80px">
          <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" width="100px"/>
        <el-table-column label="参考价" align="center" prop="referencePrice" width="100px"/>
        <el-table-column label="销售价" align="center" prop="sellingPrice" width="100px"/>
        <el-table-column label="领料数量" align="center" prop="collectNumber" width="100px" />
        <el-table-column label="入库单价" align="center" prop="price" width="100px" />
        <el-table-column label="领料金额" align="center" prop="money" width="100px" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { getMaterialPicking, listPickingAndInfoList } from '@/api/business/materialPicking'
import { getRepairForm } from '@/api/business/repairForm'
import {listMaterialVendor, listMaterialVendorAll} from '@/api/business/materialVendor'
import { addSettlementMaterial } from '@/api/business/settlementMaterial'
import { formatDate } from '@/utils'

export default {
  name: "MaterialPicking",
  dicts: ['sys_is_enable', 'picking_state', 'settlement_material_type', 'repair_form_settlement_state','material_unit'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      isTrue: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料出库表格数据
      materialPickingList: [],
      materialVendorOpt: [],
      // 已勾选出库单
      pickingSelection: [],
      // 供应商ID
      vendorId: undefined,
      // 弹出层标题
      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: [2],
        settlementState: 1,
        type: 1,
        outTime: undefined,
      },
      // 表单参数
      form: {},
      open2: false,
      materialLoading: false,
      tempSelection: [],
      // 物料列表
      materialList: [],
      materialTotal: 0,
      // 查询参数
      queryMaterialParams: {
        pageNum: 1,
        pageSize: 10,
        vendorName: undefined,
        materialCode: undefined,
        materialName: undefined,
      },
      // 表单校验
      rules: {
        settlementName: [
          { required: true, message: "结算名称不能为空", trigger: "blur" }
        ],
        settlementTime: [
          { required: true, message: "结算时间不能为空", trigger: "blur" }
        ],
        vendorId: [
          { required: true, message: "厂商不能为空", trigger: "blur" }
        ],
        settlementType: [
          { required: true, message: "结算方式不能为空", trigger: "blur" }
        ],
        settlementMoney: [
          { required: true, message: "结算金额不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getVendorList()
  },
  methods: {
    /** 查询物料出库列表 */
    getList() {
      this.loading = true;
      listPickingAndInfoList(this.queryParams).then(response => {
        this.materialPickingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询物资供应商列表 */
    getVendorList() {
      listMaterialVendorAll().then(response => {
        this.materialVendorOpt = response.data;
      });
    },
    // 单价变动
    settlementPriceChange(row) {
      row.settlementMoney = row.settlementNumber * row.settlementPrice
      let money = 0
      this.pickingSelection.forEach(item =>{
        item.pickingInfoList.forEach(info =>{
          money = money + info.settlementMoney
        })
      })
      this.form.settlementMoney = money
    },
    // 行删除
    handleRowDelete(row) {
      this.pickingSelection = this.pickingSelection.filter(item => item.id !== row.id);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        settlementNumber: undefined,
        settlementName: undefined,
        settlementTime: formatDate(new Date().getTime()),
        vendorId: undefined,
        settlementType: undefined,
        settlementMoney: 0,
        state: undefined,
        createBy: this.$store.state.user.userInfo.userName,
        createTime: formatDate(new Date().getTime()),
        pickingInfoList: []
      };
      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)
      // 如果没有选中任何项，直接禁用按钮
      if (selection.length === 0) {
        this.multiple = true; // 禁用按钮
        this.vendorId = ''; // 清空 form.vendorId
        return;
      }
      // 如果选中了数据，检查所有项的 vendorId 是否一致
      const firstVendorId = selection[0].vendorId;
      const allSameVendor = selection.every(item => item.vendorId === firstVendorId);
      if (allSameVendor) {
        this.vendorId = firstVendorId; // 赋值给 form.vendorId
        this.multiple = false; // 允许操作（不禁用按钮）
      } else {
        this.multiple = true; // 如果 vendorId 不一致，禁用按钮
        this.vendorId = ''; // 可以清空，或者保持上一次的值（按需调整）
      }
      this.pickingSelection = selection.map(item =>{
        item.pickingInfoList.forEach(info =>{
          info.settlementNumber = info.collectNumber
          info.settlementMoney = 0
        })
        return item
      })
    },
    /** 结算按钮操作 */
    handleSettle() {
      this.reset();
      this.form.vendorId = this.vendorId;
      this.open = true;
      this.title = "出库单结算";
      this.getVendorList()
    },
    // 详情按钮
    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 = "物料出库详情";
        })
      });
    },
    // 结算按钮
    handleSettlement(row) {
      this.pickingSelection = []
      let pickingInfoList = row.pickingInfoList
      pickingInfoList.forEach(item =>{
        item.settlementNumber = item.collectNumber
        item.settlementMoney = 0
      })
      this.pickingSelection.push(row)
      this.reset();
      this.form.vendorId = row.vendorId;
      this.open = true;
      this.title = "出库单结算";
      this.getVendorList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      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 = "修改物料出库";
          this.getRepairList()
        })
      });
    },
    /** 提交按钮 */
    submitForm(state) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.pickingSelection.length === 0) {
            this.$modal.msgError("结算明细不能空位")
            return
          }
          let isNull = false
          this.pickingSelection.forEach(item =>{
            item.pickingInfoList.forEach(info =>{
              if (!info.settlementPrice) {
                isNull = true
              }
            })
          })
          if (isNull) {
            this.$modal.msgError("结算单价不能为空")
            return
          }
          let pickingInfoList = []
          this.pickingSelection.map(item => {
            pickingInfoList.push(...item.pickingInfoList)
          })
          console.log('pickingInfoList', pickingInfoList)
          this.form.infoList = pickingInfoList.map(item => {
            return {
              pickingId: item.pickingId,
              pickingInfoId: item.id,
              materialId: item.materialId,
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialSpecifications: item.materialSpecifications,
              materialTypeId: item.materialTypeId,
              materialUnit: item.materialUnit,
              vendorId: item.vendorId,
              vendorName: item.vendorName,
              warehouseLocationId: item.warehouseLocationId,
              warehouseLocationType: item.warehouseLocationType,
              materialWarrantyPeriod: item.materialWarrantyPeriod,
              materialTypeName: item.materialTypeName,
              settlementNumber: item.settlementNumber,
              settlementPrice: item.settlementPrice,
              settlementMoney: item.settlementMoney
            }
          })
          console.log('form', this.form)
          addSettlementMaterial(this.form).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/materialPicking/export', {
        ...this.queryParams,
        ids: this.ids
      }, `供应商铺货结算.xlsx`)
    }
  }
};
</script>
