<template>
  <div>
    <el-card>
      <el-form :inline="true" :model="query" class="query-form" size="mini">
        <el-form-item class="query-form-item" label="仓库名称:">
          <el-input
            v-model="query.name"
            clearable
            placeholder="仓库名称"
          ></el-input>
        </el-form-item>
        <el-form-item class="query-form-item" label="仓库状态:">
          <el-select v-model="query.status" placeholder="仓库状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value='1'></el-option>
            <el-option label="禁用" value='0'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button-group style="margin-left: 10px;display:flex;">
            <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
            <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="handleSubForm( null, 'add')">新增</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
      <el-table
        :data="list"
        border
        highlight-current-row
        @current-change="handSubInvCurrentChange"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column
          prop="name"
          label="仓库名称"
        >
        </el-table-column>
        <el-table-column
          prop="code"
          label="仓库编码"
        >
        </el-table-column>
        <el-table-column
          prop="parentName"
          label="所属部门"
        >
        </el-table-column>
        <el-table-column
          prop="parentInvName"
          label="上级仓库"
        >
        </el-table-column>
        <el-table-column label="操作"  class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              :disabled="!configParms.basicInv"
              @click.native.stop="handleSubForm( scope.row, 'edit')"
            >编辑
            </el-button
            >
            <el-button
              type="text"
              :disabled="!configParms.basicInv"
              @click.native.stop="handleSubDel(scope.row)"
            >删除
            </el-button
            >
          </template>

        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="query.page"
        :limit.sync="query.limit"
        @pagination="getList"
      />
      <!--仓库编辑界面-->
      <el-dialog
        :title="formMap[formName]"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="subFormVisible"
        :before-close="hideForm"
        width="60%"
        top="5vh"
      >
        <el-form :model="subData" ref="dataForm" :rules="formRules" label-width="80px">
          <el-row :gutter="20" class="el-row" type="flex">
            <el-col :span="12" class="el-col">
              <el-form-item label="所属部门" prop="parentId">
                <el-select v-model="subData.parentId" placeholder="顶级" style="width: 80%">
                  <el-option
                    v-for="item in fromDeptOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  >
                          <span style="float: left"
                          ><span v-html="item.html"></span>{{ item.name }}</span
                          >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" class="el-col">
              <el-form-item label="上级仓库" prop="parentCode">
                <treeselect v-model="subData.parentCode" :options="invOptions" :normalizer="normalizer"
                            style="width: 80%"
                            placeholder="选择上级仓库"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="el-row" type="flex">
            <el-col :span="12" class="el-col">
              <el-form-item label="仓库编码" prop="code" class="query-form-item">
                <el-input
                  disabled
                  v-model="subData.code" style="width: 80%"
                  auto-complete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col">
              <el-form-item label="仓库名称" prop="name" class="query-form-item">
                <el-input
                  v-model="subData.name" style="width: 80%"
                  auto-complete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row class="el-row" type="flex">
            <el-col class="el-col">
              <el-form-item label="备注" prop="name" class="query-form-item">
                <el-input
                  v-model="subData.remark"
                  type="textarea"
                  style="width: 90%"
                  auto-complete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-table :data="sysSubList" style="width: 100%; margin-bottom: 30px;" border>
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column
              label="外部系统名称"
              prop="sysName"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              label="外部仓库编码"
              prop="thirdId"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              label="外部仓库名称"
              prop="thirdName"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  :disabled="!configParms.basicInv"
                  @click="intentSubSelect(scope.row)"
                >关联
                </el-button
                >
                <el-button type="text" @click.native.stop="unbindSubThrWarehouse(scope.row)"
                           :disabled="scope.row.thirdId=='' ||scope.row.thirdId==null ||!configParms.basicInv"
                >解绑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="hideForm">取消</el-button>
          <el-button
            type="primary"
            @click.native="forInvSubmit()"
          >提交
          </el-button
          >
        </div>
      </el-dialog>
    </el-card>
    <el-tabs type="border-card" style="margin: 15px">
      <el-tab-pane>
        <span slot="label">{{ currentRow.name }}-用户列表</span>
        <el-form :inline="true" :model="userQuery" class="query-form" size="mini">
          <el-form-item class="query-form-item" label="用户名称/账号:">
            <el-input
              v-model="userQuery.key"
              placeholder="请输入用户名称或用户账号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-refresh"
                @click="onUserReset"
              >重置
              </el-button>
              <el-button type="primary" @click="onUserReset"
                         icon="el-icon-search"
              >查询
              </el-button
              >
              <el-button type="primary" @click="addUser()"
                         icon="el-icon-document-add"
              >选入用户
              </el-button
              >
            </el-button-group>
          </el-form-item>
        </el-form>
        <el-table
          :data="userData"
          key="row.id"
          border
          style="width: 100%"
          highlight-current-row
        >
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column
            prop="employeeName"
            label="用户名"
            min-width="30%">
          </el-table-column>
          <el-table-column
            prop="username"
            label="账号"
            min-width="20%">
          </el-table-column>
          <el-table-column
            label="操作"
            min-width="30%"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="!configParms.basicInv"
                @click.native="rmInvUser(scope.row)">
                移除
              </el-button>

              <!--              <el-button-->
              <!--                type="text"-->
              <!--                size="small" :disabled="!configParms.basicInv"-->
              <!--                @click.native="rmInvUser(scope.row)">-->
              <!--                授权-->
              <!--              </el-button>-->
              <el-button
                type="text"
                :disabled="!configParms.basicInv"
                @click.native="relBusttype(scope.row)">
                管理单据类型
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane>
        <span slot="label">{{ currentRow.name }}-单据类型</span>
        <el-form :inline="true" :model="userQuery" class="query-form" size="mini">
          <el-form-item class="query-form-item" label="单据类型名称:">
            <el-input
              v-model="userQuery.key"
              placeholder="请输入单据类型名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-refresh"
                @click="selsectBussinessType"
              >重置
              </el-button>
              <el-button type="primary" @click="selsectBussinessType"
                         icon="el-icon-search"
              >查询
              </el-button
              >
              <el-button type="primary" @click="addBussinessType()"
                         icon="el-icon-document-add"
              >选入单据类型
              </el-button
              >
            </el-button-group>
          </el-form-item>
        </el-form>

        <el-table :data="userBussinessTypeList" ref="typeList"
                  border
                  style="width: 100%">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="单据类型名称" prop="name"></el-table-column>
          <el-table-column label="单据类型编码" prop="action"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="!configParms.basicInv"
                @click.native.stop="delWarehouseBussinessType(scope.row.id)"
              >移除
              </el-button
              >
            </template>

          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane>
        <span slot="label">{{ currentRow.name }}-货位信息</span>
        <invSpaceManage :invInfo="currentInvInfo"></invSpaceManage>
      </el-tab-pane>
    </el-tabs>
    <!--添加用户弹窗-->
    <el-dialog
      v-if="userFormVisible"
      title="仓库信息-选入用户"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="userFormVisible"
    >
      <el-table v-loading="userloading" :data="selectUserList"
                ref="selectUserList"
                @selection-change="handleUserSelectionChange"
                border
                style="width: 100%">
        <el-table-column
          type="selection"
          :reserve-selection="false"
          width="55">
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="账号" prop="userName"></el-table-column>
        <el-table-column label="用户名" prop="employeeName"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="userFormVisible = !userFormVisible"
        >取消
        </el-button
        >
        <el-button
          type="primary"
          @click.native="addUserData()"
        >选入
        </el-button>
      </div>
      <pagination
        v-show="selectUserToatl>0"
        :total="selectUserToatl"
        :page.sync="selectUserQuery.page"
        :limit.sync="selectUserQuery.limit"
        @pagination="getSelectUser"
      />
    </el-dialog>

    <!--选入单据类型弹窗-->
    <el-dialog
      title="仓库信息-选入单据类型"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="bussinessTypeFormVisible"
    >
      <el-table v-loading="loading" :data="bussinessTypeList" ref="typeList"
                border
                style="width: 100%">
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55">
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="单据类型编码" prop="action"></el-table-column>
        <el-table-column label="单据类型名称" prop="name"></el-table-column>
      </el-table>
      <pagination
        v-show="bussinessTypeTotal>0"
        :total="bussinessTypeTotal"
        :page.sync="bussinessTypeQuery.page"
        :limit.sync="bussinessTypeQuery.limit"
        @pagination="getSelectUser"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="bussinessTypeFormVisible = !bussinessTypeFormVisible"
        >取消
        </el-button
        >
        <el-button
          type="primary"
          @click.native="addBussinessTypeData()"
        >提交
        </el-button>
      </div>

    </el-dialog>

    <!--    用户业务单据类型关联-->
    <el-dialog
      title="仓库-用户单据类型管理"
      :visible.sync="relBusUserVisile"
      width="45%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      v-if="relBusUserVisile"
    >
      <relBusUserDialog :inputQuery="curSeleUser" :closeDialog="cancelRelBusDiaolog"></relBusUserDialog>
    </el-dialog>


  </div>
