<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['warehouse:add'])" type="primary"
            @click="handleAddWarehouse">新增</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" placeholder="请输入关键字搜索" />
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column prop="sn" label="仓库编号" />
        <el-table-column prop="name" label="仓库名称" />
        <!-- <el-table-column prop="admin_id" label="负责人姓名">
          <template slot-scope="scope">
            {{ adminName(scope.row.admin_id) }}
          </template>
</el-table-column> -->
        <el-table-column prop="phone" label="负责人手机号" />
        <el-table-column prop="name" label="仓库地址">
          <template slot-scope="scope">
            {{
              adminName(scope.row.ware_pro_city_area) +
              scope.row.warehouse_address || ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="仓库说明" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['warehouse:update'])"
              @click="handleEditWarehouse(scope.$index, scope.row)">编辑</el-button>
            <!-- <el-button
              size="mini"
              v-if="checkPermission(['stock:del'])"
              type="danger"
              @click="handleDeleteWarehouse(scope.$index, scope.row)"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog :title="stockForm.id ? '编辑仓库' : '添加仓库'" :visible.sync="dialogVisible" width="500px"
      @open="handleDialogOpen" :modal-append-to-body="false" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="stockForm" :rules="stockRules" ref="stockForm" label-width="120px">
        <el-form-item label="仓库编号" prop="sn">
          <el-input v-model="stockForm.sn" :minlength="2" :maxlength="4" clearable placeholder="请输入仓库编号"></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="stockForm.name" :minlength="2" :maxlength="20" clearable placeholder="请输入仓库名称"></el-input>
        </el-form-item>
        <el-form-item label="发货人姓名" prop="">
          <el-input v-model="stockForm.user_name" :minlength="2" :maxlength="20" clearable placeholder="请输入发货人姓名"></el-input>
          <!-- <el-select v-model="stockForm.admin_id" clearable @change="selUser">
            <el-option v-for="item in marketingList" :key="item.id" :label="item.real_name" :value="item.id" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="发货人电话" prop="phone">
          <el-input v-model="stockForm.phone" :minlength="2" :maxlength="20" clearable
            placeholder="请输入发货人电话"></el-input>
        </el-form-item>
        <el-form-item label="仓库地址" prop="">
          <el-cascader size="large" :options="options" clearable v-model="selectedOptions" >
          </el-cascader>
          <span>
            <el-input style="margin-top: 10px" v-model="stockForm.warehouse_address" placeholder="请输入"></el-input>
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="stockForm.description" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
            placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitWarehouseForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_BasicSetting from "@/api/basicSetting";
import * as API_Setting from "@/api/setting";
import * as API_Auth from "@/api/auth";
import { Foundation } from "~/ui-utils";
import { mapGetters } from "vuex";
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from "element-china-area-data";
export default {
  name: "warehouse",
  data() {
    return {
      deptList: [],
      adminList: [],
      // postList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
      },
      // 列表数据
      tableData: "",
      // 仓库表单
      stockForm: {
        phone: "",
      },
      // 仓库表单 规则
      stockRules: {
        sn: [{ required: true, message: "请输入仓库编号", trigger: "blur" }],
        name: [
          { required: true, message: "请选择输入仓库名称", trigger: "blur" },
        ],
        phone: [
          this.MixinRequired("请输入手机号码！"),
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
        ],
      },
      // 仓库表单 dialog
      dialogVisible: false,
      options: regionData,
      selectedOptions: [],
      marketingList: [], // 销售经理列表
    };
  },
  mounted() {
    this.GET_WarehouseList();
    this.GET_DeptList();
    // this.GET_StationAllList()
    this.GET_AdministratorList();
    this.GET_MarketingList();
  },
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    /* 选择负责人 */
    selUser(selectedUserId) {
      const selectedUser = this.marketingList.find(user => user.id === selectedUserId);
      this.stockForm.user_name = selectedUser ? selectedUser.real_name : null;
      this.stockForm.admin_id = selectedUser ? selectedUser.id : null;
      /* this.stockForm.user_name=val.real_name
      this.stockForm.admin_id=val.id */
    },
    /** 获取销售经理列表 */
    GET_MarketingList() {
      API_BasicSetting.getUserByDept().then((res) => {
        this.marketingList = res;
      });
    },
    adminName(val) {
      let text = "";
      if (val !== undefined) {
        text += codeToText[val[0]];
        text += codeToText[val[1]];
        text += codeToText[val[2]];
      }
      return text;
    },
    handleChange(value) {
      this.stockForm.ware_pro_city_area = value.join(",");
      /**/

      //打印区域码所对应的属性值即中文地址
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0,
      }).then((response) => {
        this.adminList = response.data;
      });
    },
    // /** 获取岗位 */
    // GET_StationAllList() {
    //   API_Setting.getStationAllList().then(response => {
    //     this.postList = response
    //   })
    // },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then((response) => {
        this.deptList = Foundation.buildTree(response, "0");
      });
      console.log(
        JSON.parse(JSON.parse(localStorage.getItem("admin_user")).data)
      );
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_WarehouseList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.GET_WarehouseList();
    },

    /** 添加仓库 */
    handleAddWarehouse() {
      this.stockForm = {
        dept_id: 0,
        admin_id: this.user.uid,
      };
      this.dialogVisible = true;
    },

    /** 编辑仓库 */
    handleEditWarehouse(index, row) {
      this.stockForm = row;
      this.selectedOptions = row.ware_pro_city_area;
      this.dialogVisible = true;
    },

    /** 删除仓库 */
    handleDeleteWarehouse(index, row) {
      this.$confirm("确定要删除这个仓库吗？", "提示", { type: "warning" })
        .then(() => {
          API_BasicSetting.deleteWarehouse(row.id).then(() => {
            this.$message.success("删除成功！");
            this.GET_WarehouseList();
          });
        })
        .catch(() => { });
    },
    /** dialog打开后重置form表单校验结果 */
    handleDialogOpen() {
      setTimeout(() => {
        this.$refs["stockForm"].clearValidate();
      });
    },

    /** 提交仓库表单 */
    submitWarehouseForm() {
      this.$refs["stockForm"].validate((valid) => {
        if (valid) {
          const { id } = this.stockForm;
          const params = this.MixinClone(this.stockForm);
          if (!params.real_name) delete params.real_name;
          params.role_id === "超级仓库" ? (params.role_id = 0) : null;
          delete params.admin_name;
          params.admin_id = JSON.parse(
            JSON.parse(localStorage.getItem("admin_user")).data
          ).uid;
          params.ware_pro_city_area = this.selectedOptions.join(",");
          if (id) {
            API_BasicSetting.editWarehouse(id, params).then((response) => {
              this.dialogVisible = false;
              this.$message.success("修改成功！");
              this.GET_WarehouseList();
            });
          } else {
            API_BasicSetting.addWarehouse(params).then(() => {
              this.dialogVisible = false;
              this.$message.success("添加成功！");
              this.GET_WarehouseList();
            });
          }
        } else {
          this.$message.error("表单填写有误，请核对！");
          return false;
        }
      });
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keyword: data,
      };
      this.params.page_no = 1;
      this.GET_WarehouseList();
    },

    /** 获取仓库列表 */
    GET_WarehouseList() {
      this.loading = true;
      API_BasicSetting.warehouse(this.params)
        .then((response) => {
          this.loading = false;
          response.data.map((el) => {
            if (el.ware_pro_city_area !== undefined) {
              el.ware_pro_city_area = el.ware_pro_city_area.split(",");
            }
            return el;
          });
          this.tableData = response;
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
