<template>
  <el-dialog
    title="新建"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="80%"
  >
    <div>
      <el-form :model="productForm" ref="productForm">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="回收单号" prop="code" label-width="90px">
              <el-input v-model="productForm.code" disabled=""></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="回收单名称" prop="name" label-width="90px">
              <el-input v-model="productForm.name"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-button type="primary" @click="categorySelect"
              >选择物料</el-button
            >
          </el-col>
        </el-row>
      </el-form>

      <div v-for="(item, idx) in materialList" :key="idx">
        <el-form
          :ref="`form22${idx}`"
          :model="{ pickList: item }"
          :rules="tableRules"
          size="mini"
          label-position="left"
        >
          <div class="tableZ_box">
            <div class="row">
              <div class="col">
                <div class="name">物料编码</div>
                <div class="content">{{ item.code }}</div>
              </div>
              <div class="col">
                <div class="name">物料名称</div>
                <div class="content">{{ item.name }}</div>
              </div>

              <div class="col">
                <div class="name">型号</div>
                <div class="content">{{ item.modelType }}</div>
              </div>

              <div class="col">
                <div class="name">规格</div>
                <div class="content">{{ item.specification }}</div>
              </div>

              <div class="col">
                <div class="name">牌号</div>
                <div class="content">{{ item.brandNum }}</div>
              </div>

              <div class="col">
                <div class="name">数量</div>
                <div class="content content_num">
                  <el-input v-model="productWeight"></el-input>
                  <div style="margin-left: 8px"> {{ item.measuringUnit }}</div>
                </div>
              </div>
            </div>
          </div>

          <div style="margin: 6px">
            <el-button type="primary" size="mini" @click="handWorkOrder()"
              >新增</el-button
            >
          </div>

          <div v-if="item.detailList && item.detailList.length > 0">
            <el-table
              :ref="`form222${idx}`"
              class="table_content"
              :max-height="300"
              :data="item.detailList"
              tooltip-effect="dark"
              style="width: 100%"
              stripe
              border
            >
              <el-table-column label="序号" type="index" width="60">
                <template slot-scope="{ row, $index }">
                  {{ $index }}
                </template>
              </el-table-column>

              <el-table-column label="编码" prop="categoryCode">
              </el-table-column>
              <el-table-column label="工单编码" prop="code"> </el-table-column>
              <el-table-column label="名称" prop="categoryName">
              </el-table-column>
              <el-table-column label="型号" prop="modelType"> </el-table-column>
              <el-table-column label="规格" prop="specification">
              </el-table-column>

              <el-table-column label="工序" prop="taskName"> </el-table-column>

              <el-table-column label="合格品数量" prop="formedNum">
              </el-table-column>
              <el-table-column label="不合格品数量" prop="notFormedNum">
              </el-table-column>

              <el-table-column label="回收" prop="quantity" width="180px">
                <template slot-scope="{ $index, row }">
                  <el-input v-model="row.quantity" size="mini">
                    <template slot="append">{{ row.unit }}</template>
                  </el-input>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" width="100px">
                <template slot-scope="{ $index, row }">
                  <el-link type="danger" @click="removeItem(idx, $index)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
    </div>

    <template slot="footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button size="mini" type="primary" @click="save()">确 定</el-button>
    </template>

    <ProductModal ref="productRefs" @changeProduct="determineChoose" />

    <produceOrder
      v-if="orderShow"
      @close="orderShow = false"
      @workSelect="workSelect"
    ></produceOrder>
  </el-dialog>
</template>

<script>
  import { getCode } from '@/api/produce/workOrder';
  import { listDisposeBy, disposeSave } from '@/api/byProduct/index';
  import ProductModal from './ProductModal.vue';
  import produceOrder from '@/views/pick/pickApply/components/produceOrder.vue';
  export default {
    components: {
      ProductModal,
      produceOrder
    },
    data() {
      return {
        visible: true,

        productForm: {
          code: null,
          name: null
        },

        materialList: [],

        tableRules: {},

        productWeight: null,

        orderShow: false,

        newWeightList: []
      };
    },

    created() {
      this.getOrderCode();
    },

    methods: {
      handleClose() {
        this.$emit('close');
      },

      async getOrderCode() {
        this.productForm.code = await getCode('dispose_code');
      },

      save() {
        let param = {
          detailList: this.materialList[0].detailList,
          ...this.productForm,
          categoryId: this.materialList[0].id,
          quantity: this.productWeight
        };
        console.log(param);

        disposeSave(param).then((res) => {
          this.$emit('close', true);
        });
      },

      categorySelect() {
        this.$refs.productRefs.open({}, '选择物料', '1', null);
      },

      determineChoose(title, row, idx) {
        if (title == '选择物料') {
          console.log(row, idx);
          this.materialList[0] = row;

          this.$forceUpdate();
        }
      },

      handWorkOrder() {
        if (!this.productWeight) {
          return this.$message.error('请输入数量');
        }

        this.orderShow = true;
      },

      workSelect(ids, taskId) {
        console.log(ids, taskId);

        let param = {
          categoryId: this.materialList[0].id,
          taskId: taskId,
          workOrderIds: ids
        };
        listDisposeBy(param).then((res) => {
          this.newWeightList = res;
          this.WeightListFN();

          this.$forceUpdate();
        });

        this.orderShow = false;
      },

      WeightListFN() {
        let _totalNum = 0;
        let _oneWeight = 0;
        let _arr = [];

        // 使用reduce方法求和
        _totalNum = this.newWeightList.reduce((acc, item) => {
          return acc + item.formedNum + item.notFormedNum;
        }, 0);

        _oneWeight = this.productWeight / _totalNum;

        this.newWeightList.forEach((item) => {
          _arr.push({
            ...item,
            quantity: (item.formedNum + item.notFormedNum) * _oneWeight
          });
        });

        this.$set(this.materialList[0], 'detailList', _arr);
      },

      removeItem(idx, index) {
        this.materialList[idx].detailList.splice(index, 1);
      }
    }
  };
</script>

<style lang="scss" scoped>
  .content_num {
    display: flex;
    align-items: center;
    padding: 2px;
    --input-background-color: #f0f8f2;
  }

  .table_content {
    margin-bottom: 10px;
  }

  .tableZ_box {
    border: 1px solid #e3e5e5;
    margin: 6px 0;

    &:last-child {
      border-bottom: none;
    }

    .row {
      width: 100%;
      display: flex;
    }

    .col {
      width: 16.666%;
      display: flex;
      align-items: center;
      min-width: 200px;
      min-height: 32px;
      border-bottom: 1px solid #e3e5e5;
      border-right: 1px solid #e3e5e5;

      &:last-child {
        border-right: none;
      }

      .name {
        display: flex;
        align-items: center;
        padding: 4px;
        width: 80px;
        height: 100%;
        background-color: #ededed;
        color: #000;
      }

      .content {
        padding: 4px 6px;
        color: #000;
      }
    }

    .pd6 {
      padding: 0 6px;
    }
  }
</style>

<style>
  :v-deep .el-form-item__error {
    bottom: -6px !important;
  }
</style>
