<template>
  <div>
    <el-form :model="formData" :rules="formRules" ref="dataForm" label-width="120px">

      <el-button-group style="display: flex;margin: -40px 0 20px 80%; height: 35px">

        <el-button
          type="primary"
          @click.native="submit('0')"
        >生成单据
        </el-button
        >
      </el-button-group>

      <el-row :gutter="20">
        <el-col :span="11">
          <el-form-item prop="corpOrderId" label="入库单号">
            <el-input v-model="formData.corpOrderId" auto-complete="off" style="width: 90%"
                      :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="actDate" label="单据时间">
            <el-date-picker
              v-model="formData.actDate"
              type="datetime"
              placeholder="日期"
              :disabled="true"
              style="width: 90%; "
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="11">
          <el-form-item prop="locStorageCode" label="当前仓库">
            <el-select v-model="formData.invCode" placeholder="当前仓库信息" @change="locCHange" style="width: 90%">
              <el-option
                v-for="item in curInvOptions"
                :key="item.name"
                :label="item.name"
                :value="item.code">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item class="query-form-item" prop="billType" label="单据类型">
            <el-select v-model="formData.action" placeholder="请选择单据类型" style="width: 90%"
                       @change="actionChange">
              <el-option
                v-for="item in busTypeOptions"
                :key="item.name"
                :label="item.name"
                :value="item.action">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="11">
          <el-form-item class="query-form-item" prop="fromCorp" label="往来信息"
                        v-if="curAction.corpType === 0 || curAction.corpType === 2 || (curAction.corpType === 1 && !curAction.genUnit)">
            <el-select
              v-model="formData.fromCorp"
              filterable
              remote
              clearable="true"
              style="width: 90%"
              reserve-keyword
              placeholder="请输入往来单位"
              :remote-method="findMethod"
              :loading="loading"
            >
              <el-option
                v-for="item in fromOptions"
                :key="item.erpId"
                :label="item.name"
                :value="item.erpId"
              >
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="query-form-item" prop="fromCorp" label="往来信息"
                        v-if="curAction.corpType ==3">
            <el-select v-model="formData.fromInvCode" placeholder="请选择往来仓库信息" clearable="true" style="width: 90%"
            >
              <el-option
                v-for="item in fromInvOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.code
                  }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="fromCorp" label="往来信息:"
                        v-if="curAction.corpType ==1 && curAction.genUnit">
            <el-input v-model="formData.fromCorp" auto-complete="off"
                      clearable
                      style="width: 90%"
                      placeholder="请输入病人住院号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="remark" label="备注:">
            <el-input v-model="formData.remark" auto-complete="off"
                      clearable
                      style="width: 90%"
                      placeholder="请输入备注信息"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table v-loading="detailLoading"
              :data="detailList"
              border
              @selection-change="changeFun"
              style="width: 100%; margin-top: 20px;">
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column
        label="物资名称"
        prop="coName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="规格型号"
        prop="spec"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="批次号"
        prop="batchNo"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="生产日期"
        prop="productDate"
      ></el-table-column>
      <el-table-column
        label="失效日期"
        prop="expireDate"
      ></el-table-column>
      <el-table-column
        label="单据数量"
        prop="count"
      ></el-table-column>
      <el-table-column
        label="价格"
        prop="price"
      ></el-table-column>
      <el-table-column
        label="生产企业"
        prop="manufacturer"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="注册/备案凭证号"
        prop="certCode"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="100" prop="price" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="deleteOrderDetail(scope.$index, scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {filterAllByLoc, filterAllByUser} from "@/api/system/invWarehouse";
