<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="父级区域" prop="parentId">
          <TreeSelect
            v-model="formData.parentId"
            :options="baseWarehouseTree"
            :normalizer="normalizer"
            placeholder="请选择父级仓库区域"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入仓库/货架名称"/>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入仓库/货架编码"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :precision="2" :step="0.1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="01"
            inactive-value="02">
          </el-switch>
        </el-form-item>
        <el-form-item label="关联子公司" prop="corpId">
          <el-select v-model="formData.corpIds" multiple placeholder="请选择">
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.corpName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as BaseWarehouseApi from '@/api/base/warehouse';
import TreeSelect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getCompanyList} from '@/api/base/company'

export default {
  name: "BaseWarehouseForm",
  components: {
    TreeSelect,
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        parentId: undefined,
        name: undefined,
        code: undefined,
        status: '01',
        remark: undefined,
        corpIds: [],
        corpId: undefined,
      },
      // 表单校验
      formRules: {
        parentId: [{required: true, message: '父级仓库区域不能为空', trigger: 'blur'}],
        code: [{required: true, message: '编码不能为空', trigger: 'blur'}],
        name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
      },
      baseWarehouseTree: [], // 树形结构
      companyList: []
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id, addChild) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id && !addChild) {
        this.formLoading = true;
        try {
          const res = await BaseWarehouseApi.getBaseWarehouse(id);
          this.formData = res.data;
          this.title = "修改仓库";
        } finally {
          this.formLoading = false;
        }
      }
      //新增子级
      if (addChild) {
        this.formData.parentId = id;
      }
      this.title = "新增仓库";
      //获取仓库树
      await this.getBaseWarehouseTree();
      //获取子公司
      await this.listCompany();
    },

    /**查询子公司*/
    async listCompany() {
      const res = await getCompanyList()
      this.companyList = res.data
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        this.formData.corpId = this.formData.corpIds + ''
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await BaseWarehouseApi.updateBaseWarehouse(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await BaseWarehouseApi.createBaseWarehouse(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 获得仓库树 */
    async getBaseWarehouseTree() {
      this.baseWarehouseTree = [];
      const res = await BaseWarehouseApi.getBaseWarehouseList();
      const root = {id: 0, name: '顶级仓库', children: []};
      root.children = this.handleTree(res.data, 'id', 'parentId', "children", "0")
      this.baseWarehouseTree.push(root)
    },
    /** 转换仓库数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        parentId: undefined,
        name: undefined,
        code: undefined,
        status: '01',
        remark: undefined,
        corpIds: [],
        corpId: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
