<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <div>
        <el-button type="primary" @click="submit" v-show="showButton"
          >保存</el-button
        >
        <el-button type="warning" @click="examine" v-show="showCheck"
          >审核</el-button
        >
      </div>
    </div>
    <div class="app-container" v-loading="loading">
      <div
        style="
          justify-content: flex-start;
          margin: 0px 0 12px 0;
          display: flex;
          align-items: center;
        "
      >
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="单据日期：">
            <el-date-picker
              v-model="warehousing_time"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <span style="display: inline-block; margin-top: 8px; font-size: 14px"
            ><span style="color: red; font-size: 14px">*</span>调出仓库：</span
          >
          <el-form-item prop="storehouse_out_id">
            <el-select
              size="small"
              v-model="storehouse_out_id"
              filterable
              placeholder="请选择调出仓库"
              @change="changeHouseList"
            >
              <el-option
                v-for="(option, index) in houseList"
                :key="index"
                :label="option.storehouse_name"
                :value="option.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <span style="display: inline-block; margin-top: 8px; font-size: 14px"
            ><span style="color: red; font-size: 14px">*</span>调入仓库：</span
          >
          <el-form-item prop="storehouse_in_id">
            <el-select
              size="small"
              v-model="storehouse_in_id"
              filterable
              placeholder="请选择调入仓库"
            >
              <el-option
                v-for="(option, index) in houseList"
                :key="index"
                :label="option.storehouse_name"
                :value="option.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-form :rules="tableRules" :model="recordInfo" ref="tableForm">
        <el-table
          :header-cell-style="{
            backgroundColor: 'rgb(245, 247, 250)',
            color: '#606266',
          }"
          :data="recordInfo.recordData"
          border
        >
          >

          <el-table-column align="center" width="230">
            <template slot="header" slot-scope="scope">
              商品名称<span style="color: red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordData.' + scope.$index + '.name'"
                :rules="tableRules.name"
              >
                <el-select
                  @blur="selectGoodName"
                  v-model="scope.row.name"
                  style="width: 200"
                  filterable
                  placeholder="请选择商品"
                  @change="changeName"
                  @input="changeGoodName(scope.$index)"
                  :disabled="disabled"
                >
                  <el-option
                    v-for="(item, index) in tabList"
                    :key="index"
                    :label="item.project_name"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" width="200">
            <template slot="header" slot-scope="scope">
              <span>商品类型<span style="color: red">*</span></span>
            </template>

            <template slot-scope="scope">
              <el-form-item style="padding-top: 20px">
                <el-input
                  v-model="scope.row.project_type"
                  :disabled="true"
                  style="width: 180px"
                ></el-input>
                <div style="height: 20px;visibility: hidden">/</div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" width="250">
            <template slot="header" slot-scope="scope">
              <span>规格<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">
              <el-form-item style="padding-top: 20px">
                <el-input
                  v-model="scope.row.second_specification_name"
                  style="width: 200px"
                  :disabled="true"
                ></el-input>
                <div style="height: 20px;visibility: hidden">/</div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" width="250">
            <template slot="header" slot-scope="scope">
              <span>调拨数量<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                style="padding-top: 20px"
                :prop="'recordData.' + scope.$index + '.count'"
                :rules="tableRules.count"
              >
                <el-input
                  v-model="scope.row.count"
                  style="width: 100px"
                  @input="
                    selectCount(
                      scope.row.project_id,
                      scope.row.sencond_unit,
                      scope.row.is_source,
                      scope.row.count,
                      scope.$index
                    )
                  "
                ></el-input>
                <el-select
                  v-model="scope.row.sencond_unit"
                  style="width: 100px"
                  filterable
                  placeholder="请选择"
                  :disabled="disabled"
                >
                  <el-option
                    v-for="(item, index) in scope.row.unitList"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
                <div style="height: 20px;visibility: hidden">/</div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="库存总数" align="center" width="200">
            <template slot="header" slot-scope="scope">
              <span>库存总数<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">
              <el-form-item style="padding-top: 20px">
                <el-input
                  v-model="scope.row.second_total"
                  style="width: 150px"
                  :disabled="true"
                ></el-input>
                <div style="visibility: hidden;height: 20px;">/</div>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="备注" align="center" width="200">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remake"
                style="width: 160px"
              ></el-input>
              <div style="visibility: hidden;height: 20px;">/</div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="190px">
            <template slot-scope="scope">
              <el-tooltip class="item" content="新增" placement="top-start">
                <el-button
                  icon="el-icon-plus"
                  size="small"
                  type="primary"
                  @click="toAdd(scope.row)"
                >
                </el-button>
              </el-tooltip>

              <el-tooltip class="item" content="删除" placement="top-start">
                <el-button
                  icon="el-icon-delete"
                  size="small"
                  type="danger"
                  @click="toDelete(scope.row, scope.$index)"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
  </div>
