<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.key"
            clearable
            placeholder="关键字搜索"
          ></el-input>
        </el-form-item>
        <el-form-item class="query-form-item" label="第三方系统:">
          <el-select v-model="query.thirdSysFk" placeholder="请选择第三方系统"
                     @change="thirdSysFkChange()">
            <el-option
              v-for="item in thirdSys"
              :key="item.thirdId"
              :label="item.thirdName"
              :value="item.thirdId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
            <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
            <el-button type="primary" @click.native="handleForm(null, null,'addTop')"
                       icon="el-icon-plus" :disabled="!configParms.basicThirdInv"
            >添加部门/科室
            </el-button>
            <el-button type="primary" @click.native="downloadWarehouse()"
                       icon="el-icon-download"
                       v-if="this.thirdSysDetail.enabled && this.thirdSysDetail.fromType==3"
                       :disabled="!configParms.basicThirdInv"
            >下载仓库
            </el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
      <el-table
        :data="mergeList"
        style="width: 100%;"
        row-key="id"
        border
        highlight-current-row
        @current-change="handInvCurrentChange">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column
          prop="code"
          label="部门编码"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="部门名称"
        >
        </el-table-column>
<!--        <el-table-column-->
        <!--          prop="advanceType"-->
        <!--          label="仓库类型">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ enableMap[scope.row.advanceType] }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="thirdName" label="第三方系统名称">
          <template slot-scope="scope">
            <span>{{ getThirdSysFkName(scope.row.thirdSysFk) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">

            <el-button
              type="text"
              size="small"
              @click.native.stop="handleSubForm( scope.row, 'add')"
              :disabled="!configParms.basicThirdInv"
            >添加仓库
            </el-button
            >

            <el-button
              type="text"
              size="small"
              :disabled="!configParms.basicThirdInv"
              @click.native.stop="handleForm(node, scope.row, 'edit')"
            >编辑
            </el-button
            >
            <el-button
              type="text"
              size="small"
              :disabled="!configParms.basicThirdInv"
              @click.native.stop="handleDel(node,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-card>
    <el-card>
      <el-table
        :data="subList"
        border
        highlight-current-row
        style="width: 100%;margin-top: 35px">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column
          prop="code"
          label="仓库编码"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="仓库名称"
        >
        </el-table-column>
        <el-table-column
          prop="parentName"
          label="所属部门"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              :disabled="!configParms.basicThirdInv"
              @click.native.stop="handleSubForm( scope.row, 'edit')"
            >编辑
            </el-button
            >
            <el-button
              type="text"
              size="small"
              :disabled="!configParms.basicThirdInv"
              @click.native.stop="handleSubDel(scope.row)"
            >删除
            </el-button
            >
          </template>

        </el-table-column>
      </el-table>
      <pagination
        v-show="subTotal>0"
        :total="subTotal"
        :page.sync="subQuery.page"
        :limit.sync="subQuery.limit"
        @pagination="getSubList"
      />
    </el-card>
    <!--仓库弹窗编辑页面-->
    <el-dialog
      :title="formMap[formName]"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="formVisible"
      :before-close="hideForm"
      width="45%"
      top="5vh"
    >
      <el-form :model="formData" :rules="formRules" ref="dataForm">
        <el-form-item label="仓库编码" prop="code" class="query-form-item" label-width="100px">
          <el-input
            v-model.trim="formData.code" style="width: 80%"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name" class="query-form-item" label-width="100px">
          <el-input
            v-model.trim="formData.name" style="width: 80%"
            auto-complete="off"
          ></el-input>
        </el-form-item>
<!--        <el-form-item class="query-form-item" prop="advanceType" label="仓库类型" label-width="100px">-->
<!--          <el-select v-model="formData.advanceType" placeholder="仓库类型" clearable style="width: 80%">-->
<!--            <el-option label="寄售" :value='true'></el-option>-->
<!--            <el-option label="仓库" :value='false'></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item class="query-form-item" prop="thirdSysFk" label="第三方系统" label-width="100px">
          <el-select v-model="formData.thirdSysFk" placeholder="请选择第三方系统" clearable style="width: 80%">
            <el-option
              v-for="item in thirdSys"
              :key="item.thirdId"
              :lable="item.thirdName"
              :value="item.thirdName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态:" prop="status" class="query-form-item" label-width="100px">
          <el-radio-group v-model="formData.status" style="width: 80%">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hideForm">取消</el-button>
        <el-button
          type="primary"
          @click.native="formSubmit()"
          :loading="formLoading"
        >提交
        </el-button
        >
      </div>
    </el-dialog>
    <!-- 分库弹窗编辑页面-->
    <el-dialog
      :title="subMap[subFromName]"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="subFormVisible"
      :before-close="hideForm"
      width="45%"
      top="5vh"
    >
      <el-form :model="subData" ref="dataForm">
        <el-form-item label="所属仓库" prop="pid">
          <el-select v-model="subData.parentId" placeholder="顶级" disabled style="width: 80%">
            <el-option
              v-for="item in mergeList"
              :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-form-item label="分库编码" prop="title" class="query-form-item">
          <el-input
            v-model="subData.code" style="width: 80%"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <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-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hideForm">取消</el-button>
        <el-button
          type="primary"
          @click.native="forSubSubmit()"
          :loading="formLoading"
        >提交
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  filterThrList,
  saveThrWarehouse,
  deleteThrWarehouse,
  download
} from "@/api/thrsys/thrInvWarehouse";
import {filterDetailByKey, getBasicThirdSys} from "@/api/thrsys/basicThirdSys";
import {findConfig} from "@/api/thrsys/spsSyncStatus";
import {isBlank} from "@/utils/strUtil";
import {
  filterThridSubAll,
  deleteSubWarehouse,
  saveSubWarehouse
} from "@/api/thrsys/thrdSubInvWarehouse";

const formJson = {
  id: null,
  pid: null,
  name: null,
  code: null,
  status: 1,
  advanceType: false,
  isDefault: false,
  page: 1,
  limit: 20,
};
export default {
  data() {
    return {
      query: {
        id: null,
        pid: null,
        name: null,
        code: null,
        status: null,
        advanceType: null,
        isDefault: null,
        page: 1,
        limit: 20,
        parentId: null,
        thirdSysFk: null,
      },
      mainThirdSys:'',
      ThirdSysName:"",
      mergeList: [],
      subList: [],
      subData: {},
      currentCode: null,
      node: null,
      thirdSysDetail: {
        enabled: false,
        fromType: 0,
      },
      total: 0,
      loading: true,
      index: null,
      formName: null,
      formMap: {
        addTop: "仓库信息-新增",
        add: "添加货位",
        edit: "仓库信息-编辑"
      },
      subMap: {
        add: "仓库信息-添加",
        edit: "仓库信息-编辑"
      },
      enableMap: {
        true: "寄售",
        false: "仓库",
      },
      formLoading: false,
      subFormVisible: false,
      formVisible: false,
      formData: formJson,
      formRules: {
        name: [
          {required: true, message: "请输入仓库货位名", trigger: "blur"}
        ],
        code: [
          {required: true, message: "请输入仓库货位代码", trigger: "blur"}
        ],
        thirdSysFk: [
          {required: true, message: "请选择第三方系统", trigger: "blur"}
        ],

      },
      pidData: {},
      deleteLoading: false,
      thirdSys: [],
      configParms: {},
      subTotal: 0,
      subQuery: {
        page: 1,
        limit: 10,
      },
    };
  },
  methods: {


    handleCurrentChange(val) {
      this.query.page = val;
      this.getList();
    },

    handInvCurrentChange(row) {
      this.subList = [];
      this.currentCode = row.code;
      this.loadSubData(row);
    },

    loadSubData(row) {
      this.subQuery = {
        parentId: row.code,
        thirdSysFk: row.thirdSysFk,
        page: 1,
        limit: 10,
      }
      this.getSubList();
    },
    getSubList() {
      filterThridSubAll(this.subQuery).then((res) => {
        if (res.code == 20000) {
          this.subList = res.data.list;
          this.subTotal = res.data.total;
        }
      }).catch((error) => {
      });
    },
    onReset() {
      this.$router.push({
        path: "",
      });
      this.query = {
        name: "",
        status: "",
        page:1,
        limit:20,
        thirdSysFk: this.mainThirdSys
      };
      this.getList();
    },
    onSubmit() {
      this.getList();
    },
    getList() {
      this.loading = true;
      filterThrList(this.query)
        .then((response) => {
          this.loading = false;
          this.mergeList = response.data.list || [];
          this.total = response.data.total || 0;
        })
        .catch(() => {
          this.loading = false;
          this.mergeList = [];
          this.total = 0;
        });
    },
    getThirdSysFkName(thirdSys) {
      for (let i = 0; i < this.thirdSys.length; i++) {
        if (this.thirdSys[i].thirdId === thirdSys) {
          return this.thirdSys[i].thirdName;
        }
      }
    },
    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
      }
    },
    // 隐藏表单
    hideForm() {
      // 更改值
      this.formVisible = false;
      this.subFormVisible = false;
      let Item = JSON.parse(localStorage.getItem('obj'))
      this.subData=Item;
      this.getSubList();
      return true;
    },
    // 显示表单
    handleForm(node, data, formName) {
      this.formVisible = true;
      this.resetForm();
      this.pidData = data || null;
      formJson.pid = (data && parseInt(data.id)) || "";
      this.formData = JSON.parse(JSON.stringify(formJson));
      if (formName === "edit") {
        this.formData = Object.assign({}, data);
        if (this.formData.thirdSysFk != null) {
          this.thirdSys.forEach((item) => {
            if (item.thirdId == this.formData.thirdSysFk) {
              this.formData.thirdSysFk = item.thirdName;
            }
          })
        }
        this.node = node;
      } else {
      }

      this.formData.pid = !this.formData.pid ? "" : this.formData.pid;
      this.formName = formName;
      if (data && data.id) {
        this.index = this.mergeList.findIndex((d) => d.id === data.id);
      }
      this.ThirdSysName=this.formData.thirdSysFk
    },

    handleSubForm(data, formName) {
      this.subFromName = formName;
      if (formName === "edit") {
        this.subData = data;
        localStorage.setItem('obj', JSON.stringify(this.subData))
      } else if (formName === "add") {
        this.subData = {};
        this.subData.parentId = data.code;
        this.subData.thirdSysFk = data.thirdSysFk;
      }
      this.subFormVisible = true;
      localStorage.setItem("code", JSON.stringify(this.subData.code));
    },

    handleSubDel(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.$message.success("删除成功");
                let param = {
                  code: row.parentId,
                  thirdSysFk: row.thirdSysFk
                }
                this.loadSubData(param);
              })
              .catch(() => {
                this.deleteLoading = false;
              });
          })
          .catch(() => {
            this.$message.info("取消删除");
          });
      }
    },

    //添加分库
    forSubSubmit() {
      if (this.$isBlank(this.subData.code)) {
        this.$message.error("分库编码不能为空！");
        return;
      }
      if (this.$isBlank(this.subData.name)) {
        this.$message.error("分库名称不能为空！");
        return;
      }

      saveSubWarehouse(this.subData, this.subFromName).then((response) => {

        if (response.code == 20000) {
          let row = {
            code: this.subData.parentId,
            thirdSysFk: this.subData.thirdSysFk
          }
          this.loadSubData(row);
          this.subFormVisible = false;
        } else {
          this.$message.error(response.message);
          this.subFormVisible = false;
        }
      }).catch(() => {
        this.subData.code=JSON.parse(localStorage.getItem("code"));
        this.subFormVisible = false;
      });
      this.resetForm();

    },


    formSubmit() {
      if (!isBlank(this.formData.code)) {
        if (Number(this.formData.code) + '' === NaN + '') {
          this.$message.error("仓库编码格式错误！")
          return;
        }
      }

      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.formLoading = true;
          this.thirdSys.forEach((item) => {
            if (this.formData.thirdSysFk == item.thirdName) {
              this.formData.thirdSysFk = item.thirdId;
            }
          });
          let data = Object.assign({}, this.formData);
          saveThrWarehouse(data, this.formName)
            .then((response) => {
              this.formLoading = false;
              if (response.code !== 20000) {
                this.$message.error(response.message);
                return false;
              }
              this.$message.success("操作成功");

              this.formVisible = false;
              if (this.formName !== "edit") {
                if (response.data && response.data.id) {
                  data.id = response.data.id;
                  if (this.pidData) {
                    if (!this.pidData.children) {
                      this.$set(this.pidData, "children", []);
                    }
                    this.pidData.children.push(data);
                  } else {
                    this.mergeList.push(data);
                  }
                }
              }

              // 刷新表单
              this.resetForm();
              this.getList();
            })
            .catch(() => {
              this.formLoading = false;

              this.formData.thirdSysFk=this.ThirdSysName;
            });
        }
      });
    },
    // 删除
    handleDel(node, data) {
      if (data.children && data.children.length > 0) {
        this.$alert("请先删除子节点", "提示", {
          confirmButtonText: "确定",
        });
        return false;
      }
      if (data.id) {
        this.$confirm("确认删除该记录吗?", "提示", {
          type: "warning",
        })
          .then(() => {
            this.deleteLoading = true;
            let para = {id: data.id};
            deleteThrWarehouse(para)
              .then((response) => {
                this.deleteLoading = false;
                if (response.code !== 20000) {
                  this.$message.error(response.message);
                  return false;
                }
                this.$message.success("删除成功");
                this.getList();
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex((d) => d.id === data.id);
                children.splice(index, 1);
              })
              .catch(() => {
                this.deleteLoading = false;
              });
          })
          .catch(() => {
            this.$message.info("取消删除");
          });
      }
    },
    getBasicThirdSys() {
      let query = {
        enabled: true,
      };
      getBasicThirdSys(query)
        .then((response) => {
          this.thirdSys = response.data.list || [];
          for(var i=0;i<this.thirdSys.length;i++){
            if(this.thirdSys[i].mainSys){
              this.query.thirdSysFk = this.thirdSys[i].thirdId;
              this.mainThirdSys = this.thirdSys[i].thirdId;
            }
          }
          this.getThirdSysDetail();
          this.getList();
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
        });
    },
    downloadWarehouse() {
      if (null == this.query.thirdSysFk) {
        this.$message.warning("请选择需要下载的第三方系统");
        return;
      }
      let params = {
        thirdSysFk: this.query.thirdSysFk
      }
      download(params).then((res) => {
        if (res.code == 20000) {
          this.$message.success("下载完成");
          this.getList();
        } else {
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.$message.error("下载失败");
      })
    },
    thirdSysFkChange() {
      this.getThirdSysDetail();
    },

    getThirdSysDetail() {
      let query = {
        thirdSysFk: this.query.thirdSysFk,
        key: "warehouseQueryUrl",
      };
      filterDetailByKey(query)
        .then((response) => {
          if (response.code == 20000) {
            if (response.data != null) {
              this.thirdSysDetail = response.data;
            }
          }

        })
        .catch(() => {
          this.loading = false;
          this.list = [];
        });
    },
    getSyncConfig() {
      findConfig()
        .then((response) => {
          if (response.code == 20000) {
            this.configParms = response.data;
          }
        })
        .catch(() => {
        });
    },
  }
  ,
  filters: {
    statusFilterType(status) {
      const statusMap = {
        0: "gray",
        1: "success",
      };
      return statusMap[status];
    }
    ,
    statusFilterName(status) {
      const statusMap = {
        0: "禁用",
        1: "正常",
      };
      return statusMap[status];
    }
    ,
  }
  ,
  mounted() {
  }
  ,
  created() {
    // 加载表格数据
    this.getBasicThirdSys();
    this.getSyncConfig();
    this.getList();
  }
  ,
}
;
</script>

<style type="text/scss" lang="scss">
</style>
