<template>
  <div class="app-container">
    <el-card style="margin-bottom: 15px">
      <div slot="header">
        <span class="left-text">仓库管理</span>
      </div>
      <div class="clearfix">
        <!-- 表单 -->
        <el-form
          :inline="true"
          :model="formInline"
          label-width="100px"
          class="demo-form-inline"
          size="mini"
        >
          <el-form-item label="仓库名称：">
            <el-input
              v-model.trim="formInline.name"
              placeholder="请输入仓库名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="启用状态：">
            <el-select
              v-model="formInline.status"
              placeholder="请选择"
              style="width: 260px"
            >
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="仓库编码：">
            <el-input
              v-model.trim="formInline.code"
              style="width: 260px"
              placeholder="请输入仓库编码"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话：">
            <el-input
              v-model.trim="formInline.contact_tel"
              style="width: 260px"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人：">
            <el-input
              v-model.trim="formInline.contact_name"
              style="width: 260px"
              placeholder="请输入联系人"
            ></el-input>
          </el-form-item>
          <el-form-item style="margin-left: 20px">
            <el-button type="primary" @click="onSubmit" size="mini"
              >查询</el-button
            >
            <el-button @click="reset" icon="el-icon-refresh-right" size="mini"
              >重置</el-button
            >
            <el-button type="primary" @click="handleAdd()" size="mini"
              >添加仓库</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        :height="tableHeight"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="code" label="仓库编码" width="90px">
        </el-table-column>
        <el-table-column prop="name" label="仓库名称"> </el-table-column>
        <el-table-column prop="contact_name" label="联系人"> </el-table-column>
        <el-table-column prop="contact_tel" label="联系电话" width="110px">
        </el-table-column>
        <el-table-column label="地区" width="200px">
          <template slot-scope="scope">
            <div>
              {{ scope.row.province + scope.row.city + scope.row.district }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="仓库地址"> </el-table-column>
        <el-table-column label="仓库面积">
          <template slot-scope="scope">
            <div>{{ scope.row.warehouse_area }}&nbsp;m²</div>
          </template>
        </el-table-column>
        <el-table-column label="默认发货仓">
          <template slot-scope="scope">
            <div>
              {{ isDefaulu(scope.row.is_default_send) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="默认收货仓">
          <template slot-scope="scope">
            <div>
              {{ isDefaulu(scope.row.is_default_get) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="启用状态" width="110px">
          <template slot-scope="scope">
            <el-switch
              @change="change(scope.row)"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
            <span v-if="scope.row.status == 1" style="color: #13ce66"
              >已启用</span
            >
            <span v-if="scope.row.status == 0">已停用</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              style="color: red"
              >删除
            </el-button>
            <!-- <el-divider direction="vertical"></el-divider> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="footer_pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 40, 60, 80, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增或修改弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      center
      v-loading="loading"
      :append-to-body="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :before-close="clearData"
      width="40%"
    >
      <div style="width: 100%; margin: 0 auto">
        <el-form
          v-if="dialogVisible"
          :model="editForm"
          ref="editForms"
          :rules="editFormRules"
          :label-position="labelPosition"
          label-width="150px"
          size="mini"
        >
          <el-form-item label="仓库名称：" prop="name" inline-message="true">
            <el-input
              v-model.trim="editForm.name"
              style="width: 80%"
              placeholder="请输入仓库名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="联系人："
            prop="contact_name"
            inline-message="true"
          >
            <el-input
              v-model.trim="editForm.contact_name"
              style="width: 80%"
              placeholder="请输入联系人姓名"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="联系电话："
            prop="contact_tel"
            inline-message="true"
          >
            <el-input
              v-model.trim="editForm.contact_tel"
              style="width: 80%"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="地区："
            :rules="[
              { required: true, message: '请选择地区', trigger: 'blur' },
            ]"
          >
            <el-cascader
              v-model="areaList"
              :props="props"
              @change="handleChanges"
              placeholder="请选择具体的省市区"
              style="width: 80%"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="仓库地址：" prop="address" inline-message="true">
            <el-input
              v-model.trim="editForm.address"
              style="width: 80%"
              placeholder="请输入仓库详细地址"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="仓库面积："
            prop="warehouse_area"
            inline-message="true"
          >
            <el-input
              v-model.trim="editForm.warehouse_area"
              style="width: 80%"
              placeholder="请输入仓库面积（单位：m²）"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="默认发货仓："
            prop="is_default_send"
            inline-message="true"
          >
            <el-radio-group v-model="editForm.is_default_send">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="默认收货仓："
            prop="is_default_get"
            inline-message="true"
          >
            <el-radio-group v-model="editForm.is_default_get">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="启用状态：" prop="status" inline-message="true">
            <el-radio-group v-model="editForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="clearData" size="mini">取 消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="closeDialogVisible('editForms')"
          >提交</el-button
        >
      </span>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogDelete"
      center
      :close-on-click-modal="false"
      width="30%"
    >
      <div style="text-align: center; margin: 0 auto">
        <p>确定要删除仓库吗？删除后添加商品时将不可用</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDelete = false" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="closeDialogDelete()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getAreaList } from "@/api/module/retreat/address";
import {
  wareHoustList,
  addWareHoust,
  wareHoustInfo,
  updateWareHoust,
  deleteWareHoust,
} from "@/api/system/wareHouse";
export default {
  name: "wareHouse",
  data() {
    // 手机号码格式校验
    let checkTel = (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/;
      if (value === "") {
        callback(new Error("手机号码不能为空"));
      } else if (!reg.test(value)) {
        callback(new Error("手机号码格式不对,请重新输入"));
      } else {
        callback();
      }
    };
    // 面积格式校验
    let checkware = (rule, value, callback) => {
      const reg = /^[0-9]+(\.[0-9]{1,2})?$/;
      if (value === "") {
        callback(new Error("仓库面积不能为空"));
      } else if (!reg.test(value)) {
        callback(new Error("格式不对或只能保留两位小数"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      fullHeight: 0,
      tableHeight: 0,
      total: 0,
      currentPage: 1,
      pageSize: 20,
      code: 0,
      //控制启用状态展示
      exhibition: true,
      tableData: [],
      labelPosition: "right",
      //   所属地区下拉框
      props: {
        expandTrigger: "click",
        lazy: true,
        lazyLoad: this.lazyLoad,
        value: "id",
        label: "name",
        leaf: "leaf",
      },
      areaList: [],
      //搜索表单内容
      formInline: {
        name: "",
        status: "",
        code: "",
        contact_tel: "",
        contact_name: "",
      },
      //新增表单内容
      editForm: {
        name: "",
        contact_name: "",
        contact_tel: "",
        address: "",
        warehouse_area: "",
        is_default_send: 1,
        is_default_get: 1,
        status: 1,
      },
      //表单验证
      editFormRules: {
        name: [{ required: true, message: "请输入仓库名称", trigger: "blur" }],
        contact_name: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
        ],
        contact_tel: [{ required: true, validator: checkTel, trigger: "blur" }],
        address: [
          { required: true, message: "请输入仓库地址", trigger: "blur" },
        ],
        warehouse_area: [
          { required: true, validator: checkware, trigger: "blur" },
        ],
        is_default_send: [
          { required: true, message: "请选择", trigger: "blur" },
        ],
        is_default_get: [
          { required: true, message: "请选择", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      title: "",
      //新增修改提示框
      dialogVisible: false,
      //删除提示框
      dialogDelete: false,
    };
  },
  created() {
    this.$nextTick(() => {
      this.fullHeight =
        document.getElementsByClassName("app-container")[0].clientHeight;
    });
    this.getWareHoustList();
  },
  watch: {
    fullHeight(val) {
      let formHeight =
        document.getElementsByClassName("clearfix")[0].clientHeight;
      this.tableHeight = val - formHeight - 225;
    },
  },
  methods: {
    //   开关已停用和已启用
    change(val) {
      let obj = JSON.parse(JSON.stringify(val));
      updateWareHoust(obj).then((res) => {
        if (res.code == 1) {
          this.getWareHoustList();
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      });
    },
    //新增分组
    handleAdd() {
      this.dialogVisible = true;
      this.title = "新增仓库";
      this.editForm.name = "";
      this.editForm.contact_name = "";
      this.editForm.contact_tel = "";
      this.editForm.address = "";
      this.editForm.warehouse_area = "";
      this.editForm.is_default_send = 1;
      this.editForm.is_default_get = 1;
      this.editForm.status = 1;
      this.areaList = [];
    },
    //删除分组
    handleDelete(val) {
      this.dialogDelete = true;
      this.code = val.id;
    },
    //点击编辑按钮
    handleUpdate(val) {
      this.loading = true;
      this.title = "编辑仓库";
      let obj = {
        id: val.id,
      };
      wareHoustInfo(obj).then((res) => {
        if (res.code == 1) {
          this.editForm = res.data;
          this.areaList.push(res.data.province_id);
          this.areaList.push(res.data.city_id);
          this.areaList.push(res.data.district_id);
          this.dialogVisible = true;
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
        this.loading = false;
      });
    },
    //查询
    onSubmit() {
      this.getWareHoustList();
    },
    //重置
    reset() {
      this.formInline.name = "";
      this.formInline.status = "";
      this.formInline.code = "";
      this.formInline.contact_tel = "";
      this.formInline.contact_name = "";
      this.getWareHoustList();
    },
    //新增或修改弹框确定回调
    closeDialogVisible(editForms) {
      this.$refs[editForms].validate((valid) => {
        if (valid) {
          if (this.title == "新增仓库") {
            this.editForm["province_id"] = this.areaList[0];
            this.editForm["city_id"] = this.areaList[1];
            this.editForm["district_id"] = this.areaList[2];
            addWareHoust(this.editForm).then((res) => {
              if (res.code == 1) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.clearData();
                this.getWareHoustList();
                this.dialogVisible = false;
              } else {
                this.$message({
                  message: res.message,
                  type: "error",
                });
              }
            });
          } else if (this.title == "编辑仓库") {
            this.editForm["province_id"] = this.areaList[0];
            this.editForm["city_id"] = this.areaList[1];
            this.editForm["district_id"] = this.areaList[2];
            updateWareHoust(this.editForm).then((res) => {
              if (res.code == 1) {
                this.$message({
                  message: "编辑成功",
                  type: "success",
                });
                this.clearData();
                this.getWareHoustList();
                this.dialogVisible = false;
              } else {
                this.$message({
                  message: res.message,
                  type: "error",
                });
              }
            });
          }
        }
      });
    },
    //清空表单数据
    clearData() {
      this.dialogVisible = false;
      this.editForm.name = "";
      this.editForm.contact_name = "";
      this.editForm.contact_tel = "";
      this.editForm.address = "";
      this.editForm.warehouse_area = "";
      this.editForm.is_default_send = 1;
      this.editForm.is_default_get = 1;
      this.editForm.status = 1;
      this.areaList = [];
    },
    //删除提示框
    closeDialogDelete() {
      let obj = {
        id: this.code,
      };
      deleteWareHoust(obj).then((res) => {
        if (res.code == 1) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getWareHoustList();
          this.dialogDelete = false;
        } else {
          this.$message({
            message: res.message,
            type: "error",
          });
          this.dialogDelete = false;
        }
      });
    },
    //
    lazyLoad(node, resolve) {
      this.getArea(node, resolve);
    },
    //
    getArea(node, resolve) {
      const level = node.level;
      let limboNode = {};
      if (level === 0) {
        limboNode = { pid: 0 };
      }
      if (level === 1) {
        limboNode = { pid: node.value };
      }
      if (level === 2) {
        limboNode = { pid: node.value };
      }
      getAreaList(limboNode).then((res) => {
        let result = {};
        if (level === 0) {
          result = res.data;
          result.forEach((item) => {
            item.value = item.id;
            item.label = item.name;
            item.children = [];
            item.leaf = 0; // 可以控制 是否有下级   值为true都不行，必须等于0
          });
        }

        if (level === 1) {
          result = res.data;
          result.forEach((item) => {
            item.value = item.id;
            item.label = item.name;
            item.children = [];
            //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
            item.leaf = 0;
          });
        }

        if (level === 2) {
          result = res.data;
          result.forEach((item) => {
            item.value = item.id;
            item.label = item.name;
            item.leaf = 1;
          });
        }
        resolve(result);
      });
    },
    handleChanges(value) {
      this.areaList = value;
      //   this.addressForm.address_ids = value;
    },
    // 获取仓库列表
    getWareHoustList() {
      let obj = {};
      obj["limit"] = this.pageSize;
      obj["page"] = this.currentPage;
      if (this.formInline.name != "") {
        obj["name"] = this.formInline.name;
      }
      if (this.formInline.status != "") {
        obj["status"] = this.formInline.status;
      }
      if (this.formInline.code != "") {
        obj["code"] = this.formInline.code;
      }
      if (this.formInline.contact_tel != "") {
        obj["contact_tel"] = this.formInline.contact_tel;
      }
      if (this.formInline.contact_name != "") {
        obj["contact_name"] = this.formInline.contact_name;
      }
      wareHoustList(obj).then((res) => {
        if (res.code == 1) {
          this.total = res.data.count;
          this.tableData = res.data.list;
        }
      });
    },
    //分页查询
    handleSizeChange(val) {
      this.pageSize = val;
      this.getWareHoustList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getWareHoustList();
    },
    //是否默认收货仓
    isDefaulu(val) {
      if (val == 0) {
        return "否";
      } else if (val == 1) {
        return "是";
      }
    },
  },
};
</script>
<style scoped>
/* .clearfix {
  margin: 10px 0 15px 0;
} */
.left-text {
  padding-left: 7px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #333333;
  line-height: 28px;
}
/* 分页 */
.footer_pagination {
  text-align: center;
  margin-top: 15px;
}
</style>