</template>

<script>
import {
  filterSubAll, saveSubWarehouse, deleteSubWarehouse,
  getSubThrsysDetail, bindThrSubWarehouse, unbindSubThrWarehouse
} from "@/api/system/invSubWarehouse";
import {getHospitalUserList, selectNotSelectUser} from "@/api/auth/authUser";
import {getJoinBussinessType} from "@/api/basic/bussinessType";
import {findConfig} from "@/api/thrsys/spsSyncStatus";
import relBusUserDialog from "./invUserRelBusTypes";
import {selectSysParamByKey} from "@/api/system/param/systemParamConfig";
import invSpaceManage from "@/views/inventory/InvSpaceManage";
import {
  addWarehouseUser, deleteWarehouseBussinessType, deleteWarehouseUser, filterList,
  warehouseBussinessTypeList,
  warehouseUserList
} from "@/api/system/invWarehouse";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";

export default {
  data() {
    return {
      //---------------仓库相关-------------------
      query: {
        name: null,
        code: null,
        status: "1",
        page: 1,
        limit: 10,
      },
      loading: true,
      list: [],
      isExpandAll: true,
      total: 0,
      formMap: {
        add: "仓库信息-新增",
        edit: "仓库信息-编辑"
      },
      formName: null,
      configParms: {},
      currentCode: null,
      currentRow: {name: "仓库"},
      mutiInvMode: true,
      subFormVisible: false,
      formRules: {
        parentId: [
          {required: true, message: "请选择所属部门", trigger: "blur"}
        ],
        name: [
          {required: true, message: "请选择仓库名称", trigger: "blur"}
        ]
      },
      subData: {},
      fromDeptOptions: [],
      invOptions: [],


      //---------------仓库-用户相关---------------------
      userQuery: {
        code: null,
        page: 1,
        limit: 10
      },
      userData: [],
      userTotal: 0,
      //---------------仓库添加用户-----
      selectUserQuery: {
        code: null,
        page: 1,
        limit: 10
      },
      userFormVisible: false,
      userloading: false,
      selectUserList: [],
      selectUserToatl: 0,
      selectAddUser: [],
      //------用户-单据类型相关-----------------------
      curSeleUser: null,
      relBusUserVisile: false,
      userBussinessTypeList: [],

      bussinessTypeTotal: 0,
      bussinessTypeQuery: {
        enabled: true,
        page: 1,
        limit: 10,
        ids: ""
      },

      busQuery: {
        code: null,
        page: 1,
        limit: 10
      },
      selectBussinessTypeList: [],
      bussinessTypeFormVisible: false,

      //管理货位
      currentInvInfo: {
        invStorageCode: null,
        invWarehouseCode: null
      },
      sysList: [],
      sysSubList: [],
    };
  },
  methods: {

    //----------------仓库相关-----------------
    onReset() {   //重置
      this.$router.push({
        path: "",
      });
      this.query = {
        name: "",
        status: "",
      };
      this.userQuery.page = 1;
      this.busQuery.page = 1;
      this.getList();
    },

    onSubmit() { //提交查询
      this.getList();
    },
    getList() { //获取仓库信息
      this.loading = true;
      filterSubAll(this.query)
        .then((response) => {
          this.loading = false;
          this.total = response.data.total;
          let invlist = response.data.list || [];
          this.list = this.handleTree(invlist, "code", "parentCode");

        })
        .catch(() => {
          this.loading = false;
          this.total = 0;
          this.list = [];
        });
    },
    handleSubForm(data, formName) {   //新增，编辑

      this.formName = formName;
      if (formName === "edit") {
        this.subData = JSON.parse(JSON.stringify(data));
      } else if (formName === "add") {
        this.subData = {};
      }
      this.subFormVisible = true;
      this.getSubThrsysDetailData();
      filterSubAll(this.query)
        .then((response) => {
          let invList = response.data.list || [];
          this.invOptions = this.handleTree(invList, "code", "parentCode");
        })
        .catch(() => {
        });

    },
    hideForm() {    // 新增，编辑---取消
      this.formVisible = false;
      this.subFormVisible = false;
      return true;
    },
    forInvSubmit() {    // 新增，编辑---提交
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          saveSubWarehouse(this.subData, this.formName).then((response) => {
            if (response.code == 20000) {
              this.loadSubData(this.subData.parentId);
              this.subFormVisible = false;
            } else {
              this.$message.error(response.message);
              this.subFormVisible = false;
            }
          }).catch(() => {
            this.subFormVisible = false;
          });
        }
      });
    },
    findDeptMethod() {      //新增，编辑---获取部门信息
      let query = {
        status: 1,
      };
      filterList(query)
        .then((response) => {
          this.loading = false;
          this.fromDeptOptions = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
          this.fromDeptOptions = [];
        });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.code,
        label: node.name,
        children: node.children
      };
    },
    getSyncConfig() {//获取配置信息
      findConfig()
        .then((response) => {
          if (response.code == 20000) {
            this.configParms = response.data;
          }
        })
        .catch(() => {
        });
      let query = {
        paramKey: "muti_inv_mode",
      };
      selectSysParamByKey(query).then((response) => {
        if (response.code == 20000) {
          if (response.data.paramValue == "1") {
            this.mutiInvMode = true;
          } else {
            this.mutiInvMode = false;
          }
        }
      });
    },
    handSubInvCurrentChange(row) {  //列表选中
      this.currentCode = row.code;
      this.currentRow = row;
      this.curSeleUser = null;
      //加载用户信息
      this.loadLinkData(row)
      //加载单据类型
      this.selsectBussinessType(row);
      //加载货位信息
      this.invSpaceManage(row);
    },


    //------仓库-用户相关------------------
    loadUserList(val) {   //获取仓库用户列表
      if (val != null) {
        this.userQuery.page = val;
      }
      //加载用户数据
      warehouseUserList(this.userQuery).then((res) => {
        this.userData = res.data.list;
        this.userTotal = res.data.total;
      }).catch((error) => {
        this.$message.error("用户数据加载失败")
      });
    },
    rmInvUser(row) { //移除仓库关联用户
      this.$confirm("确定移除该仓库关联用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {id: row.id};
          deleteWarehouseUser(params).then((res) => {
            if (res.code == 20000) {
              this.loadUserList();
            } else {
              this.$message.error(res.message);
            }
          }).catch((error) => {
          });


        })
        .catch(() => {
        });
    },


    loadLinkData(row) {
      this.userQuery.page = 1;
      this.userQuery.code = row.code;
      this.curSeleUser = null;
      //加载用户数据
      this.loadUserList();
    },


    //添加仓库关联用户
    addUser() {
      this.currentCode = this.currentRow.code;
      this.userFormVisible = true;
      this.selectUserQuery.code = this.currentRow.code;
      this.selectUserQuery.page = 1;
      this.getSelectUser();
    },

    handleUserSelectionChange(val) {
      this.selectAddUser = val;
    },

    getSelectUser() {
      selectNotSelectUser(this.selectUserQuery).then((res) => {
        this.selectUserList = res.data.list;
        this.selectUserToatl = res.data.total;
      }).catch((error) => {
        this.$message.error("用户数据加载失败")
      });
    },

    addUserData() {
      let query = {
        code: this.currentCode,
        userList: JSON.stringify(this.selectAddUser)
      };
      addWarehouseUser(query).then((res) => {
        if (res.code === 20000) {
          this.userFormVisible = false;
          this.$message.success("添加成功");
          this.userQuery = {
            code: this.currentCode,
            page: 1,
            limit: 10
          }
          //重新加载数据
          warehouseUserList(this.userQuery).then((res) => {
            this.userData = res.data.list;
            this.userTotal = res.data.total;
          }).catch((error) => {
            this.userData = [];
            this.userTotal = 0;
          });
        } else {
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.$message.error("添加失败");
      });
    },


    relBusttype(row) {
      this.curSeleUser = row;
      this.relBusUserVisile = true;
    },

    cancelRelBusDiaolog() {
      this.relBusUserVisile = false;
      this.getUserBusTypeList(1);
    },


    selsectBussinessType() {
      var busQuery = {
        code: this.currentCode,
        page: 1,
        limit: 50
      }
      warehouseBussinessTypeList(busQuery).then((res) => {
        this.userBussinessTypeList = res.data.list;
      }).catch((error) => {
        this.$message.error("单据类型数据加载失败")
      });
    },


    delWarehouseBussinessType(id) {
      let params = {id: id};
      deleteWarehouseBussinessType(params).then((res) => {
        if (res.code == 20000) {
          this.$message.success("已移除");
          this.bussinessTypeData = [];
          this.selectWhouseBussinessType();
          var busQuerys = {
            code: this.currentCode,
            page: 1,
            limit: 10
          }
          warehouseBussinessTypeList(busQuerys).then((res) => {
            this.bussinessTypeData = res.data.list;
          }).catch((error) => {
            this.$message.error("单据类型数据加载失败")
          });

        } else {
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.$message.error("移除失败");
      })
    },

    addBussinessType(row) {
      var action = [];
      for (var i = 0; i < this.userBussinessTypeList.length; i++) {
        action.push(this.userBussinessTypeList[i].action);
      }
      this.bussinessTypeFormVisible = true;
      this.bussinessTypeQuery.page = 1;
      this.getBussinessType(1, action);
    },
    getBussinessType(val, obj) {
      if (val != null) {
        this.bussinessTypeQuery.page = val;
      }
      if (obj != undefined) {
        var action = obj.toString();
        this.bussinessTypeQuery.ids = action;
      }
      this.bussinessTypeQuery.code = this.busQuery.code;
      getJoinBussinessType(this.bussinessTypeQuery).then((res) => {
        this.selectBussinessTypeList = [];
        this.bussinessTypeList = res.data.list;
        this.bussinessTypeTotal = res.data.total;
        var that = this;
        that.$nextTick(() => {
          if (that.$refs.typeList) {
            that.$refs.typeList.clearSelection();
          }
          that.bussinessTypeList.forEach(row => {
            if (row.checkSelect == true) {
              that.$refs.typeList.toggleRowSelection(row, true);
            }
          });
        });
      }).catch((error) => {
      });
    },

    invSpaceManage(row) {
      this.currentInvInfo = {
        invStorageCode: row.parentId,
        invWarehouseCode: row.code
      };
    },


    getSubThrsysDetailData() {
      let params = {
        id: this.subData.code,
      };
      getSubThrsysDetail(params)
        .then((response) => {
          this.loading = false;
          this.sysSubList = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
          this.sysSubList = [];
        });
    },


  },
  mounted() {
  },
  components: {
    relBusUserDialog,
    invSpaceManage, Treeselect
  },
  created() {
    this.getList();
    this.getSyncConfig();
    this.findDeptMethod();
  }
};
</script>

<style scoped>

.vue-treeselect >>> .vue-treeselect__placeholder {
  font-size: 12px;
}

.vue-treeselect >>> .vue-treeselect__value-container {
  font-size: 12px;
}

.vue-treeselect >>> .vue-treeselect__control {
  height: 20px;
}

</style>