</template>

<script>
import BreadCrumb from "@/xt_pages/components/bread-crumb";
import { uParseTime } from "@/utils/tools";
import {
  getSencondeGoodList,
  saveSencondOrder,
  checkSecondOrder,
  getStoreHouseGoodList,
  getSumSecondeCount,
} from "@/api/seconde";
export default {
  components: {
    BreadCrumb,
  },
  data() {
    return {
      crumbs: [
        { path: false, name: "库房管理" },
        { path: "/stock/warehousequery", name: "新增调拨" },
      ],
      value1: "",
      total: 0,
      page: 1,
      limit: 10,
      tableData: [{}, {}],
      formInline: {
        user: "",
        region: "",
      },
      currentIndex: 0,
      tableRules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        count: [
          { required: true, message: "调拨数量不能为空", trigger: "blur" },
        ],
      },
      goodType: [],
      manufacturerList: [],
      goodList: [],
      loading: false,
      list: [],
      configlist: {},
      recordInfo: {
        recordData: [],
      },
      drugList: [],
      goodTypeList: [],
      drugTypeList: [],
      houseList: [],
      tabList: [],
      disabled: false,
      storehouse_out_id: "",
      storehouse_in_id: "",
      loading: false,
      warehousing_time: "",
      showButton: true,
      showCheck: false,
    };
  },

  methods: {
    // 初始化数据
    init() {},

    // 反审核
    approval() {},

    // 审核
    examine() {
      this.loading = true;
      var array = [];
      array.push(this.id);
      var ids = array.join(",");

      checkSecondOrder(ids).then((response) => {
        if (response.data.state == 1) {
          var msg = response.data.data.msg;
          this.loading = false;
          if (msg == 1) {
            this.$message.success("审核成功!");
            this.$router.push({ path: "/stock/inventoryTransfer" });
          }
          if (msg == 2) {
            var good_name = response.data.data.good_name;
            var specification_name = response.data.data.specification_name;
            var storehose_name = response.data.data.storehose_name;

            this.$message.error(
              storehose_name +
                " " +
                good_name +
                "*" +
                specification_name +
                "库存不足,无法调拨,请修改调拨数量!"
            );
          }
          if (msg == 3) {
            var drug_name = response.data.data.drug_name;
            var dose = response.data.data.dose;
            var dose_unit = response.data.data.dose_unit;
            var min_number = response.data.data.min_number;
            var min_unit = response.data.data.min_unit;
            var max_unit = response.data.data.max_unit;
            var str =
              drug_name +
              " " +
              dose +
              dose_unit +
              "*" +
              min_number +
              min_unit +
              "/" +
              max_unit;
            var storehose_name = response.data.data.storehose_name;
            this.$message.error(
              storehose_name + " " + str + "库存不足,无法调拨,请修改调拨数量!"
            );
          }
        }
      });
    },
    // 表单添加
    toAdd() {
      const tempObj = {};
      tempObj["name"] = "";
      tempObj["project_name"] = "";
      tempObj["project_type"] = "";
      tempObj["second_specification_name"] = "";
      tempObj["sencond_unit"] = "";
      tempObj["count"] = "";
      tempObj["second_total"] = "";
      tempObj["is_source"] = 0;
      tempObj["remake"] = "";
      tempObj["project_id"] = 0;
      tempObj["min_price"] = 0;
      this.recordInfo.recordData.push(tempObj);
    },

    // 删除
    toDelete(row, index) {
      if (this.recordInfo.recordData.length <= 1) {
        this.$message.error("只有一条记录的时候无法删除");
        return;
      } else {
        this.recordInfo.recordData.splice(index, 1);
      }
    },

    // 详情查看
    toDetails() {},

    // 表单全选
    handleSelectionChange() {},

    // 页表操作
    handleSizeChange(val) {
      this.limit = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.init();
    },

    // 表格样式
    changColor({ rowIndex }) {
      if (rowIndex % 2 == 1) {
        return {
          backgroundColor: "#C4E1FF",
          color: "#303133",
        };
      } else {
        return {
          backgroundColor: "#ACD6FF",
          color: "#303133",
        };
      }
    },
    //获取基本数据信息
    getlist() {
      getSencondeGoodList().then((response) => {
        if (response.data.state == 1) {
          var houseList = response.data.data.houseList;
          this.houseList = houseList;
        }
      });
    },
    getTime(val, temp) {
      if (val != 0) {
        return uParseTime(val, temp);
      } else {
        return "";
      }
    },
    submit() {
      this.loading = true;
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.storehouse_out_id <= 0) {
        this.$message.error("调出仓库不能为空!");
        this.loading = false;
        loading.close();
        return;
      }
      if (this.storehouse_in_id <= 0) {
        this.$message.error("调入仓库不能为空!");
        this.loading = false;
        loading.close();
        return;
      }
      this.$refs["tableForm"].validate((valid) => {
        if (valid) {
          const array = this.recordInfo.recordData;

          for (let i = 0; i < array.length; i++) {
            array[i].count = parseInt(array[i].count);
            array[i].second_total = array[i].second_total.toString();
          }
          const params = {
            stockIn: this.recordInfo.recordData,
          };
          var storehouse_in_id = parseInt(this.storehouse_in_id);
          var storehouse_out_id = parseInt(this.storehouse_out_id);

          var warehouse_time = this.warehousing_time;

          console.log("@3232332323232", warehouse_time);

          saveSencondOrder(
            params,
            warehouse_time,
            storehouse_in_id,
            storehouse_out_id
          ).then((response) => {
            if (response.data.state == 1) {
              this.showCheck = true;
              this.showButton = false;
              var warehousingInfo = response.data.data.warehousingInfo;
              this.$message.success("保存成功");
              this.loading = false;
              loading.close();
              this.id = response.data.data.id;
            } else {
              this.$message.error("保存失败");
              loading.close();
            }
          });
        } else {
          return false;
        }
      });
    },
    changeGoodName(val) {
      this.currentIndex = val;
    },
    selectGoodName(val) {
      if (this.storehouse_out_id == "") {
        this.$message.error("请先选择调出仓库!");
        return;
      }
    },
    changeName(val) {
      for (let i = 0; i < this.recordInfo.recordData.length; i++) {
        if (this.currentIndex == i) {
          this.recordInfo.recordData[i].project_id = val.id;
          this.recordInfo.recordData[i].is_source = val.is_source;
          this.recordInfo.recordData[i].name = val.name;
          this.recordInfo.recordData[i].project_name = val.project_name;
          this.recordInfo.recordData[i].project_type = val.project_type;
          this.recordInfo.recordData[i].second_specification_name =
            val.second_specification_name;
          this.recordInfo.recordData[i].second_total = val.second_total;
          this.recordInfo.recordData[i].sencond_unit = val.sencond_unit;
          this.recordInfo.recordData[i].min_price = val.min_price;
          if (val.count == NaN) {
            this.recordInfo.recordData[i].count = "";
          } else {
            this.recordInfo.recordData[i].count = val.count ? val.count : "";
          }
          this.recordInfo.recordData[i].unitList = val.unitList;
        }
      }
    },
    getWarehoseInfo(arr, max_unit, min_unit, min_number) {
      var total = 0;
      var max_str = "";
      var min_str = "";
      if (arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          total += parseInt(arr[i].stock_max_number + arr[i].stock_min_number);
        }
      }
      if (total < min_number) {
        min_str = total + min_unit;
      }
      if (total == 0) {
        min_str = "";
        max_str = "";
      }
      if (total >= min_number) {
        if (parseInt(total / min_number) != 0) {
          max_str = parseInt(total / min_number) + max_unit;
        }
        if (total % min_number != 0) {
          min_str = (total % min_number) + min_unit;
        }
      }
      return max_str + min_str;
    },
    getTotalStockCount(arr) {
      var total_count = 0;
      for (let i = 0; i < arr.length; i++) {
        total_count += arr[i].stock_count;
      }
      return total_count;
    },
    changeHouseList() {
      var params = {
        storehouse_out_id: this.storehouse_out_id,
      };
      this.tabList = [];
      getStoreHouseGoodList(params).then((response) => {
        var drugList = response.data.data.drugList;
        this.drugList = drugList;
        var goodList = response.data.data.goodList;
        this.goodList = goodList;
        var manufactuerList = response.data.data.manufacturerList;

        var goodTypeList = response.data.data.goodTypeList;
        this.goodTypeList = goodTypeList;
        var drugTypeList = response.data.data.drugTypeList;
        this.drugTypeList = drugTypeList;

        for (let i = 0; i < drugList.length; i++) {
          for (let j = 0; j < manufactuerList.length; j++) {
            if (drugList[i].manufacturer == manufactuerList[j].id) {
              drugList[i].manufacturer = manufactuerList[j].manufacturer_name;
            }
          }
          for (let z = 0; z < drugList[i].drug_warehouse_info.length; z++) {
            if (
              drugList[i].max_unit ==
              drugList[i].drug_warehouse_info[z].max_unit
            ) {
              drugList[i].drug_warehouse_info[z].stock_max_number =
                drugList[i].drug_warehouse_info[z].stock_max_number *
                drugList[i].min_number;
            }
          }
          for (let y = 0; y < this.drugTypeList.length; y++) {
            if (drugList[i].drug_type == this.drugTypeList[y].value) {
              drugList[i].drug_type = this.drugTypeList[y].name;
            }
          }
          drugList[i].name = drugList[i].drug_name;
          drugList[i].project_name =
            drugList[i].drug_name +
            " " +
            drugList[i].dose +
            drugList[i].dose_unit +
            "*" +
            drugList[i].min_number +
            drugList[i].min_unit +
            "/" +
            drugList[i].max_unit +
            " " +
            drugList[i].manufacturer;
          drugList[i].project_type = drugList[i].drug_type;
          drugList[i].second_specification_name =
            drugList[i].dose +
            drugList[i].dose_unit +
            "*" +
            drugList[i].min_number +
            drugList[i].min_unit +
            "/" +
            drugList[i].max_unit;
          drugList[i].second_total = this.getWarehoseInfo(
            drugList[i].drug_warehouse_info,
            drugList[i].max_unit,
            drugList[i].min_unit,
            drugList[i].min_number
          );
          drugList[i].is_source = 1;
          drugList[i].count = "";
          drugList[i].remake = "";
          drugList[i].min_price = drugList[i].min_price;
          if (drugList[i].max_unit != drugList[i].min_unit) {
            drugList[i].unitList = [
              { id: 1, name: "" },
              { id: 2, name: "" },
            ];
          }
          if (drugList[i].max_unit == drugList[i].min_unit) {
            drugList[i].unitList = [{ id: 1, name: "" }];
          }

          drugList[i].sencond_unit = drugList[i].max_unit;
          for (let j = 0; j < drugList[i].unitList.length; j++) {
            if (drugList[i].max_unit != drugList[i].min_unit) {
              drugList[i].unitList[0].name = drugList[i].max_unit;
              drugList[i].unitList[1].name = drugList[i].min_unit;
            }
            if (drugList[i].max_unit == drugList[i].min_unit) {
              drugList[i].unitList[0].name = drugList[i].max_unit;
            }
          }
          this.tabList.push(drugList[i]);
        }

        for (let i = 0; i < goodList.length; i++) {
          for (let j = 0; j < manufactuerList.length; j++) {
            if (goodList[i].manufacturer == manufactuerList[j].id) {
              goodList[i].manufacturer = manufactuerList[j].manufacturer_name;
            }
          }
          for (let y = 0; y < this.goodTypeList.length; y++) {
            if (goodList[i].good_type_id == this.goodTypeList[y].id) {
              goodList[i].good_type_id = this.goodTypeList[y].type_name;
            }
          }
          goodList[i].name = goodList[i].good_name;
          goodList[i].project_name =
            goodList[i].good_name +
            " " +
            goodList[i].specification_name +
            " " +
            goodList[i].manufacturer;
          goodList[i].project_type = goodList[i].good_type_id;
          goodList[i].second_specification_name =
            goodList[i].specification_name;
          goodList[i].second_total = this.getTotalStockCount(
            goodList[i].good_warehouse_info
          );
          goodList[i].count = "";
          goodList[i].is_source = 2;
          goodList[i].name = goodList[i].good_name;
          goodList[i].unitList = [{ id: 1, name: "" }];
          goodList[i].sencond_unit = goodList[i].packing_unit;
          goodList[i].remake = "";
          goodList[i].min_price = goodList[i].retail_price;
          for (let j = 0; j < goodList[i].unitList.length; j++) {
            goodList[i].unitList[0].name = goodList[i].packing_unit;
          }
          this.tabList.push(goodList[i]);
        }
      });
    },
    selectCount(project_id, sencond_unit, is_source, count, index) {
      var params = {
        project_id: project_id,
        sencond_unit: sencond_unit,
        is_source: parseInt(is_source),
        count: parseInt(count),
        storehouse_out_id: this.storehouse_out_id,
      };
      getSumSecondeCount(params).then((response) => {
        if (response.data.state == 1) {
          var msg = response.data.data.msg;
          if (msg == 2) {
            this.$message.error("调拨数量不能大于库存总量!");
            for (let i = 0; i < this.recordInfo.recordData.length; i++) {
              if (index == i) {
                this.recordInfo.recordData[i].count = "";
              }
            }
          }
        }
      });
    },
  },
  created() {
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();
    this.warehousing_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    const tempObj = {};
    tempObj["name"] = "";
    tempObj["project_name"] = "";
    tempObj["project_type"] = "";
    tempObj["second_specification_name"] = "";
    tempObj["sencond_unit"] = "";
    tempObj["count"] = "";
    tempObj["second_total"] = "";
    tempObj["remake"] = "";
    tempObj["is_source"] = 0;
    tempObj["project_id"] = 0;
    tempObj["min_price"] = 0;
    this.recordInfo.recordData.push(tempObj);
    this.getlist();
  },
};
</script>

<style rel="stylesheet/css" lang="scss" scoped>
</style>
<style scoped>
/deep/ .el-table__body {
  width: 100% !important;
}
/deep/ .el-table__header {
  width: 100% !important;
}

/deep/ .el-table--scrollable-x .el-table__body-wrapper {
  overflow: auto;
}
/deep/ .gutter {
  width: 15px !important;
  display: inline-block !important;
}
/deep/ .el-table__fixed-right-patch {
  width: 15px !important;
}

/deep/ .el-table__fixed-right {
  bottom: 0 !important;
  left: auto;
  right: 0;
}
/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 15px !important;
  height: 15px !important;
}
</style>