<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>
          <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" ref="dataForm"></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="popInvRelUser( scope.row)"
            >用户管理
            </el-button
            >


            <el-button
              type="text"
              :disabled="!configParms.basicInv"
              @click.native.stop="popInvRelBustype(scope.row)"
            >单据类型
            </el-button
            >

            <el-button
              type="text"
              :disabled="!configParms.basicInv"
              @click.native.stop="handleDelInv(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="130px">
          <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"
                            :disabled="isShow"
                            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%"
                  placeholder="请输入仓库名称"
                  auto-complete="off"
                ></el-input>
              </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="advanceType" class="query-form-item">
                <el-radio-group v-model="subData.advanceType">
                  <el-radio :label="false">非寄售</el-radio>
                  <el-radio :label="true">寄售</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12" class="el-col">
              <el-form-item label="是否能被供应商使用" prop="spUse" class="query-form-item">
                <el-radio-group v-model="subData.spUse">
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>


          <el-row class="el-row" type="flex">
            <el-col class="el-col">
              <el-form-item label="备注" prop="remark" 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-dialog title="仓库信息-关联第三方仓库" :visible.sync="thrSubWareHouseVisible">
        <el-form :inline="true" :model="thirdSubQuery" class="query-form" size="mini">
          <el-form-item class="query-form-item">
            <el-input
              v-model="thirdSubQuery.name"
              clearable
              placeholder="仓库名称"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" icon="search" @click="intentSubSelect">查询</el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
        <el-table
          :data="thrSubWarehouseData"
          style="width: 100%;margin-top: 10px;"
          row-key="id"
          border
          highlight-current-row
          @current-change="changeSubThrWarehouse"
        >
          <el-table-column
            type="index"
            label="序号"
          >
          </el-table-column>
          <el-table-column
            prop="code"
            label="仓库编码"
          >
          </el-table-column>
          <el-table-column
            prop="name"
            label="仓库名称"
          >
          </el-table-column>
        </el-table>

        <pagination
          v-show="subTotal>0"
          :total="subTotal"
          :page.sync="thirdSubQuery.page"
          :limit.sync="thirdSubQuery.limit"
          @pagination="intentSubSelect"
        />

        <div slot="footer" class="dialog-footer">
          <el-button @click.native="hideThrWarehouseTable()">取消</el-button>
          <el-button
            type="primary"
            @click.native="bindSubThrWarehouse()"
          >提交
          </el-button>
        </div>
      </el-dialog>

      <!-- 仓库关联用户对话框-->
      <el-dialog
        title="仓库-用户管理"
        :visible.sync="relUserVisible"
        width="60%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        v-if="relUserVisible"
      >
        <inv-rel-users :inputQuery="currentRow"
                       :configParms="configParms"
                       :closeDialog="cancelRelUser"
        ></inv-rel-users>
      </el-dialog>

      <!-- 仓库关联单据类型对话框-->
      <el-dialog
        title="仓库-单据类型"
        :visible.sync="relBusTypeVisible"
        width="45%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        v-if="relBusTypeVisible"
      >
        <inv-rel-bus-type :inputQuery="currentRow"
                          :configParms="configParms"
                          :closeDialog="cancelRelBustype"
        ></inv-rel-bus-type>
      </el-dialog>

    </el-card>
    <el-tabs type="border-card" style="margin: 15px">
      <!--      <el-tab-pane>-->
      <!--        <span slot="label">{{ currentRow.name }}-用户列表</span>-->
      <!--      </el-tab-pane>-->
      <!--      <el-tab-pane>-->
      <!--        <span slot="label">{{ currentRow.name }}-单据类型</span>-->
      <!--      </el-tab-pane>-->
      <el-tab-pane>
        <span slot="label">{{ currentRow.name }}-货位信息</span>
        <invSpaceManage :invInfo="currentInvInfo"></invSpaceManage>
      </el-tab-pane>
    </el-tabs>


  </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 {selectSysParamByKey} from "@/api/system/param/systemParamConfig";
import invSpaceManage from "@/views/inventory/InvSpaceManage";
import {
  addWarehouseUser,
  deleteWarehouseBussinessType,
  deleteWarehouseUser,
  filterInvWarehouse,
  filterList,
  filterThridSubByInv,
  warehouseBussinessTypeList,
  warehouseUserList
} from "@/api/system/invWarehouse";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import InvRelBusType from "@/views/system/dept/invRelBusType";
import InvRelUsers from "@/views/system/dept/invRelUsers";
import {isBlank} from "@/utils/strUtil";

