<template>
  <div>
    <el-dialog
      top="3vh"
      title="新建物品"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose"
      :append-to-body="true"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
      >
        <div class="main">
          <div class="left">
            <el-card class="box-card">
              <el-form-item label="物品类别" prop="categoryLevelId">
                <el-select
                  v-model="formData.categoryLevelId"
                  @change="chooseItem"
                >
                  <el-option
                    v-for="(item, index) in typeList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="分类" prop="categoryLevelPathId">
                <el-cascader
                  @change="shooteCategory"
                  v-model="formData.categoryLevelPathId"
                  :options="classList"
                  :props="{ value: 'id', label: 'name' }"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="物品编码" prop="code">
                <el-input placeholder="请输入" v-model="formData.code">
                  <template slot="prepend">{{ formData.code1 }}</template>
                </el-input>
              </el-form-item>
              <el-form-item label="物品名称" prop="name">
                <el-input placeholder="请输入" v-model="formData.name">
                </el-input>
              </el-form-item>
              <el-form-item label="计量单位" prop="unit">
                <div class="dj">
                  <el-input placeholder="请输入" v-model="formData.unit">
                  </el-input>
                  <DictSelection
                    dictName="计量单位"
                    clearable
                    filterable
                    v-model="formData.measuringUnit"
                  />
                </div>
              </el-form-item>
              <el-form-item label="包装单位" prop="packingUnit">
                <el-input placeholder="请输入" v-model="formData.packingUnit">
                </el-input>
              </el-form-item>
              <el-form-item label="参考单价">
                <div class="dj">
                  <el-input-number
                    style="width: 300px"
                    v-model="formData.price"
                    :min="1"
                    placeholder="请输入"
                  ></el-input-number>
                  <DictSelection
                    dictName="金额单位"
                    clearable
                    filterable
                    v-model="formData.priceUnit"
                  >
                  </DictSelection>
                </div>
              </el-form-item>
              <el-form-item label="保质期">
                <div class="dj">
                  <el-input-number
                    style="width: 300px"
                    v-model="formData.warrantyPeriod"
                    :min="1"
                    placeholder="请输入"
                  ></el-input-number>

                  <DictSelection
                    dictName="时间单位"
                    clearable
                    filterable
                    v-model="formData.warrantyPeriodUnit"
                  >
                  </DictSelection>
                </div>
              </el-form-item>
              <el-form-item label="安全库存" prop="secureInventory">
                <el-input
                  placeholder="请输入"
                  v-model="formData.secureInventory"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="盘点模式" prop="inventoryMode">
                <el-radio v-model="formData.inventoryMode" label="1"
                  >逐个盘点</el-radio
                >
                <el-radio v-model="formData.inventoryMode" label="2"
                  >批量盘点</el-radio
                >
              </el-form-item>
              <el-form-item label="允许拆包">
                <el-switch v-model="formData.isUnpack" active-color="#13ce66">
                </el-switch>
              </el-form-item>
              <el-form-item label="描述">
                <el-input
                  type="textarea"
                  placeholder="请输入"
                  v-model="formData.description"
                >
                </el-input>
              </el-form-item>
            </el-card>
          </div>
          <div class="right">
            <el-card class="box-card">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="规格">
                    <el-input
                      placeholder="请输入"
                      v-model="formData.specification"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="型号">
                    <el-input placeholder="请输入" v-model="formData.modelType">
                    </el-input>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <el-form-item label="标准产能">
                    <el-input placeholder="请输入" v-model="formData.cn">
                      <span slot="append">/小时</span>
                    </el-input>
                  </el-form-item>
                </el-col> -->
              </el-row>
              <div class="dashed-line"></div>
              <div class="production-device">
                <productionDevice
                  ref="productionDeviceRef"
                  :categoryLevelId="formData.categoryLevelId"
                />
              </div>
            </el-card>
          </div>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getTreeByPid } from '@/api/classifyManage';
  import {
    informationAdd,
    getOrderNo
  } from '@/api/classifyManage/itemInformation';

  import productionDevice from './production-device.vue';
  export default {
    components: { productionDevice },
    data() {
      return {
        dialogVisible: false,
        formData: {
          categoryLevelId: '',
          isUnpack: true,
          inventoryMode: '2',
          warrantyPeriodUnit: 'minute',
          priceUnit: 'yuan'
        },
        rules: {
          categoryLevelId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          warrantyPeriod: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          warrantyPeriodUnit: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          inventoryMode: [
            { required: true, message: '请选择', trigger: 'change' }
          ],

          name: [{ required: true, message: '请输入物品名称', trigger: 'blur' }]
        },
        classList: [],

        typeList: [],

        // 提交状态
        loading: false
      };
    },
    methods: {
      submit() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.loading = true;
            let newFormData = {
              ...this.formData,
              categoryLevelPathId: this.formData.categoryLevelPathId.pop(),
              categoryLevelPathIdParent:
                this.formData.categoryLevelPathId.shift(),
              categoryLevelGroupId: '1678277959244431361',
              categoryRelationPOList:
                this.$refs.productionDeviceRef.datasource.map((item) => {
                  return {
                    categoryId: item.id
                  };
                })
            };
            console.log(newFormData);
            informationAdd({ category: newFormData })
              .then((msg) => {
                this.formData = {};
                this.loading = false;
                this.$message.success(msg);
                this.handleClose();
                this.$emit('done');
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },
      async handleTree(code) {
        const res = await getTreeByPid(code);
        this.classList = res.data;
        this.typeList = res.data.map((item) => {
          return { id: item.id, name: item.code + ' ' + item.name };
        });
      },
      async open() {
        this.dialogVisible = true;
        await this.handleTree(0);
        //默认物品类别===》生产设备
        this.formData.categoryLevelId = '9';
        this.formData.code1 = 'W1';
      },
      handleClose() {
        this.dialogVisible = false;
      },
      shooteCategory(val) {
        console.log(this.classList);
        const row = this.findItemsByIds(this.classList, val);
        this.formData.categoryLevelPath = row.join('/');
      },
      //递归
      findItemById(arr, id) {
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i];
          if (item.id == id) {
            return item;
          }
          if (item.children && item.children.length > 0) {
            const childResult = this.findItemById(item.children, id);
            if (childResult) {
              return childResult;
            }
          }
        }
        return null;
      },
      findItemsByIds(array, ids) {
        return ids.map((id) => {
          const item = this.findItemById(array, id);
          return item ? item.name : null;
        });
      },
      chooseItem(val) {
        this.classList.map(async (item) => {
          if (item.id == val) {
            // const res = await getOrderNo(item.code);
            // console.log(res);
            this.formData.code1 = item.code;
            // this.itemForm.code = val;
            // this.getTreeData(item.code);
          }
        });
      }
    },
    mounted() {}
  };
</script>

<style lang="scss" scoped>
  .el-card {
    height: 100%;
  }

  .tabs {
    margin-top: 20px;
  }

  .dashed-line {
    border-bottom: 1px dashed #999;
    margin: 10px 0;
  }

  .dj {
    display: flex;

    ::v-deep .el-select {
      margin-left: 10px;
    }
  }

  ::v-deep .el-cascader,
  .el-select {
    width: 100%;
  }

  .main {
    display: flex;
    width: 100%;

    .left {
      margin-right: 5px;
      width: 30%;
    }

    .right {
      margin-left: 5px;
      width: 70%;
    }
  }
</style>
