<template>
  <div>
    <header-title title="物料清单"></header-title>

    <ele-pro-table
      ref="table"
      row-key="id"
      :columns="materialColumns"
      :datasource="materialList"
      cache-key="prenatal-examination-material-list-table-2511031522"
      autoAmendPage
      :needPage="false"
      @refresh="$emit('refresh', 'material')"
    >
      <template v-slot:toolbar>
        <el-button type="primary" @click="openMaterialModal"
          >添加物料</el-button
        >
      </template>

      <template v-slot:selectColumn="{ row }">
        <el-checkbox
          v-model="row.selected"
          @change="selectedChange(row)"
        ></el-checkbox>
      </template>
    </ele-pro-table>

    <header-title title="产出清单" style="margin-top: 20px"></header-title>

    <ele-pro-table
      ref="table"
      row-key="id"
      :columns="outputDetailsColumns"
      :datasource="localOutputDetails"
      cache-key="prenatal-examination-output-list-table-2511031523"
      autoAmendPage
      :needPage="false"
      @refresh="$emit('refresh', 'output')"
    >
      <template v-slot:reportQuantity="{ row }">
        <el-input-number
          size="small"
          v-model.number="row.reportQuantity"
          controls-position="right"
          :min="0"
          :max="row.feedQuantity"
        ></el-input-number>
      </template>
      <template v-slot:qualifiedQuantity="{ row }">
        <el-input-number
          size="small"
          v-model.number="row.qualifiedQuantity"
          controls-position="right"
          :min="0"
          :max="qualifiedQuantityMax(row)"
        ></el-input-number>
      </template>
      <template v-slot:noQualifiedQuantity="{ row }">
        <el-input-number
          size="small"
          v-model.number="row.noQualifiedQuantity"
          controls-position="right"
          :min="0"
          :max="noQualifiedQuantityMax(row)"
        ></el-input-number>
      </template>
      <template v-slot:msg="{ row }">
        <el-input
          v-model="row.msg"
          type="textarea"
          rows="1"
          autosize
        ></el-input>
      </template>
    </ele-pro-table>

    <materialModal ref="materialModalRef" @confirm="materialConfirm" />
  </div>
</template>