export default {
  data() {
    return {
      //---------------仓库相关-------------------
      query: {
        name: null,
        code: null,
        status: "1",
        // page: 1,
        // limit: 10,
      },
      isShow: null,
      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"}
        ],
        advanceType: [
          {required: true, message: "请选择是否寄售", trigger: "blur"}
        ]
      },
      subData: {},
      fromDeptOptions: [],
      invOptions: [],
      thirdSubQuery: {
        parentId: null,
        name: null,
        page: 1,
        limit: 10,
        thirdSysFk: "thirdId",
      },
      thrSubWareHouseVisible: false,
      thrSubWarehouseData: [],
      checkSubThrWarehouseRow: null,
      subTotal: 0,

      relBusTypeVisible: false,
      relUserVisible: false,

      //管理货位
      currentInvInfo: {
        invStorageCode: null,
        invWarehouseCode: null,
      },
      sysList: [],
      sysSubList: [],
    };
  },
  methods: {
    //----------------仓库相关-----------------
    onReset() {   //重置
      this.$router.push({
        path: "",
      });
      this.query = {
        name: "",
        status: "",
      };
      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 || [];
          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));
        this.isShow = true;
      } else if (formName === "add") {
        this.subData = {advanceType: false,};
        this.isShow = false;
      }
      this.subFormVisible = true;
      this.getSubThrsysDetailData();
      filterSubAll(this.query)
        .then((response) => {
          let invList = response.data || [];
          this.invOptions = this.handleTree(invList, "code", "parentCode");
        })
        .catch(() => {
        });
      this.sysSubList = null;
    },

    hideForm() {    // 新增，编辑---取消
      this.formVisible = false;
      this.subFormVisible = false;
      this.resetForm();
      return true;
    },
    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
        this.getList();
      }
    },
    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;
          });
        }
      });
      this.getList();
    },
    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.invSpaceManage(row);
      //加载单据类型
      this.selsectBussinessType(row);

    },
    //关联第三方仓库信息
    intentSubSelect(row) {
      if (row != null) {
        if (row.sysId != null && row.sysId != undefined) {
          this.thirdSubQuery.thirdSysFk = row.sysId;
        }
      }
      this.thrSubWarehouseData = [];
      this.thrSubWareHouseVisible = true;
      filterThridSubByInv(this.thirdSubQuery).then((res) => {
        if (res.code == 20000) {
          this.thrSubWarehouseData = res.data.list;
          this.subTotal = res.data.total || 0;
        } else {
          this.$message.error(res.message);
        }

      }).catch((error) => {
        this.thrWarehouseData = [];
        this.subTotal = 0;
        this.$message.error("第三方分库库数据加载失败");
      });
    },
    changeSubThrWarehouse(row) {
      this.checkSubThrWarehouseRow = row;
    },
    hideThrWarehouseTable() {
      this.thrWareHouseVisible = false;
      this.thrSubWareHouseVisible = false;
      //刷新表单
      this.thirdSubQuery.name = "";
      this.subData.id = null;
      this.checkSubThrWarehouseRow.code = null;
      this.checkSubThrWarehouseRow.thirdSysFk = null;
    },
    //绑定第三方分库
    bindSubThrWarehouse() {

      let params = {
        id: this.subData.id,
        thridWarehouseId: this.checkSubThrWarehouseRow.code,
        sysId: this.checkSubThrWarehouseRow.thirdSysFk
      }
      bindThrSubWarehouse(params).then((res) => {
        if (res.code == 20000) {
          this.$message.success("绑定成功")
          this.getSubThrsysDetailData();
        }
        this.thrSubWareHouseVisible = false;
      }).catch((error) => {
        this.$message.error("绑定失败");
        this.thrSubWareHouseVisible = false;
      })
    },
    //解绑第三方分库
    unbindSubThrWarehouse(row) {

      this.$confirm("确定解绑已关联第三方仓库信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            id: this.subData.id,
            sysId: row.sysId
          };
          unbindSubThrWarehouse(params).then((res) => {
            this.$message.success("解绑成功");
            this.getSubThrsysDetailData();
          }).catch((error) => {
            this.$message.error("解绑失败");
          })
        })
        .catch(() => {
        });


    },

    popInvRelBustype(row) {
      this.relBusTypeVisible = true;
      this.currentRow = row;
    },

    cancelRelBustype() {
      this.relBusTypeVisible = false;
    },

    popInvRelUser(row) {
      this.relUserVisible = true;
      this.currentRow = row;
    },

    cancelRelUser() {
      this.relUserVisible = false;
    },


    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,
        flag: row.id,
        page: 1
      };
    },


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


    handleDelInv(row) {
      if (row.id) {
        this.$confirm("确认删除该仓库吗?", "提示", {
          type: "warning",
        })
          .then(() => {
            this.deleteLoading = true;
            let para = {id: row.id};
            deleteSubWarehouse(para)
              .then((response) => {
                this.deleteLoading = false;
                if (response.code !== 20000) {
                  this.$message.error(response.message);
                  return false;
                }
                this.getList();
                this.$message.success("删除成功");
                this.loadSubData(row.parentId);
              })
              .catch(() => {
                this.deleteLoading = false;
              });
          })
          .catch(() => {
            this.$message.info("取消删除");
          });
      }
    },


  },
  mounted() {
  },
  components: {
    InvRelUsers,
    InvRelBusType,
    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;
  height: 30px;
}

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

</style>