import {getBasicUnitMaintains} from "@/api/basic/basicUnitMaintain";
// import {parseTime} from "@/filtres";
import {getLocalJoinByUser} from "@/api/basic/busLocalType";
import {submitOrderWeb} from "@/api/inout/order";
import {orderChange} from "@/api/inout/order";
import {getBizDetailList} from "@/api/inout/orderDetailBiz";
import {filterSubByInv, findByFrom, findInvByUser} from "@/api/system/invSubWarehouse";
import {isBlank} from "@/utils/strUtil";
import {convertDate} from "@/utils/date"
import {findByInvUser} from "@/api/basic/busType";
import {stockOrderChange} from "@/api/inout/stockOrder";

export default {
  name: "DialogcChangeNewOrder",

  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    curRow: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      convertDateFun: convertDate,
      formData: {
        corpOrderId: "",
        code: "",
        actor: "",
        fromCorpId: "",
        fromCorp: null,
        fromType: 2,
        actDate: new Date(),
        action: null,

        fromInvCode: null,


        locStorageCode: null,
        fromSubInvCode: null,
        invWarehouseCode: null,
        mainAction: null
      },


      curInvOptions: [],
      busTypeOptions: [],
      fromInvOptions: [],


      curAction: {
        corpType: 0,
        genUnit: false,
      },
      busTypes: [],
      fromOptions: [],
      loading: false,
      detailList: [],
      storageList: [],
      detailLoading: false,
      subInvList: [],

    }
  },
  methods: {

    submit() {
      if (this.$isBlank(this.formData.action)) {
        this.$message.warning("请选择单据类型！");
        return;
      }
      if ((this.curAction.corpType === 0 || this.curAction.corpType === 2 || (this.curAction.corpType === 1 && !this.curAction.genUnit)) && this.$isBlank(this.formData.fromCorp)) {
        this.$message.error('当前往来信息不能为空');
        return;
      }
      if (this.$isBlank(this.formData.invCode)) {
        this.$message.error("当前分库不能为空");
        return;
      }

      if (this.curAction.corpType === 0 || this.curAction.corpType === 2 || (this.curAction.corpType === 1 && !this.curAction.genUnit && this.$isBlank(this.formData.fromCorp))) {
        this.$message.error("往来单位不能为空");
        return;
      }

      if (this.curAction.corpType == 3 && this.$isBlank(this.formData.fromInvCode)) {
        this.$message.error("往来单位不能为空");
        return;
      }

      if (this.curAction.corpType === 1 && this.$isBlank(this.formData.fromCorp)) {
        this.$message.error('往来单位不能为空');
        return;
      }
      if (this.detailList.length == 0) {
        this.$message.error("产品列表不能为空");
        return;
      }

      // if (this.formData.locStorageCode === this.formData.fromCorp || this.formData.invWarehouseCode === this.formData.fromSubInvCode) {
      //   this.$message.error("当前仓库和往来仓库不能相同！");
      //   return;
      // }

      let products = [];
      this.detailList.forEach(item => {
        let product = {
          relId: item.bindRlFk,
          batchNo: item.batchNo
        };
        products.push(product);
      });

      this.busTypes.forEach(item => {
        if (item.action === this.formData.action) {
          this.formData.mainAction = item.mainAction;
        }
      })
      let tQuery = {
        orderId: this.curRow.billNo,
        corpOrderId: this.curRow.corpOrderId,
        fromCorp: this.formData.fromCorp,
        action: this.formData.action,
        fromInvCode: this.formData.fromInvCode,
        invCode: this.formData.invCode,
        products: products
      };
      stockOrderChange(tQuery)
        .then((response) => {
          if (response.code === 20000) {
            this.$message.success("提交成功");
            this.closeDialog();
          } else {
            this.$message.error(response.message);
          }
          this.loading = false;
        });
    },


    //获取用户仓库列表
    findInvListByUser() {
      this.curInvOptions = [];
      findInvByUser()
        .then(response => {
          this.curInvOptions = response.data || [];
          if (this.curInvOptions != null && this.curInvOptions.length > 0 && this.formData.invWarehouseCode == null) {
            this.formData.invWarehouseCode = this.curInvOptions[0].code;
            this.getBusTypeByInv()
          }
        })
        .catch(() => {
        });
    },


    //根据仓库,用户获取单据类型
    getBusTypeByInv() {
      let query = {
        code: this.formData.invCode,
      };
      findByInvUser(query)
        .then((response) => {
          this.busTypeOptions = response.data || [];
        })
        .catch(() => {
        });
    },


    locCHange() {
      this.formData.action = null;
      this.getBusTypeByInv();
    },


    findSubInvByInv(invCode) {
      this.subInvList = [];
      let query = {
        pcode: invCode
      };
      filterSubByInv(query)
        .then((response) => {
          this.subInvList = response.data || [];
        })
        .catch(() => {
        });
    },

    findStorageMethod(query) {
      if (this.formData.locStorageCode == null)
        return;
      this.fromStorageOptions = [];
      let cQuery = {
        locInvCode: this.formData.locStorageCode,
      };
      filterAllByLoc(cQuery)
        .then((response) => {
          this.fromStorageOptions = response.data || [];
        })
        .catch(() => {
        });
    },
    findMethod(query) {
      this.fromOptions = [];
      let cQuery = {
        key: query,
        corpType: null,
        outType: null,
        page: 1,
        limit: 20
      };
      if (this.curAction.corpType == 3) {//内部科室
        cQuery.corpType = 3;
      } else if (this.curAction.corpType == 2)//供应商信息
      {
        cQuery.corpType = 2;
      } else if (this.curAction.corpType == 0) {
        cQuery.corpType = 2;
      } else return;
      getBasicUnitMaintains(cQuery)
        .then((response) => {
          this.loading = false;
          this.fromOptions = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
        });
    },


    unitChange(row) {
      this.formData.fromCorpId = row.erpId;
      this.formData.fromCorp = row.name;
    },
    actionChange(item) {
      this.curAction = this.getActionItem(item);
      if (this.curAction.corpType == 0 || this.curAction.corpType == 2 || (this.curAction.corpType == 1 && !this.curAction.genUnit)) {
        //1.切换往来单位
        this.formData.fromCorp = null;
        this.findMethod();

      } else if (this.curAction.corpType == 3) {
        //2. 切换往来仓库
        this.formData.fromInvCode = null;
        this.findFromInvList();
      }
    },
    getActionItem(action) {
      for (let i = 0; i < this.busTypeOptions.length; i++) {
        if (this.busTypeOptions[i].action == action) {
          return this.busTypeOptions[i];
        }
      }
    },

    //获取往来仓库列表
    findFromInvList(val) {
      let cQuery = {
        locInvCode: this.formData.invCode,
      };
      findByFrom(cQuery)
        .then((response) => {
          this.fromInvOptions = response.data || [];
          if (val == 1) {
            this.formData.fromInvCode = this.fromInvOptions[0].code;
          }
        })
        .catch(() => {
        });
    },

    changeFun(row) {
      let _this = this;
      _this.multipId = []; //每次改动重置ID
      row.forEach((item) => {
        _this.multipId.push(item.id);
      })
    },


    getStockOrderDetailList(orderId) {
      let query = {
        orderIdFk: orderId
      }
      getBizDetailList(query)
        .then((response) => {
          this.detailLoading = false;
          this.detailList = response.data.list || [];
        })
        .catch(() => {
          this.detailLoading = false;
          this.detailList = [];
        });
    },
    deleteOrderDetail(index) {
      for (let i = 0; i < this.detailList.length; i++) {
        if (index === i) {
          this.detailList.splice(index, 1);
          break
        }
      }
    }
  },
  created() {
    // if (this.$isBlank(this.formData.corpOrderId)) {
    //   let date = new Date();
    //   this.formData.corpOrderId = parseTime(date, '{y}{m}{d}{h}{i}{s}') + Math.ceil(Math.random() * 89 + 10);
    // }
    this.findInvListByUser();
    this.getStockOrderDetailList(this.curRow.billNo);
  }
}
</script>

<style scoped>

</style>
