<template>
  <ele-modal :visible.sync="visible" :title="title" width="80vw" append-to-body @close="cancel"> 
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="90px"
      class="create-form"
    >
      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="编码:">
            <el-input :maxlength="20" v-model="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="来源编码:">
            <el-input :maxlength="20" v-model="form.unqualifiedSourceCode" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="数量:">
            <el-input
              :maxlength="20"
              v-model="form.unqualifiedQuantity"
              disabled
            />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="工艺路线:">
            <el-input
              @click.native="openVersion"
              clearable
              v-model="form.produceRoutingName"
            />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="工序:">
            <el-select
              style="width: 100%"
              v-model="form.produceTaskId"
              placeholder="请选择"
              clearable
              @change="produceTaskChange"
            >
              <el-option
                v-for="item in produceTaskList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="批次号:">
            <el-input :maxlength="20" v-model="form.batchNo" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-table :data="form.poList" border height="40vh">
        <el-table-column label="序号" align="center" width="60">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column label="产品名称" align="center" prop="productName">
        </el-table-column>
        <el-table-column label="产品编码" align="center" prop="productCode">
        </el-table-column>
        <el-table-column label="牌号" align="center" prop="brandNo">
        </el-table-column>
        <el-table-column label="刻码" align="center" prop="engravingCode">
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + scope.$index + '.engravingCode'"
            >
              <el-input
                v-model="scope.row.engravingCode"
                size="small"
                style="width: 100%"
                placeholder="输入刻码"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="型号" align="center" prop="model">
        </el-table-column> -->
        <el-table-column label="规格" align="center" prop="specification">
        </el-table-column>

        <el-table-column label="数量" align="center" prop="unqualifiedQuantity">
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + scope.$index + '.unqualifiedQuantity'"
              :rules="[
                {
                  required: true,
                  message: '请输入数量',
                  trigger: 'blur'
                },
                { validator: validatePass, trigger: 'change' }
              ]"
            >
              <el-input
                :disabled="!!scope.row.id"
                v-model.number="scope.row.unqualifiedQuantity"
                size="small"
                oninput="value=value.replace(/[^\d]/g,'')"
                style="width: 100%"
                placeholder="输入数量"
                @input="
                  inputNumber(scope.$index, scope.row.unqualifiedQuantity)
                "
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="工艺路线"
          align="center"
          prop="produceRoutingName"
        >
        </el-table-column>
        <el-table-column label="工序" align="center" prop="produceTaskName">
        </el-table-column>

        <el-table-column label="原因" align="center" prop="unqualifiedReason">
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + scope.$index + '.unqualifiedReason'"
              :rules="{
                required: true,
                message: '请输入原因',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="scope.row.unqualifiedReason"
                size="small"
                style="width: 100%"
                placeholder="输入原因"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="70">
          <template slot-scope="scope">
            <el-link
              type="danger"
              :underline="false"
              @click="handleDeleteItem(scope.$index, scope.row.id)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-product" @click="addEquipment">
        <i class="el-icon-circle-plus-outline"></i>
      </div>
    </el-form>
    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading">
        确定
      </el-button>
    </template>

    <!-- 选择产品 -->
    <EquipmentDialog ref="equipmentRefs" @choose="confirmChoose">
    </EquipmentDialog>
    <ProductionVersion
      ref="versionRefs"
      @changeProduct="changeProduct"
    ></ProductionVersion>
  </ele-modal>
</template>

