<template>
  <span>
    <el-select v-model="selected" :placeholder="placeholder" :disabled="disabled" filterable clearable
      @change="onChange" :value-key="'productId'">
      <template #empty>
        <el-button v-if="canAdd" @click="add" icon="el-icon-plus">未搜索到半成品，点击添加</el-button>
        <div v-else style="padding: 10px;">未搜索到半成品</div>
      </template>
      <el-option v-for="item in productOptions" :key="item.productId"
        :label="`${item.productName}（${item.productCode}）`" :value="item.productId">
        <div class="option-label">
          <span class="product-name">{{ item.productName }}</span>
          <span class="product-code">{{ item.productCode }}</span>
        </div>
      </el-option>
    </el-select>

    <el-dialog v-if="canAdd" :visible.sync="addDialogVisible" title="添加半成品" width="700px" append-to-body>
      <el-steps align-center :active="activeStep" finish-status="success">
        <!-- 新增半成品的步骤 -->
        <el-step title="创建半成品"></el-step>
        <!-- 创建BOM的步骤 -->
        <el-step title="填写BOM信息"></el-step>
      </el-steps>

      <el-form ref="form" v-if="activeStep === 0" :model="addForm" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="半成品编号" prop="productCode">
              <el-input v-model="addForm.productCode" placeholder="请输入半成品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="半成品名称" prop="productName">
              <el-input v-model="addForm.productName" placeholder="请输入半成品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="owner">
              <el-input v-model="addForm.owner" :multiple="false" placeholder="请填写负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit">
              <el-input v-model="addForm.unit" placeholder="请输入计量单位" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="activeStep === 0" slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">创建半成品</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <BomPanel v-if="activeStep === 1" :id="bomId" :itemId="itemId" :type="addForm.type" @addBom="handleBom" />
    </el-dialog>
  </span>
</template>

<script>
import { listProduct, addProduct } from '@/api/wms/product';
import BomPanel from '../BomPanel/index.vue';

export default {
  name: 'ProductSelect',
  props: {
    value: [String, null],
    disabled: Boolean,
    placeholder: {
      type: String,
      default: '请选择半成品'
    },
    canAdd: {
      default: false,
      type: Boolean
    },
  },
  components: {
    BomPanel
  },
  data() {
    return {
      productOptions: [],
      selected: this.value,
      addForm: {
        productCode: undefined,
        productName: undefined,
        owner: undefined,
        unit: undefined,
        type: 'semi'
      },
      addDialogVisible: false,
      rules: {
        productCode: [
          { required: true, message: "半成品编号不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "半成品名称不能为空", trigger: "blur" }
        ],
        owner: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
      },
      buttonLoading: false,
      itemId: undefined,
      activeStep: 0,
      bomId: undefined,
    };
  },
  watch: {
    value(val) {
      this.selected = val;
    },
    selected(val) {
      this.$emit('input', val);
    }
  },
  created() {
    this.getProductOptions();
  },
  methods: {
    getProductOptions() {
      listProduct({ pageNum: 1, pageSize: 1000, type: 'semi' }).then(res => {
        this.productOptions = res.rows || [];
      });
    },
    onChange(val) {
      // 通过val找到item
      const product = this.productOptions.find(p => p.productId === val);
      this.$emit('change', product);
    },
    add() {
      this.addDialogVisible = true;
      this.addForm = {
        productCode: undefined,
        productName: undefined,
        owner: undefined,
        unit: undefined,
        type: 'semi'
      };
      this.bomId = undefined;
      this.itemId = undefined;
    },
    handleBom(bom) {
      this.bomId = bom.bomId;
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          // console.log(this.addForm);
          addProduct(this.addForm).then(res => {
            this.$modal && this.$modal.msgSuccess("创建半成品成功");
            this.getProductOptions();
            console.log(res);
            this.itemId = res.productId;
            this.$emit('input', res.productId);
            this.activeStep = 1;
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    cancel() {
      this.addDialogVisible = false;
      this.addForm = {
        productCode: undefined,
        productName: undefined,
        owner: undefined,
        unit: undefined,
        type: 'semi'
      };
    }
  }
};
</script>

<style scoped>
.option-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-name {
  font-size: 14px;
  color: #333;
}

.product-code {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}
</style>