<script>
  import materialModal from './materialModal.vue';
  import {
    getMaterialQuotaInfo,
    getCategoryAndLevelByCategoryId
  } from '@/api/producetaskrecordrulesrecord/index';

  export default {
    components: {
      materialModal
    },
    props: {
      // 物料明细
      pickDetails: {
        type: Array,
        default: () => []
      },
      // 本次产出明细
      outputDetails: {
        type: Array,
        default: () => []
      },
      // 上到工序产出明细
      preOutputDetails: {
        type: Array,
        default: () => []
      },
      // 工单id
      workOrderId: {
        type: [String, Number],
        required: true
      },
      // 规则id
      ruleId: {
        type: [String, Number],
        required: true
      },
      // 工序id
      produceTaskId: {
        type: [String, Number],
        required: true
      },
      // BOM产品分类id
      bomCategoryId: {
        type: [String, Number],
        required: true
      },
      // 产出类型 1-物料本身 2-在制品 3-BOM标准产出
      outputType: {
        type: [Number],
        required: true
      },
      // 产品分类id
      categoryId: {
        type: [String, Number],
        required: false
      }
    },
    watch: {
      pickDetails: {
        handler(newVal) {
          this.localPickDetails = JSON.parse(JSON.stringify(newVal));
        },
        deep: true
      },
      outputDetails: {
        handler(newVal) {
          this.localOutputDetails = JSON.parse(JSON.stringify(newVal));
        },
        deep: true
      },
      bomCategoryId: {
        handler() {
          this.getMaterialQuotaInfo();
        }
      },
      produceTaskId: {
        handler() {
          this.getMaterialQuotaInfo();
        }
      },
      outputType: {
        handler() {
          // 重置产出明细
          this.localOutputDetails = [];

          // 根据不同的类型，重置物料明细
          if (this.outputType == 1) {
            this.$emit('update:outputDetails', this.localOutputDetails);
            // 1-物料本身
          } else if (this.outputType == 2) {
            // 2-在制品
            this.getCategoryAndLevelByCategoryId();
          } else {
            // 3 BOM标准产出
            this.getMaterialQuotaInfo();
          }
        }
      }
    },
    computed: {
      // 物料清单（包含上到工序产出明细）
      materialList() {
        return [...this.preOutputDetails, ...this.localPickDetails];
      },
      // 物料清单表头
      materialColumns() {
        const list = [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center'
          },
          {
            label: '类型',
            prop: 'categoryLevelNamePath',
            minWidth: 120
          },
          {
            label: '编码',
            prop: 'categoryCode',
            minWidth: 120
          },
          {
            label: '名称',
            prop: 'categoryName',
            minWidth: 120
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specifications',
            label: '规格',
            align: 'center',
            width: 160,
            showOverflowTooltip: true
          },
          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center'
          },
          {
            label: '工序名称',
            prop: 'produceTaskName',
            minWidth: 120
          },
          {
            label: '数量',
            prop: 'feedQuantity',
            minWidth: 120,
            formatter: (row) => {
              return (row.quantity || '') + (row.unit || '');
            }
          }
        ];
        if (this.outputType == 1) {
          list.push({
            prop: '',
            label: '选择',
            slot: 'selectColumn',
            align: 'center',
            fixed: 'right'
          });
        }
        return list;
      }
    },

    data() {
      return {
        localPickDetails: JSON.parse(JSON.stringify(this.pickDetails)),
        localOutputDetails: JSON.parse(JSON.stringify(this.outputDetails)),
        materialQuotaInfo: null,
        // 产出清单表头
        outputDetailsColumns: [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center'
          },
          {
            label: '类型',
            prop: 'categoryLevelNamePath',
            minWidth: 120
          },
          {
            label: '编码',
            prop: 'categoryCode',
            minWidth: 120
          },
          {
            label: '名称',
            prop: 'categoryName',
            minWidth: 120
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specifications',
            label: '规格',
            align: 'center',
            width: 160,
            showOverflowTooltip: true
          },
          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center'
          },
          {
            label: '工序名称',
            prop: 'produceTaskName',
            minWidth: 120
          },
          {
            label: '当次报工数量',
            prop: 'reportQuantity',
            minWidth: 160,
            slot: 'reportQuantity',
            formatter: (row) => {
              return (
                (row.reportQuantity == null ? '' : row.unit) +
                (row.feedUnit || '')
              );
            }
          },
          {
            label: '当次合格数量',
            prop: 'qualifiedQuantity',
            minWidth: 160,
            slot: 'qualifiedQuantity',
            formatter: (row) => {
              return (
                (row.qualifiedQuantity == null ? '' : row.unit) +
                (row.feedUnit || '')
              );
            }
          },
          {
            label: '当次不合格数量',
            prop: 'noQualifiedQuantity',
            minWidth: 160,
            slot: 'noQualifiedQuantity',
            formatter: (row) => {
              return (row.noQualifiedQuantity || 0) + (row.unit || '');
            }
          },
          {
            label: '不合格原因',
            prop: 'msg',
            minWidth: 160,
            slot: 'msg'
          },
          {
            label: '已报工数量',
            prop: 'sumReportQuantity',
            minWidth: 120,
            formatter(row) {
              return (row.sumReportQuantity || 0) + row.unit;
            }
          },
          {
            label: '合格总数',
            prop: 'sumQualifiedQuantity',
            minWidth: 120,
            formatter(row) {
              return (row.sumQualifiedQuantity || 0) + (row.unit || '');
            }
          },
          {
            label: '不合格总数',
            prop: 'sumNoQualifiedQuantity',
            minWidth: 120,
            formatter(row) {
              return (row.sumNoQualifiedQuantity || 0) + (row.unit || '');
            }
          }
        ]
      };
    },
    mounted() {
      if (this.outputType == 2) {
        this.getCategoryAndLevelByCategoryId();
      }
      if (this.outputType == 3) {
        this.getMaterialQuotaInfo();
      }
    },
    methods: {
      // 选择物料
      openMaterialModal() {
        this.$refs.materialModalRef.open(
          {
            workOrderId: this.workOrderId,
            ruleId: this.ruleId,
            produceTaskId: this.produceTaskId
          },
          []
        );
      },
      materialConfirm(data) {
        // 选择物料后添加
        console.log('data', data);

        data.forEach((newItem) => {
          const index = this.localPickDetails.findIndex(
            (item) =>
              item.categoryCode === newItem.categoryCode &&
              item.produceTaskInstanceId === newItem.produceTaskInstanceId
          );
          if (index !== -1) {
            // 存在则替换数量
            this.localPickDetails[index].quantity = newItem.quantity;
          } else {
            // 不存在则添加
            this.localPickDetails.push({ ...newItem });
          }
        });

        this.$emit('update:pickDetails', this.localPickDetails);
      },
      // 获取bom的产出
      async getMaterialQuotaInfo() {
        if (this.bomCategoryId && this.produceTaskId) {
          const data = await getMaterialQuotaInfo(
            this.bomCategoryId,
            this.produceTaskId
          );
          console.log('this.materialQuotaInfo', data);
          if (!data.standardOutput) {
            return this.$message.warning('未配置标准产出物料');
          }
          // 赋值产出
          this.localOutputDetails = [
            {
              ...data.standardOutput,
              reportQuantity: 0,
              qualifiedQuantity: 0,
              noQualifiedQuantity: 0,
              msg: '',
              sumReportQuantity: 0,
              sumQualifiedQuantity: 0,
              sumNoQualifiedQuantity: 0
            }
          ];
          this.$emit('update:outputDetails', this.localOutputDetails);
          console.log('this.localOutputDetails', this.localOutputDetails);
        }
      },
      // qualifiedQuantityMax 最大合格数量
      qualifiedQuantityMax(row) {
        return row.reportQuantity - row.noQualifiedQuantity;
      },
      noQualifiedQuantityMax(row) {
        return row.reportQuantity - row.qualifiedQuantity;
      },
      selectedChange(row) {
        console.log('row', row);

        if (row.selected) {
          // 判断是否存在
          const index = this.localOutputDetails.findIndex(
            (item) =>
              item.categoryId === row.categoryId &&
              item.produceTaskInstanceId === row.produceTaskInstanceId
          );

          if (index === -1) {
            // 不存在则添加
            this.localOutputDetails.push({
              ...row,
              reportQuantity: 0,
              qualifiedQuantity: 0,
              noQualifiedQuantity: 0,
              msg: '',
              sumReportQuantity: 0,
              sumQualifiedQuantity: 0,
              sumNoQualifiedQuantity: 0
            });
          } else {
            this.$message.warning('该物料已存在于产出清单中');
          }

          this.$emit('update:outputDetails', this.localOutputDetails);
        }
      },
      // getCategoryAndLevelByCategoryId 获取产品
      async getCategoryAndLevelByCategoryId() {
        const data = await getCategoryAndLevelByCategoryId(this.categoryId);
        this.localOutputDetails = [
          {
            ...data,
            reportQuantity: 0,
            qualifiedQuantity: 0,
            noQualifiedQuantity: 0,
            msg: '',
            sumReportQuantity: 0,
            sumQualifiedQuantity: 0,
            sumNoQualifiedQuantity: 0
          }
        ];
        this.$emit('update:outputDetails', this.localOutputDetails);
        console.log('this.localOutputDetails', this.localOutputDetails);
      }
    }
  };
</script>

<style></style>