<script>
import EquipmentDialog from '../components/EquipmentDialog.vue';
import ProductionVersion from '@/components/ProductionVersion/ProductionVersion.vue';
import { getProduceTaskList } from '@/api/aps';
import {
  unqualifiedProductsAdd,
  getDetail,
  deleteUnacceptedProductDetail
} from '@/api/unacceptedProduct/index';
export default {
  components: {
    EquipmentDialog,
    ProductionVersion
  },
  data() {
    return {
      validatePass: (rule, value, callback) => {
        if (!value) {
          callback(new Error('数量不能为0'));
        } else {
          callback();
        }
      },
      visible: false,
      loading: false,
      produceTaskList: [],
      form: {
        poList: [],
        code: '',
        unqualifiedSourceCode: '',
        unqualifiedSourceId: '',
      
        unqualifiedQuantity: '',
        type: '',
        status: null,
        reviewerId: null,
        reviewerName: '',
        createUserName: '',
        brandNo: '',
        produceRoutingId: '',
        produceRoutingName: '',
        produceTaskId: '',
        produceTaskName: '',
        batchNo: ''
      },
      // 表单验证规则
      rules: {
        deliveryTime: [
          { required: true, message: '请选择交付日期', trigger: 'change' }
        ]
      },

      title: '创建'
    };
  },

  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    }
  },
  created() {},
  methods: {
    open(row, type) {
      this.visible = true;
      if (type == 'add') {
        this.title = '创建';
        this.form = row;
        this.getProduceTaskList();
        return;
      }
      if (row) {
        this.title = '修改';
        this.detail(row);
      } else {
        this.title = '创建';
      }
    },
    //选择工艺路线
    openVersion() {
      this.$refs.versionRefs.open();
    },
    //工艺路线回调
    changeProduct(data) {
      this.form.produceRoutingId = data.id;
      this.form.produceRoutingName = data.name;
      this.form.produceTaskId = '';
      this.form.produceTaskName = '';
      this.getProduceTaskList();
    },
    async getProduceTaskList() {
      const res = await getProduceTaskList({
        isDetail: true,
        pageNum: 1,
        routingId: this.form.produceRoutingId,
        size: -1
      });
      this.produceTaskList = res.list;
    },
    produceTaskChange() {
      if (!this.form.produceTaskId) {
        return;
      }
      this.form.produceTaskName = this.produceTaskList.find(
        (item) => item.id == this.form.produceTaskId
      ).name;
      this.form.poList.forEach((item, index) => {
        this.$set(
          this.form.poList[index],
          'produceRoutingId',
          this.form.produceRoutingId
        );
        this.$set(
          this.form.poList[index],
          'produceRoutingName',
          this.form.produceRoutingName
        );
        this.$set(
          this.form.poList[index],
          'produceTaskId',
          this.form.produceTaskId
        );
        this.$set(
          this.form.poList[index],
          'produceTaskName',
          this.form.produceTaskName
        );
      });
    },

    detail(row) {
      getDetail(row.id).then((res) => {
        this.form = row;
        this.getProduceTaskList();
        this.form.poList = res;
      });
    },
    cancel() {
      this.form = {
        poList: [],
        code: '',
        workOrderId: '',
        productCode: '',
        productName: '',
        specifications: '',
        unqualifiedQuantity: '',
        type: '',
        status: null,
        reviewerId: null,
        reviewerName: '',
        createUserName: '',
        brandNo: '',
        produceRoutingId: '',
        produceRoutingName: '',
        produceTaskId: '',
        produceTaskName: '',
        batchNo: ''
      };
      this.$refs.form.clearValidate();
      this.visible = false;
    },
    // 删除产品
    handleDeleteItem(index, id) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancleButtonText: '取消',
        type: 'warning'
      })
        .then((res) => {
          if (id) {
            deleteUnacceptedProductDetail([id]).then((res) => {
              this.form.poList.splice(index, 1);
            });
          } else {
            this.form.poList.splice(index, 1);
          }
        })
        .catch(() => {});

      this.inputNumber();
    },
    addEquipment() {
      this.$refs.equipmentRefs.open();
    },
    /* 保存编辑 */
    save() {
      console.log(this.form.poList);
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        if (!this.form.poList.length) {
          return this.$message.warning('产品列表不能为空！');
        }
        for (let key in this.form) {
          if (key.includes('create')) {
            this.form[key] = '';
          }
        }
        this.form.poList.forEach((item) => {
          for (let key in item) {
            if (key.includes('create')) {
              item[key] = '';
            }
          }
        });
        this.loading = true;
        unqualifiedProductsAdd(this.form)
          .then((res) => {
            this.loading = false;
            this.$message.success('成功');
            this.cancel();
            this.$emit('refresh');
          })
          .catch((e) => {
            this.loading = false;
          });
      });
    },

    // 确定选择
    confirmChoose(data) {
      let list = [];
      list = data.map((item, index) => {
        if (item.productCode) {
          return item;
        } else {
          return {
            productCode: item.code,
            productName: item.name,
            // productUnitWeight: item.netWeight,
            // weightUnit: item.weightUnit,
            specification: item.specification,
            brandNo: item.brandNum,
            unqualifiedQuantity: '',
            unqualifiedReason: '',
            produceRoutingId: '',
            produceRoutingName: '',
            produceTaskId: '',
            produceTaskName: ''
          };
        }
      });

      this.form.poList = this.form.poList.concat(list);

      this.produceTaskChange();
      this.inputNumber();
    },

    inputNumber() {
      this.form.unqualifiedQuantity = 0;
      this.form.poList.forEach((item) => {
        this.form.unqualifiedQuantity += Number(item.unqualifiedQuantity) || 0;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.basic-details-title {
  margin: 10px 0;
}

.add-product {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 30px;
  color: #1890ff;
  margin: 10px 0;
  cursor: pointer;
}

.create-form .el-form-item {
  margin-bottom: 15px !important;
}
</style>
